wayBetter for X

This commit is contained in:
CRTkafa 2026-09-30 23:01:13 +00:00
commit ae6ed24700
720 changed files with 147465 additions and 0 deletions

265
apps/api/src/app.test.ts Normal file
View file

@ -0,0 +1,265 @@
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { SITE_LANGUAGES, createApp } from './app';
let dir: string;
const HOTFIX_BODY = '{"version":3,"expires":"2099-01-01T00:00:00Z","minNative":"0.2.0","selectors":{"composer":"div"},"flags":{}}';
beforeAll(async () => {
dir = await mkdtemp(join(tmpdir(), 'bt-api-'));
await mkdir(join(dir, 'native'), { recursive: true });
await writeFile(join(dir, 'native', 'latest.json'), JSON.stringify({
version: '0.3.0',
notes: 'Tabs and splits',
pubDate: '2026-09-27T12:00:00Z',
platforms: { 'windows-x86_64': { url: 'https://example.invalid/Better-Twttr_0.3.0_x64.zip', signature: 'c2ln' } },
}));
await mkdir(join(dir, 'hotfix'), { recursive: true });
await writeFile(join(dir, 'hotfix', 'stable.json'), HOTFIX_BODY);
await writeFile(join(dir, 'hotfix', 'stable.json.sig'), 'c2lnbmF0dXJl');
await writeFile(join(dir, 'hotfix', 'beta.json'), '{"version":1,"expires":"2099-01-01T00:00:00Z","minNative":"0.1.0","script":"alert(1)"}');
await writeFile(join(dir, 'hotfix', 'beta.json.sig'), 'c2ln');
});
afterAll(() => rm(dir, { recursive: true, force: true }));
describe('update endpoint', () => {
test('returns the Tauri update payload for an older client', async () => {
const res = await createApp({ releasesDir: dir }).request('/v1/updates/windows/x86_64/0.2.0');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ version: '0.3.0', notes: 'Tabs and splits', pub_date: '2026-09-27T12:00:00Z', url: 'https://example.invalid/Better-Twttr_0.3.0_x64.zip', signature: 'c2ln' });
});
test('returns 204 when up to date or the platform is unpublished', async () => {
const app = createApp({ releasesDir: dir });
expect((await app.request('/v1/updates/windows/x86_64/0.3.0')).status).toBe(204);
expect((await app.request('/v1/updates/darwin/aarch64/0.2.0')).status).toBe(204);
});
test('rejects malformed parameters', async () => {
expect((await createApp({ releasesDir: dir }).request('/v1/updates/windows/x86_64/latest')).status).toBe(400);
});
test('returns 204 when nothing has been published yet', async () => {
expect((await createApp({ releasesDir: join(dir, 'missing') }).request('/v1/updates/windows/x86_64/0.1.0')).status).toBe(204);
});
test('works under a base path', async () => {
const app = createApp({ releasesDir: dir, basePath: '/x/api' });
expect((await app.request('/x/api/health')).status).toBe(200);
});
});
describe('download redirect', () => {
test('302s to the current Windows installer', async () => {
const res = await createApp({ releasesDir: dir }).request('/v1/download/windows/latest');
expect(res.status).toBe(302);
expect(res.headers.get('location')).toBe('https://example.invalid/Better-Twttr_0.3.0_x64.zip');
});
test('404s when nothing is published for the target', async () => {
expect((await createApp({ releasesDir: dir }).request('/v1/download/darwin/latest')).status).toBe(404);
});
});
describe('hotfix channel', () => {
test('serves the published body byte-for-byte', async () => {
const res = await createApp({ releasesDir: dir }).request('/v1/hotfix/stable');
expect(res.status).toBe(200);
expect(res.headers.get('content-type')).toContain('application/json');
expect(res.headers.get('cache-control')).toBe('public, max-age=60');
expect(await res.text()).toBe(HOTFIX_BODY);
});
test('serves the detached signature', async () => {
const res = await createApp({ releasesDir: dir }).request('/v1/hotfix/stable.sig');
expect(res.status).toBe(200);
expect(await res.text()).toBe('c2lnbmF0dXJl');
});
test('rejects unknown channels and path tricks', async () => {
const app = createApp({ releasesDir: dir });
expect((await app.request('/v1/hotfix/nightly')).status).toBe(400);
expect((await app.request('/v1/hotfix/..%2Fnative%2Flatest')).status).toBe(400);
});
test('never serves a body that fails the schema', async () => {
const app = createApp({ releasesDir: dir });
expect((await app.request('/v1/hotfix/beta')).status).toBe(404);
expect((await app.request('/v1/hotfix/beta.sig')).status).toBe(404);
});
test('404s when nothing is published', async () => {
expect((await createApp({ releasesDir: join(dir, 'missing') }).request('/v1/hotfix/stable')).status).toBe(404);
});
test('works under a base path', async () => {
const res = await createApp({ releasesDir: dir, basePath: '/x/api' }).request('/x/api/v1/hotfix/stable.sig');
expect(res.status).toBe(200);
});
});
describe('site pages', () => {
test('/x gets its trailing slash (relative Location) and the API still wins over the site', async () => {
const app = createApp({ releasesDir: dir, web: async c => c.text('site') });
const res = await app.request('/x');
expect(res.status).toBe(301);
expect(res.headers.get('location')).toBe('x/');
expect(await (await app.request('/x/')).text()).toBe('site');
expect((await app.request('/v1/updates/windows/x86_64/0.2.0')).status).toBe(200);
});
test('the old /twttr address moves to /x for good: the page, deep paths and queries', async () => {
const at = (base: string, path: string) => new URL(path, `https://waybetter.fyi${base}`).href.slice('https://waybetter.fyi'.length);
for (const basePath of ['', '/mounted']) {
const app = createApp({ releasesDir: dir, basePath, web: async c => c.text('site') });
for (const [from, to] of [
['/twttr', '/x/'],
['/twttr/', '/x/'],
['/twttr?ref=old', '/x/?ref=old'],
['/twttr/index.html', '/x/index.html'],
['/twttr/a/b/c.png?v=3', '/x/a/b/c.png?v=3'],
] as const) {
const res = await app.request(`${basePath}${from}`);
expect(res.status).toBe(301);
expect(at(`${basePath}${from}`, res.headers.get('location')!)).toBe(`${basePath}${to}`);
}
}
});
test('the store galleries get their trailing slash too', async () => {
const app = createApp({ releasesDir: dir, web: async c => c.text('site') });
for (const page of ['themes', 'plugins']) {
const res = await app.request(`/${page}`);
expect(res.status).toBe(301);
expect(res.headers.get('location')).toBe(`${page}/`);
expect(await (await app.request(`/${page}/`)).text()).toBe('site');
}
});
test('the Store: /store and its pages get their trailing slash, files are left to the site', async () => {
const at = (base: string, path: string) => new URL(path, `https://waybetter.fyi${base}`).href.slice('https://waybetter.fyi'.length);
for (const basePath of ['', '/mounted']) {
const app = createApp({ releasesDir: dir, basePath, web: async c => c.text(`site ${c.req.path}`) });
for (const [from, to, status] of [
['/store', '/store/', 301],
['/store/submit', '/store/submit/', 301],
['/store/themes/nord', '/store/themes/nord/', 301],
['/store/plugins/thread-reader', '/store/plugins/thread-reader/', 301],
// One kind's listing is the storefront with that filter.
['/store/themes', '/store/?kind=theme', 302],
['/store/themes/', '/store/?kind=theme', 302],
['/store/plugins', '/store/?kind=plugin', 302],
['/store/plugins/', '/store/?kind=plugin', 302],
] as const) {
const res = await app.request(`${basePath}${from}`);
expect(res.status).toBe(status);
expect(at(`${basePath}${from}`, res.headers.get('location')!)).toBe(`${basePath}${to}`);
}
// Pages, and the files the apps download: untouched, straight to the static handler.
for (const path of [
'/store/', '/store/submit/', '/store/themes/nord/', '/store/plugins/thread-reader/',
'/store/catalog.json', '/store/catalog.json.sig', '/store/themes/nord.json',
'/store/plugins/bt-thread-reader.plugin.js', '/store/previews/theme-nord.svg',
]) {
const res = await app.request(`${basePath}${path}`);
expect(res.status).toBe(200);
expect(await res.text()).toBe(`site ${basePath}${path}`);
}
}
});
test('a missing page is the 404 page for browsers, and JSON for programs and the API', async () => {
const page = join(dir, '404.html');
await writeFile(page, '<!doctype html><base href="/" /><title>Page not found</title>');
const html = { headers: { accept: 'text/html,application/xhtml+xml' } };
const app = createApp({ releasesDir: dir, notFoundPage: page, web: async (_c, next) => next() });
const res = await app.request('/store/themes/nope/', html);
expect(res.status).toBe(404);
expect(res.headers.get('content-type')).toContain('text/html');
expect(await res.text()).toContain('<title>Page not found</title>');
// The apps and the updater never ask for HTML: their answer stays JSON.
const json = await app.request('/store/themes/nope.json');
expect(json.status).toBe(404);
expect(await json.json()).toEqual({ error: 'not found' });
// API paths answer JSON even to a browser.
const api = await app.request('/v1/nope', html);
expect(api.status).toBe(404);
expect(api.headers.get('content-type')).toContain('application/json');
// Under a path prefix the page's links still start at the site's root.
const mounted = createApp({ releasesDir: dir, basePath: '/mounted', notFoundPage: page, web: async (_c, next) => next() });
expect(await (await mounted.request('/mounted/nope', html)).text()).toContain('<base href="/mounted/"');
// Without a built page there is still an answer.
const bare = await createApp({ releasesDir: dir, notFoundPage: join(dir, 'missing.html'), web: async (_c, next) => next() }).request('/nope', html);
expect(bare.status).toBe(404);
expect(await bare.json()).toEqual({ error: 'not found' });
});
});
describe('site languages', () => {
const at = (base: string, path: string) => new URL(path, `https://waybetter.fyi${base}`).href.slice('https://waybetter.fyi'.length);
const html = { headers: { accept: 'text/html,application/xhtml+xml' } };
test('the API knows exactly the languages the site is published in', () => {
const web = join(import.meta.dir, '../../web');
const listed = /export const LANGUAGES = \[([^\]]+)\]/.exec(readFileSync(join(web, 'site.config.ts'), 'utf8'))![1]!.split(',').map(code => code.trim().replace(/'/g, ''));
expect(listed[0]).toBe('en');
expect([...SITE_LANGUAGES]).toEqual(listed.slice(1));
});
test('/xx gets its trailing slash, and every page redirect exists under a language', async () => {
for (const basePath of ['', '/mounted']) {
const app = createApp({ releasesDir: dir, basePath, web: async c => c.text(`site ${c.req.path}`) });
for (const [from, to, status] of [
['/tr', '/tr/', 301],
['/ar', '/ar/', 301],
['/zh-Hant', '/zh-Hant/', 301],
['/tr?ref=x', '/tr/', 301],
['/tr/x', '/tr/x/', 301],
['/ja/themes', '/ja/themes/', 301],
['/de/plugins', '/de/plugins/', 301],
['/tr/store', '/tr/store/', 301],
['/tr/store/submit', '/tr/store/submit/', 301],
['/hi/store/plugins/thread-reader', '/hi/store/plugins/thread-reader/', 301],
['/tr/store/themes', '/tr/store/?kind=theme', 302],
['/tr/store/plugins/', '/tr/store/?kind=plugin', 302],
// Another spelling of a language's code moves to the folder's own, path and query kept.
['/TR', '/tr/', 301],
['/zh-hant/', '/zh-Hant/', 301],
['/zh-hant/store/themes/nord/?q=1', '/zh-Hant/store/themes/nord/?q=1', 301],
['/ZH-HANT/x/index.html', '/zh-Hant/x/index.html', 301],
] as const) {
const res = await app.request(`${basePath}${from}`);
expect([from, res.status]).toEqual([from, status]);
expect([from, at(`${basePath}${from}`, res.headers.get('location')!)]).toEqual([from, `${basePath}${to}`]);
}
// The pages themselves, and folders that only look like a language, go straight to the site.
for (const path of ['/tr/', '/tr/x/', '/zh-Hant/store/', '/ar/store/plugins/thread-reader/', '/og/home.png', '/x/']) {
const res = await app.request(`${basePath}${path}`);
expect([path, res.status, await res.text()]).toEqual([path, 200, `site ${basePath}${path}`]);
}
}
});
test('an unknown language prefix is a 404, with or without the slash', async () => {
const page = join(dir, '404.html');
await writeFile(page, '<!doctype html><base href="/" /><title>Page not found</title>');
const app = createApp({ releasesDir: dir, notFoundPage: page, web: async (_c, next) => next() });
for (const path of ['/xx', '/xx/', '/xx/store/', '/en', '/en/', '/en-GB/', '/zh-Hans/', '/pt-BR']) {
const res = await app.request(path, html);
expect([path, res.status]).toEqual([path, 404]);
expect([path, res.headers.get('location')]).toEqual([path, null]);
expect(await res.text()).toContain('<title>Page not found</title>');
}
});
test('a missing page under a language is that language\'s 404 page', async () => {
const page = join(dir, '404.html');
await writeFile(page, '<!doctype html><base href="/" /><title>Page not found</title>');
await mkdir(join(dir, 'tr'), { recursive: true });
await writeFile(join(dir, 'tr', '404.html'), '<!doctype html><html lang="tr"><base href="/tr/" /><title>Sayfa bulunamadı</title>');
const app = createApp({ releasesDir: dir, notFoundPage: page, web: async (_c, next) => next() });
const res = await app.request('/tr/store/themes/nope/', html);
expect(res.status).toBe(404);
expect(await res.text()).toContain('<title>Sayfa bulunamadı</title>');
// A language whose page is not built yet, and English, answer with the English page.
expect(await (await app.request('/ja/nope', html)).text()).toContain('<title>Page not found</title>');
expect(await (await app.request('/nope', html)).text()).toContain('<title>Page not found</title>');
// Programs keep the JSON answer.
expect(await (await app.request('/tr/store/catalog.json')).json()).toEqual({ error: 'not found' });
// Under a path prefix the links still start at the language's home.
const mounted = createApp({ releasesDir: dir, basePath: '/mounted', notFoundPage: page, web: async (_c, next) => next() });
expect(await (await mounted.request('/mounted/tr/nope', html)).text()).toContain('<base href="/mounted/tr/"');
});
});

185
apps/api/src/app.ts Normal file
View file

@ -0,0 +1,185 @@
import { Channel, Hotfix, NativeRelease, UpdateArch, UpdateTarget, pickUpdate, Semver } from '@better-twttr/contracts';
import { Hono, type MiddlewareHandler } from 'hono';
import { readFile, stat } from 'node:fs/promises';
import { dirname, join } from 'node:path';
export type ApiConfig = {
/** Directory holding published release metadata (`native/latest.json`). */
releasesDir: string;
/** Mount point, e.g. "" for api.example or "/x/api" when served under a path. */
basePath?: string;
version?: string;
/** Static handler for the landing page (served for every non-API path). */
web?: MiddlewareHandler;
/** The site's 404 page (apps/web/dist/404.html), shown to browsers for addresses that do not exist. */
notFoundPage?: string;
/** The site's languages besides English, each published under /<code>/ (default: SITE_LANGUAGES). */
languages?: readonly string[];
};
/**
* The languages the site is published in besides English (apps/web/site.config.ts LANGUAGES; the
* test keeps the two lists equal). English lives at the root, every other language under its code:
* /tr/, /tr/x/, /zh-Hant/store/…
*/
export const SITE_LANGUAGES = ['ja', 'es', 'ar', 'id', 'de', 'pt', 'tr', 'fr', 'th', 'ko', 'nl', 'vi', 'zh-Hant', 'it', 'hi', 'ru'] as const;
/**
* The update API. Privacy rule: no handler reads client addresses (Cloudflare's
* CF-Connecting-IP / X-Forwarded-For included) and nothing is logged per request.
*/
export function createApp(config: ApiConfig) {
const app = config.basePath ? new Hono().basePath(config.basePath) : new Hono();
const latestNative = cachedJson(join(config.releasesDir, 'native', 'latest.json'), value => NativeRelease.parse(value));
app.use('*', async (c, next) => {
await next();
c.header('Referrer-Policy', 'no-referrer');
c.header('X-Content-Type-Options', 'nosniff');
});
app.get('/health', c => c.json({ ok: true, version: config.version ?? 'dev' }));
// Tauri updater dynamic endpoint: {{target}}/{{arch}}/{{current_version}} → 200 JSON or 204.
app.get('/v1/updates/:target/:arch/:current', async c => {
const target = UpdateTarget.safeParse(c.req.param('target'));
const arch = UpdateArch.safeParse(c.req.param('arch'));
const current = Semver.safeParse(c.req.param('current'));
if (!target.success || !arch.success || !current.success) return c.json({ error: 'invalid target, arch or version' }, 400);
const release = await latestNative();
const update = release ? pickUpdate(release, target.data, arch.data, current.data) : null;
c.header('Cache-Control', 'public, max-age=60');
return update ? c.json(update) : c.body(null, 204);
});
// Stable download link for the landing page: 302 to the current signed installer.
app.get('/v1/download/:target/latest', async c => {
const target = UpdateTarget.safeParse(c.req.param('target'));
if (!target.success) return c.json({ error: 'invalid target' }, 400);
const release = await latestNative();
const artifact = release?.platforms[`${target.data}-x86_64`];
if (!artifact) return c.json({ error: 'no release published yet' }, 404);
c.header('Cache-Control', 'public, max-age=60');
return c.redirect(artifact.url, 302);
});
// Signed data-only hotfix channel. Bytes are served exactly as published (the detached minisign
// signature covers them); the body is still schema-checked so a broken upload is never served.
const hotfixFiles = new Map<string, () => Promise<Buffer | null>>();
const hotfixFile = (name: string) => {
let reader = hotfixFiles.get(name);
if (!reader) hotfixFiles.set(name, reader = cachedBytes(join(config.releasesDir, 'hotfix', name)));
return reader();
};
app.get('/v1/hotfix/:channel', async c => {
const param = c.req.param('channel');
const signature = param.endsWith('.sig');
const channel = Channel.safeParse(signature ? param.slice(0, -4) : param);
if (!channel.success) return c.json({ error: 'invalid channel' }, 400);
const body = await hotfixFile(`${channel.data}.json`);
if (!body || !isValidHotfix(body)) return c.json({ error: 'no hotfix published' }, 404);
c.header('Cache-Control', 'public, max-age=60');
if (signature) {
const sig = await hotfixFile(`${channel.data}.json.sig`);
if (!sig) return c.json({ error: 'no hotfix published' }, 404);
return c.body(new Uint8Array(sig), 200, { 'Content-Type': 'text/plain; charset=utf-8' });
}
return c.body(new Uint8Array(body), 200, { 'Content-Type': 'application/json; charset=utf-8' });
});
const languages = config.languages ?? SITE_LANGUAGES;
if (config.web) {
// A language's folder is its code exactly (/zh-Hant/): another spelling of it (/zh-hant/store/,
// /TR) moves to that one, path and query kept. Anything else that only looks like a language
// (/xx/) is no page: it falls through to the static handler and ends as a 404.
const spelled = new Map(languages.map(code => [code.toLowerCase(), code]));
app.get('*', async (c, next) => {
const [first = '', ...rest] = c.req.path.slice((config.basePath ?? '').length + 1).split('/');
const code = spelled.get(first.toLowerCase());
if (!code || code === first) return next();
return c.redirect(`${'../'.repeat(rest.length)}${code}/${rest.join('/')}${new URL(c.req.url).search}`, 301);
});
// wayBetter for X lived at /twttr/ before /x/: old links, deep paths and queries keep working.
app.get('/twttr', c => c.redirect(`x/${new URL(c.req.url).search}`, 301));
app.get('/twttr/*', c => {
const rest = c.req.path.slice(`${config.basePath ?? ''}/twttr/`.length);
return c.redirect(`${'../'.repeat(rest.split('/').length)}x/${rest}${new URL(c.req.url).search}`, 301);
});
// The same pages exist once per language: English at the root, the others under /<code>/.
for (const at of ['', ...languages.map(code => `/${code}`)]) {
// A language's home is a folder too: /tr → /tr/.
if (at) app.get(at, c => c.redirect(`${at.slice(1)}/`, 301));
// The site has a page per app under a folder (/x/); relative links need the trailing slash.
// A relative Location keeps this correct when the site is mounted under a path prefix.
app.get(`${at}/x`, c => c.redirect('x/', 301));
// Store galleries (generated from the signed store catalog, apps/web/store-pages.ts).
app.get(`${at}/themes`, c => c.redirect('themes/', 301));
app.get(`${at}/plugins`, c => c.redirect('plugins/', 301));
// The Store (/store/): the storefront, the submit page and one page per item are folders next to
// the files the apps download (/store/catalog.json, /store/themes/<id>.json, …), which the static
// handler below keeps serving byte for byte. Only addresses without a file extension are touched.
app.get(`${at}/store`, c => c.redirect('store/', 301));
app.get(`${at}/store/submit`, c => c.redirect('submit/', 301));
// One kind's listing is the storefront with its filter on.
for (const [folder, kind] of [['themes', 'theme'], ['plugins', 'plugin']] as const) {
app.get(`${at}/store/${folder}`, c => c.redirect(`./?kind=${kind}`, 302));
app.get(`${at}/store/${folder}/`, c => c.redirect(`../?kind=${kind}`, 302));
app.get(`${at}/store/${folder}/:id{[a-z0-9-]+}`, c => c.redirect(`${c.req.param('id')}/`, 301));
}
}
app.get('*', config.web);
}
// A person who follows a dead link gets the site's 404 page; programs (the apps, the updater,
// anything that does not ask for HTML) and the API's own paths keep the JSON answer.
// Under a language's folder the answer is that language's 404 page (<dist>/<code>/404.html), when the build has it.
const notFoundPage = config.notFoundPage ? cachedBytes(config.notFoundPage) : null;
const notFoundPages = new Map(config.notFoundPage ? languages.map(code => [code, cachedBytes(join(dirname(config.notFoundPage!), code, '404.html'))] as const) : []);
app.notFound(async c => {
const path = c.req.path.slice((config.basePath ?? '').length);
const browser = (c.req.method === 'GET' || c.req.method === 'HEAD') && (c.req.header('accept') ?? '').includes('text/html');
if (notFoundPage && browser && path !== '/health' && !path.startsWith('/v1/')) {
const language = path.split('/')[1] ?? '';
const translated = await notFoundPages.get(language)?.();
// The page's links start at its language's home (<base href="/">, <base href="/tr/">): keep that true under a path prefix.
if (translated) return c.html(translated.toString('utf8').replace(`<base href="/${language}/"`, `<base href="${config.basePath ?? ''}/${language}/"`), 404, { 'Cache-Control': 'no-store' });
const page = await notFoundPage();
if (page) return c.html(page.toString('utf8').replace('<base href="/"', `<base href="${config.basePath ?? ''}/"`), 404, { 'Cache-Control': 'no-store' });
}
return c.json({ error: 'not found' }, 404);
});
app.onError((error, c) => {
console.error('[api]', error instanceof Error ? error.message : error);
return c.json({ error: 'internal error' }, 500);
});
return app;
}
function isValidHotfix(body: Buffer): boolean {
try { return Hotfix.safeParse(JSON.parse(body.toString('utf8'))).success; } catch { return false; }
}
/** Raw bytes, re-read only when the mtime changes; a missing file is null. */
function cachedBytes(path: string): () => Promise<Buffer | null> {
let cache: { mtimeMs: number; value: Buffer } | null = null;
return async () => {
let info;
try { info = await stat(path); } catch { return null; }
if (!cache || cache.mtimeMs !== info.mtimeMs) cache = { mtimeMs: info.mtimeMs, value: await readFile(path) };
return cache.value;
};
}
/** Re-reads a JSON file only when its mtime changes; a missing file means "nothing published". */
function cachedJson<T>(path: string, parse: (value: unknown) => T): () => Promise<T | null> {
let cache: { mtimeMs: number; value: T } | null = null;
return async () => {
let info;
try { info = await stat(path); } catch { return null; }
if (!cache || cache.mtimeMs !== info.mtimeMs) {
cache = { mtimeMs: info.mtimeMs, value: parse(JSON.parse(await readFile(path, 'utf8'))) };
}
return cache.value;
};
}

20
apps/api/src/index.ts Normal file
View file

@ -0,0 +1,20 @@
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import { resolve } from 'node:path';
import { createApp } from './app.js';
const port = Number(process.env.PORT ?? 8787);
// Bind to loopback by default: the API is reached through Cloudflare Tunnel, never a public port.
const hostname = process.env.HOST ?? '127.0.0.1';
const app = createApp({
releasesDir: resolve(process.env.RELEASES_DIR ?? './releases'),
basePath: process.env.BASE_PATH ?? '',
version: process.env.npm_package_version,
// Landing page build (relative to the process cwd, the repo root under pm2).
web: process.env.WEB_DIR ? serveStatic({ root: process.env.WEB_DIR }) : undefined,
notFoundPage: process.env.WEB_DIR ? resolve(process.env.WEB_DIR, '404.html') : undefined,
});
serve({ fetch: app.fetch, port, hostname }, info => {
console.log(`[api] listening on http://${info.address}:${info.port}`);
});