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

35
scripts/build-store.mjs Normal file
View file

@ -0,0 +1,35 @@
#!/usr/bin/env node
// Builds wayBetter for X's part of the shared wayBetter Store in apps/web/public/store/ with the
// framework CLI (`waybetter store build`, waybetter/packages/waybetter/cli/store.mjs) and X's
// items (scripts/store.config.mjs). Other apps' items in catalog.json are kept as they are.
// Then sign it: `node scripts/sign-store.mjs` (needs the store key; writes catalog.json.sig).
// The site (/themes/, /plugins/) and the in-app store read the same catalog.
//
// node scripts/build-store.mjs [--base https://waybetter.fyi/store/] [--out dir] [--plugins dir]
// (--plugins: read the first-party plugins from another folder, e.g. an export of committed files.)
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { buildStore } from '../waybetter/packages/waybetter/cli/store.mjs';
import config from './store.config.mjs';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
function options(argv) {
const out = { base: undefined, out: join(ROOT, 'apps/web/public/store') };
for (let i = 0; i < argv.length; i += 1) {
if (argv[i] === '--base') out.base = argv[++i];
else if (argv[i] === '--out') out.out = resolve(argv[++i]);
else if (argv[i] === '--plugins') process.env.WAYBETTER_STORE_PLUGINS = resolve(argv[++i]);
else throw new Error(`unknown option ${argv[i]}`);
}
return out;
}
try {
const { path, items } = await buildStore(config, options(process.argv.slice(2)));
console.log(`store: ${items.filter(i => i.kind === 'plugin').length} plugins, ${items.filter(i => i.kind === 'theme').length} themes, ${items.filter(i => i.kind === 'strings').length} string packs → ${dirname(path)}`);
console.log('Now sign it: node scripts/sign-store.mjs');
} catch (error) {
console.error(`build-store: ${error.stack ?? error}`);
process.exit(1);
}

287
scripts/check-store.mjs Normal file
View file

@ -0,0 +1,287 @@
#!/usr/bin/env node
// `bun run check:store`: what a contributor runs before a pull request that adds or changes a
// Store item, and what a maintainer runs before merging. No key is needed and nothing is written
// to the repository.
//
// node scripts/check-store.mjs check every item under store/x/ and the published catalog
// node scripts/check-store.mjs --verbose also print the notes (not failures)
//
// It checks, for every folder under store/x/ (layout: store/README.md):
// - ids, file names, item.json fields, categories and tags, duplicates
// - plugins: the rules the app applies at install (waybetter-host `validate_plugin`): UTF-8 text,
// a header with @name and @version, valid @permissions; plus the Store's own: a description,
// a @permissions line that names network or network:none, gated API calls declared, and no
// code loaded or evaluated at run time (eval, new Function, import())
// - themes: a JSON object the app's sanitizer accepts, no outside files in its CSS
// - previews: .svg or .png, 16:10, at least 640×400, at most 300 KB, nothing scriptable
// - media for the item's page (item.json "cover", "screenshots", "video"; files in media/):
// PNG, WebP or JPEG up to 400 KB and 1600 px wide with alt text, a 16:10 cover, at most six
// screenshots; one MP4 (H.264) or WebM up to 6 MB and 20 s, without sound, with a poster
// - search and sharing: the page title (≤ 60) and description (50–160) the site generates
// then builds the catalog in a temporary folder (the framework's rules, the ones the apps enforce)
// and compares it with the published one in apps/web/public/store/: the signature, every file's
// size and SHA-256, and which items a maintainer still has to build and sign.
import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { buildStore, catalogProblems, sha256, verifyFile } from '../waybetter/packages/waybetter/cli/store.mjs';
import config, { APP, source } from './store.config.mjs';
import { CATEGORIES } from './store/source.mjs';
import { readAreaSource } from './store/areas.mjs';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const PUBLISHED = join(ROOT, 'apps/web/public/store');
const PUBLIC_KEY = join(ROOT, 'apps/desktop/src-tauri/keys/store.pub');
const MAX_ITEM_BYTES = 2 * 1024 * 1024;
const MAX_PREVIEW_BYTES = 300 * 1024;
const verbose = process.argv.includes('--verbose');
const errors = [];
const notes = [];
const fail = (where, message) => errors.push(`${where}: ${message}`);
const note = (where, message) => notes.push(`${where}: ${message}`);
/** What waybetter-host `source_findings` looks for; `network:none` with any of the first five is refused. */
const NETWORK = [['fetch(', 'fetch'], ['XMLHttpRequest', 'XMLHttpRequest'], ['WebSocket', 'WebSocket'], ['EventSource', 'EventSource'], ['sendBeacon', 'sendBeacon']];
const RUNTIME_CODE = [[/\bimport\s*\(/, 'import()'], [/\beval\b/, 'eval'], [/\bnew\s+Function\b/, 'new Function']];
/** The gated part of the plugin API (docs/PLUGINS.md → Permissions). */
const GATED = [
['storage', /\bapi\.storage\s*\(/], ['ui', /\bapi\.(ui\b|toast\s*\()|\bscope\.ui\b/], ['clipboard', /\bapi\.copyText\s*\(/],
['account', /\bapi\.account\s*\(/], ['users', /\bapi\.users\b/], ['commands', /\bapi\.commands\b|\bscope\.commands\b/],
];
function checkPlugin(entry) {
const where = `${entry.dir}/${entry.file}`;
const bytes = Buffer.isBuffer(entry.bytes) ? entry.bytes : Buffer.from(entry.bytes);
if (!bytes.length) return fail(where, 'the file is empty');
if (bytes.length > MAX_ITEM_BYTES) fail(where, 'plugins are limited to 2 MiB');
const text = bytes.toString('utf8');
if (!Buffer.from(text, 'utf8').equals(bytes)) return fail(where, 'a plugin must be UTF-8 text');
// eslint-disable-next-line no-control-regex
if (/[\u0000-\u0008\u000b\u000e-\u001f\u007f-\u009f�]/.test(text)) return fail(where, 'the file contains binary data, not JavaScript text');
const start = text.replace(/^/, '').trimStart();
if (!start.startsWith('/**') || !start.includes('*/')) return fail(where, 'a plugin starts with a /** … */ header (@name, @version, @description, @author, @permissions)');
const header = start.slice(0, start.indexOf('*/'));
if (!header.includes('@name')) fail(where, 'the header needs an @name');
if (!header.includes('@description') || !entry.description) fail(where, 'the header needs an @description');
if (!entry.firstParty && !entry.author) fail(where, 'the header needs an @author');
if ([...header.matchAll(/@description\s*(.*)/g)].some(match => [...match[1].trim()].length > 300)) note(where, 'the @description is longer than 300 characters; the app and the Store keep the first 300');
const permissions = entry.permissions;
if (permissions == null) fail(where, 'the header needs a @permissions line (for example "@permissions storage, ui, network:none"); a plugin without one is "legacy" and is not accepted in the Store');
else {
if (permissions.includes('network') && permissions.includes('network:none')) fail(where, '@permissions: "network" and "network:none" contradict each other');
if (!permissions.includes('network') && !permissions.includes('network:none')) fail(where, '@permissions must say whether the plugin contacts a server: add "network" or "network:none"');
const used = NETWORK.filter(([needle]) => text.includes(needle)).map(([, name]) => name);
if (permissions.includes('network:none') && used.length) fail(where, `the header says network:none but the code uses ${used.join(', ')}`);
for (const [permission, pattern] of GATED) {
if (pattern.test(text) && !permissions.includes(permission)) fail(where, `the code uses the "${permission}" part of the API but @permissions does not declare it`);
}
}
const loaded = RUNTIME_CODE.filter(([pattern]) => pattern.test(text)).map(([, name]) => name);
if (loaded.length) fail(where, `a Store plugin may not load or evaluate code at run time (${loaded.join(', ')}): the code that is reviewed and signed must be the code that runs`);
if (/<script[\s>]|createElement\(\s*['"`]script['"`]\s*\)/i.test(text)) fail(where, 'a Store plugin may not add <script> elements: the code that is reviewed and signed must be the code that runs');
}
/** A string pack: the framework's pack rules, and every string fits the site's inventory. */
async function checkStrings(entry) {
const where = `${entry.dir}/${entry.file}`;
const bytes = Buffer.isBuffer(entry.bytes) ? entry.bytes : Buffer.from(entry.bytes);
if (bytes.length > MAX_ITEM_BYTES) fail(where, 'string packs are limited to 2 MiB');
const { checkPackShape, compilePack } = await import('../waybetter/packages/runtime/src/stringPacks.ts');
for (const issue of checkPackShape(entry.pack)) (issue.level === 'error' ? fail : note)(where, issue.message);
const inventory = JSON.parse(readFileSync(join(ROOT, 'apps/desktop/strings/x.web.inventory.json'), 'utf8'));
if (entry.pack.catalog !== inventory.catalog) return fail(where, `the pack is for the "${entry.pack.catalog}" catalog; the inventory is "${inventory.catalog}"`);
let compiled;
try { compiled = compilePack(entry.pack, inventory); } catch (error) { return fail(where, error.message); }
const { unknown, rejected } = compiled.report;
if (unknown.length) fail(where, `${unknown.length} key(s) the inventory does not have (${unknown.slice(0, 5).join(', ')}); run waybetter strings check`);
for (const item of rejected.slice(0, 10)) fail(where, `${item.id}: ${item.reason}`);
if (rejected.length > 10) fail(where, `… ${rejected.length - 10} more strings do not fit`);
}
function checkTheme(entry) {
const where = `${entry.dir}/theme.json`;
const bytes = Buffer.isBuffer(entry.bytes) ? entry.bytes : Buffer.from(entry.bytes);
if (bytes.length > MAX_ITEM_BYTES) fail(where, 'themes are limited to 2 MiB');
const css = typeof entry.theme?.css === 'string' ? entry.theme.css : '';
if (css) {
if (/@import\b/i.test(css)) fail(where, 'a Store theme\'s css may not @import anything');
if (/url\(\s*['"]?\s*(https?:)?\/\//i.test(css)) fail(where, 'a Store theme\'s css may not load files from another server');
if (!entry.firstParty) note(where, 'this theme carries custom CSS; the install screen warns about it and a maintainer reads it');
}
if (entry.theme?.id !== undefined && entry.theme.id !== entry.id && !entry.firstParty) note(where, `the theme's "id" (${entry.theme.id}) differs from its folder (${entry.id}); the Store uses the folder`);
}
/** Pixel size of a PNG (IHDR) or an SVG (width/height, else viewBox). */
function pictureSize(bytes, png) {
if (png) {
if (bytes.length < 24 || bytes.readUInt32BE(0) !== 0x89504e47 || bytes.toString('latin1', 12, 16) !== 'IHDR') return null;
return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
}
const tag = /<svg\b[^>]*>/i.exec(bytes.toString('utf8'))?.[0];
if (!tag) return null;
const number = name => Number(new RegExp(`\\s${name}="([\\d.]+)(?:px)?"`).exec(tag)?.[1]);
const box = /\sviewBox="\s*[-\d.]+[\s,]+[-\d.]+[\s,]+([\d.]+)[\s,]+([\d.]+)\s*"/.exec(tag);
const width = number('width') || Number(box?.[1]);
const height = number('height') || Number(box?.[2]);
return width && height ? { width, height } : null;
}
function checkPreview(entry) {
const preview = entry.preview;
const where = `${entry.dir} (preview ${preview.path.split('/').pop()})`;
const bytes = Buffer.isBuffer(preview.bytes) ? preview.bytes : Buffer.from(preview.bytes);
const png = preview.path.endsWith('.png');
if (bytes.length > MAX_PREVIEW_BYTES) fail(where, `a preview is at most 300 KB (this one is ${Math.round(bytes.length / 1024)} KB)`);
const size = pictureSize(bytes, png);
if (!size) return fail(where, png ? 'not a PNG file' : 'an SVG preview needs width and height, or a viewBox');
if (Math.abs(size.width / size.height - 1.6) > 0.01) fail(where, `a preview is 16:10, for example 640×400 (this one is ${size.width}×${size.height})`);
if (png && size.width < 640) fail(where, `a PNG preview is at least 640×400 (this one is ${size.width}×${size.height})`);
if (!png) {
const svg = bytes.toString('utf8');
if (/<script\b|<foreignObject\b|\son[a-z]+\s*=|javascript:/i.test(svg)) fail(where, 'an SVG preview may not contain scripts, event handlers or foreignObject');
// The namespace declarations are names, not files; pictures inside the SVG must be data: URLs.
if (/(?:href|src)\s*=\s*["']\s*(?:https?:)?\/\//i.test(svg) || /url\(\s*['"]?\s*(?:https?:)?\/\//i.test(svg)) fail(where, 'an SVG preview may not load files from another server (embed pictures as data: URLs)');
}
}
try {
// ---- The source folders ---------------------------------------------------------------------
const { entries, problems } = await source();
for (const problem of problems) errors.push(problem);
const { readItemMedia } = await import('../apps/web/store-media.ts');
const withMedia = [];
const seen = new Map();
const files = new Map();
for (const entry of entries) {
const where = entry.dir;
const key = `${entry.kind}/${entry.id}`;
if (seen.has(key)) fail(where, `duplicate id (also ${seen.get(key)})`);
seen.set(key, where);
if (entry.kind === 'plugin') {
const file = entry.file.toLowerCase();
if (files.has(file)) fail(where, `another plugin is installed under the same file name (${files.get(file)})`);
files.set(file, where);
}
if (!CATEGORIES[entry.kind].includes(entry.category)) fail(`${where}/item.json`, `"category" must be one of ${CATEGORIES[entry.kind].join(', ')}${entry.category ? ` (not "${entry.category}")` : ''}`);
if (entry.tags.length > 12 || entry.tags.some(tag => !tag.trim() || [...tag].length > 32)) fail(`${where}/item.json`, 'tags: at most 12, each 1 to 32 characters');
if (new Set(entry.tags.map(tag => tag.toLowerCase())).size !== entry.tags.length) fail(`${where}/item.json`, 'tags: a tag is listed twice');
if (!/^\d+\.\d+\.\d+([-+][\w.-]+)?$/.test(entry.version)) note(where, `version "${entry.version}" is not major.minor.patch`);
if ([...entry.name].length > 60) fail(where, 'the name is longer than 60 characters');
if ([...entry.description].length < 50) fail(where, `the description is ${[...entry.description].length} characters; say what it does in at least 50 (it becomes the text under the item's name in search results)`);
if (entry.kind === 'plugin') checkPlugin(entry); else if (entry.kind === 'strings') await checkStrings(entry); else checkTheme(entry);
checkPreview(entry);
// The item's own cover, screenshots and video (website only; the catalog never names them).
const { media, problems: mediaProblems } = readItemMedia(join(ROOT, where), `/store-media/${where.slice('store/'.length)}/`, where);
for (const problem of mediaProblems) errors.push(problem);
const pieces = [media.cover && 'a cover', media.screenshots.length && `${media.screenshots.length} screenshot(s)`, media.video && `a ${media.video.seconds.toFixed(1)} s video`].filter(Boolean);
if (pieces.length) withMedia.push(`${where}: ${pieces.join(', ')}`);
}
// The area plugins: built into the app, a page each on the site (store/x/areas/<id>/), never in the catalog.
const { X_TABLE } = await import('../apps/desktop/src/areas/table.ts');
const areas = readAreaSource({ root: ROOT, app: APP, ids: X_TABLE.areas.map(area => area.id) });
for (const problem of areas.problems) errors.push(problem);
for (const area of areas.entries) {
const { media, problems: mediaProblems } = readItemMedia(join(ROOT, area.dir), `/store-media/${area.dir.slice('store/'.length)}/`, area.dir);
for (const problem of mediaProblems) errors.push(problem);
const pieces = [media.cover && 'a cover', media.screenshots.length && `${media.screenshots.length} screenshot(s)`, media.video && `a ${media.video.seconds.toFixed(1)} s video`].filter(Boolean);
if (pieces.length) withMedia.push(`${area.dir}: ${pieces.join(', ')}`);
}
for (const line of withMedia) note(line, 'media for its page on the site (not in the catalog: no signature needed)');
// store/featured.json: the storefront's "Featured" shelf.
const featuredPath = join(ROOT, 'store/featured.json');
if (existsSync(featuredPath)) {
let featured = [];
try { featured = JSON.parse(readFileSync(featuredPath, 'utf8')); } catch (error) { fail('store/featured.json', `not valid JSON (${error.message})`); }
if (!Array.isArray(featured)) fail('store/featured.json', 'must be a list of "<app>/<kind>/<id>"');
else for (const item of featured) if (typeof item !== 'string' || !seen.has(item.replace(new RegExp(`^${APP}/`), ''))) fail('store/featured.json', `"${item}" is not an item under store/ (write "<app>/<kind>/<id>")`);
}
// ---- The catalog these folders build, with the rules the apps enforce -------------------------
let built = null;
if (!problems.length) {
const out = mkdtempSync(join(tmpdir(), 'wb-store-check-'));
try {
// Start from the published catalog, as the real build does (other apps' items stay).
if (existsSync(join(PUBLISHED, 'catalog.json'))) cpSync(join(PUBLISHED, 'catalog.json'), join(out, 'catalog.json'));
built = (await buildStore(config, { out })).catalog;
} catch (error) {
errors.push(error.message);
} finally {
rmSync(out, { recursive: true, force: true });
}
}
// ---- Search and sharing: the meta data the site generates for every item page -----------------
if (built) {
const { sitePages, TITLE_MAX, DESCRIPTION_MIN, DESCRIPTION_MAX } = await import('../apps/web/seo.ts');
const { areaItems } = await import('../apps/web/areas.ts');
const pages = sitePages(built, { areas: areaItems() });
const titles = new Map();
const descriptions = new Map();
for (const page of pages) {
const where = `page ${page.path}`;
const title = [...page.title].length;
const description = [...page.description].length;
if (title > TITLE_MAX) fail(where, `the title is ${title} characters (at most ${TITLE_MAX}): "${page.title}"`);
// The two app pages keep their longer, hand-written descriptions.
if (page.path.startsWith('/store/') || page.path === '/themes/' || page.path === '/plugins/') {
if (description < DESCRIPTION_MIN || description > DESCRIPTION_MAX) fail(where, `the description is ${description} characters (${DESCRIPTION_MIN} to ${DESCRIPTION_MAX})`);
}
if (titles.has(page.title)) fail(where, `same title as ${titles.get(page.title)}: "${page.title}"`);
if (descriptions.has(page.description)) fail(where, `same description as ${descriptions.get(page.description)}`);
titles.set(page.title, page.path);
descriptions.set(page.description, page.path);
}
for (const entry of entries) if ([...entry.description].length > DESCRIPTION_MAX) note(entry.dir, `the description is ${[...entry.description].length} characters; search engines get its first ${DESCRIPTION_MAX} or fewer (whole sentences)`);
}
// ---- The published catalog (apps/web/public/store): signature, files, and what is pending ------
const catalogPath = join(PUBLISHED, 'catalog.json');
let pending = [];
if (existsSync(catalogPath)) {
const published = JSON.parse(readFileSync(catalogPath, 'utf8'));
for (const problem of catalogProblems(published, { app: APP })) fail('published catalog', problem);
if (!existsSync(`${catalogPath}.sig`) || !verifyFile(catalogPath, [readFileSync(PUBLIC_KEY, 'utf8').trim()])) fail('published catalog', 'catalog.json.sig does not verify with apps/desktop/src-tauri/keys/store.pub (a maintainer signs: node scripts/sign-store.mjs)');
const base = 'https://waybetter.fyi/store/';
for (const item of published.items) {
for (const [field, url] of [['file', item.url], ['preview', item.preview]]) {
if (!url?.startsWith(base)) continue;
const path = join(PUBLISHED, url.slice(base.length));
if (!existsSync(path)) { fail(`published ${item.kind}:${item.id}`, `${field} ${url.slice(base.length)} is missing from apps/web/public/store`); continue; }
if (field !== 'file') continue;
const bytes = readFileSync(path);
if (bytes.length !== item.size || sha256(bytes) !== item.sha256) fail(`published ${item.kind}:${item.id}`, `${url.slice(base.length)} does not match the size and sha256 in the signed catalog`);
}
}
if (built) {
const key = item => `${item.kind}:${item.id}`;
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
const mine = items => new Map(items.filter(item => item.apps.includes(APP)).map(item => [key(item), item]));
const before = mine(published.items);
const after = mine(built.items);
for (const [id, item] of after) if (!before.has(id)) pending.push(`new: ${id}`); else if (!same(item, before.get(id))) pending.push(`changed: ${id}`);
for (const id of before.keys()) if (!after.has(id)) pending.push(`removed: ${id}`);
}
} else fail('published catalog', 'apps/web/public/store/catalog.json is missing');
// ---- Report ---------------------------------------------------------------------------------
const count = kind => entries.filter(entry => entry.kind === kind).length;
if (verbose) for (const line of notes) console.log(`note ${line}`);
for (const line of errors) console.error(`error ${line}`);
console.log(`store: ${count('plugin')} plugins, ${count('theme')} themes, ${count('strings')} string packs under store/${APP}/ · ${errors.length} error(s), ${notes.length} note(s)${notes.length && !verbose ? ' (--verbose lists them)' : ''}`);
if (built && !errors.length) {
if (pending.length) {
console.log(`published catalog: signature and files verify · ${pending.length} item(s) wait for a maintainer to build and sign:`);
for (const line of pending) console.log(` ${line}`);
} else console.log('published catalog: signature and files verify · in sync with the source (nothing to build or sign)');
}
process.exit(errors.length ? 1 : 0);
} catch (error) {
console.error(`check-store: ${error.stack ?? error}`);
process.exit(1);
}

23
scripts/i18n-check.mjs Normal file
View file

@ -0,0 +1,23 @@
#!/usr/bin/env node
// Checks every locale catalog (docs/TRANSLATING.md) and the files generated from them. Part of
// `bun run test`. This is `waybetter i18n check` (the framework's CLI, waybetter/packages/waybetter/
// cli/i18n.mjs) with this repository's waybetter.i18n.json: file shape, keys that English does not
// have, ICU syntax, placeholder parity with English, plural forms each language needs, no markup or
// control characters, length warnings; the app's catalogs and the framework's.
//
// node scripts/i18n-check.mjs check (exit 1 on errors)
// node scripts/i18n-check.mjs --write also regenerate apps/desktop/locales/languages.json and
// the native localization files (macOS, Linux)
// node scripts/i18n-check.mjs --verbose list every warning (untranslated and long messages)
// node scripts/i18n-check.mjs tr only these locales (plus English)
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { i18nCommand } from '../waybetter/packages/waybetter/cli/i18n.mjs';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
try {
process.exit(await i18nCommand(['check', ...process.argv.slice(2)], { cwd: root }));
} catch (error) {
console.error(`i18n-check: ${error instanceof Error ? error.message : error}`);
process.exit(1);
}

25
scripts/i18n-extract.mjs Normal file
View file

@ -0,0 +1,25 @@
#!/usr/bin/env node
// Lists the message keys the app's code looks up and compares them with the English source
// catalog (docs/TRANSLATING.md). A developer runs it after adding UI text. This is
// `waybetter i18n extract` (waybetter/packages/waybetter/cli/i18n.mjs) with this repository's
// waybetter.i18n.json.
//
// node scripts/i18n-extract.mjs keys used in code but missing from en.json (exit 1),
// then keys en.json has that no literal lookup names
// node scripts/i18n-extract.mjs --missing only the missing keys
//
// Keys built at runtime (`features.${id}.label`) are invisible here, so "no literal lookup" is a
// hint, never a reason to delete: check with a search first. `plugin.*` keys belong to bundled
// plugins (their inline English is compared by the check), `native.app.*` to the generated native
// files.
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { i18nCommand } from '../waybetter/packages/waybetter/cli/i18n.mjs';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
try {
process.exit(await i18nCommand(['extract', ...process.argv.slice(2)], { cwd: root }));
} catch (error) {
console.error(`i18n-extract: ${error instanceof Error ? error.message : error}`);
process.exit(1);
}

68
scripts/i18n-site.mjs Normal file
View file

@ -0,0 +1,68 @@
#!/usr/bin/env node
// The site's catalogs (apps/web/locales, docs/TRANSLATING.md → "The website"). English is the source:
// a page's own text is in its HTML, marked with data-i18n (apps/web/i18n-html.ts); what the build and
// the scripts say is written in en.json by hand (site.meta.*, site.gen.*, site.js.*,
// site.lang.*).
//
// node scripts/i18n-site.mjs check: en.json matches the pages, every language has every
// key, then the framework's `waybetter i18n check` on the
// site's catalogs (exit 1 on errors)
// node scripts/i18n-site.mjs --write write the pages' text and notes into en.json / en.meta.json
// (hand-written keys and notes are kept) and languages.json
// node scripts/i18n-site.mjs --verbose list every warning
// node scripts/i18n-site.mjs tr only these languages (plus English)
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { i18nCommand } from '../waybetter/packages/waybetter/cli/i18n.mjs';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const web = join(root, 'apps/web');
const locales = join(web, 'locales');
const args = process.argv.slice(2);
const write = args.includes('--write');
const { CODE_PREFIXES, extractPages } = await import('../apps/web/i18n.ts');
const { LANGUAGES } = await import('../apps/web/site.config.ts');
const readJson = (file, fallback) => (existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : fallback);
const byHand = key => CODE_PREFIXES.some(prefix => key.startsWith(prefix));
let errors = 0;
const fail = message => { errors += 1; console.error(`ERROR ${message}`); };
try {
const pages = extractPages(web);
const enFile = join(locales, 'en.json');
const metaFile = join(locales, 'en.meta.json');
const en = readJson(enFile, { $schema: '../../../waybetter/packages/waybetter/i18n.schema.json', locale: 'en', name: 'English', englishName: 'English', status: 'source', messages: {} });
const meta = readJson(metaFile, { $schema: '../../../waybetter/packages/waybetter/i18n-meta.schema.json' });
const hand = Object.fromEntries(Object.entries(en.messages).filter(([key]) => byHand(key)));
const handNotes = Object.fromEntries(Object.entries(meta).filter(([key]) => byHand(key)));
const wanted = { ...en, messages: { ...pages.messages, ...hand } };
const wantedMeta = { $schema: meta.$schema, ...pages.notes, ...handNotes };
const text = value => `${JSON.stringify(value, null, 2)}\n`;
if (write) {
writeFileSync(enFile, text(wanted));
writeFileSync(metaFile, text(wantedMeta));
console.log(`wrote apps/web/locales/en.json (${Object.keys(pages.messages).length} page + ${Object.keys(hand).length} hand-written messages) and en.meta.json`);
} else {
if (text(wanted) !== text(en)) {
const stale = [...new Set([...Object.keys(wanted.messages), ...Object.keys(en.messages)])].filter(key => wanted.messages[key] !== en.messages[key]);
fail(`apps/web/locales/en.json is out of date with the pages (${stale.slice(0, 5).join(', ')}${stale.length > 5 ? ', …' : stale.length ? '' : 'key order'}): run \`node scripts/i18n-site.mjs --write\``);
}
if (text(wantedMeta) !== text(meta)) fail('apps/web/locales/en.meta.json is out of date with the pages: run `node scripts/i18n-site.mjs --write`');
// A site page is never half translated: every published language has every key.
for (const code of LANGUAGES) {
if (code === 'en' || !existsSync(join(locales, `${code}.json`))) continue;
const catalog = readJson(join(locales, `${code}.json`));
const missing = Object.keys(wanted.messages).filter(key => !(key in catalog.messages));
if (missing.length) fail(`apps/web/locales/${code}.json lacks ${missing.length} message(s): ${missing.slice(0, 5).join(', ')}${missing.length > 5 ? ', …' : ''}`);
}
}
const code = await i18nCommand(['check', ...args, '--config', join(web, 'waybetter.i18n.json')], { cwd: root });
if (errors) console.error(`i18n-site: ${errors} error(s)`);
process.exit(code || (errors ? 1 : 0));
} catch (error) {
console.error(`i18n-site: ${error instanceof Error ? error.message : error}`);
process.exit(1);
}

75
scripts/privacy-scan.mjs Normal file
View file

@ -0,0 +1,75 @@
#!/usr/bin/env node
// Checks that nothing this repository publishes names a person: `waybetter privacy-scan` (the
// framework's command, waybetter/packages/waybetter/cli/privacy.mjs) over
//
// 1. every file git tracks here and in the framework submodule (and their names),
// 2. the built site (apps/web/dist, when it exists),
// 3. the npm tarballs of `waybetter` and `create-waybetter`, packed into a temporary folder.
//
// The forbidden terms are a file outside every repository ("forbiddenTerms" in
// waybetter.release.json, or WAYBETTER_FORBIDDEN_TERMS); this machine's account name is always
// added. A term is never printed: hits show the file, the line or offset and `x***`. Reviewed
// false positives: privacy-allowlist.txt.
//
// node scripts/privacy-scan.mjs everything above (bun run privacy:scan)
// node scripts/privacy-scan.mjs --fast tracked files only, and nothing at all (quietly)
// when the terms file does not exist (bun run test)
// node scripts/privacy-scan.mjs --history every blob, path, commit message and identity of
// both repositories (before a history is published)
// --all list every hit, not the first five of each file
//
// Native artifacts are checked by the release itself (`waybetter release` refuses an installer, a
// binary, a dmg or an updater bundle with a hit); to check one by hand:
// node waybetter/packages/waybetter/bin/waybetter.mjs privacy-scan <file or folder>
import { spawnSync } from 'node:child_process';
import { existsSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { TERMS_ENV, privacyCommand, privacyConfig } from '../waybetter/packages/waybetter/cli/privacy.mjs';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const args = process.argv.slice(2);
const fast = args.includes('--fast');
const extra = args.includes('--all') ? ['--all'] : [];
const allow = ['--allow', join(root, 'privacy-allowlist.txt')];
// The same terms for every step, also the ones that run in a temporary folder.
const configured = process.env[TERMS_ENV] || privacyConfig(root).forbiddenTerms;
const terms = configured && existsSync(configured) ? ['--terms', configured] : [];
let worst = 0;
const run = (label, scanArgs, cwd = root) => {
if (!fast) console.log(`\n${label}`);
worst = Math.max(worst, privacyCommand([...scanArgs, ...terms, ...allow, ...extra, ...(fast ? ['--if-terms'] : [])], { cwd }));
};
try {
if (args.includes('--history')) {
run('history of this repository and of the framework', ['--history', '.', 'waybetter']);
} else {
run('tracked files (this repository, the framework)', ['--tracked', '.', 'waybetter']);
if (!fast) {
const site = join(root, 'apps/web/dist');
if (existsSync(site)) run('the built site (apps/web/dist)', ['apps/web/dist']);
else console.log('\nthe built site: apps/web/dist does not exist (bun run build:server), skipped');
const packed = mkdtempSync(join(tmpdir(), 'wb-pack-'));
try {
for (const name of ['waybetter', 'create-waybetter']) {
const cwd = join(root, 'waybetter/packages', name);
if (name === 'waybetter' && !existsSync(join(cwd, 'dist'))) console.log('\nnote: waybetter/packages/waybetter/dist is not built; the tarball is packed without it');
// A fixed command (no user input); the shell resolves npm's .cmd shim on Windows.
const pack = spawnSync(`npm pack --silent --pack-destination "${packed}"`, { cwd, shell: true, stdio: ['ignore', 'ignore', 'inherit'] });
if (pack.status !== 0) throw new Error(`npm pack failed in waybetter/packages/${name}`);
}
run(`npm tarballs (${readdirSync(packed).join(', ')})`, ['.'], packed);
} finally {
rmSync(packed, { recursive: true, force: true });
}
}
}
} catch (error) {
console.error(`privacy-scan: ${error instanceof Error ? error.message : error}`);
process.exit(1);
}
if (worst) console.error('\nprivacy-scan: FAILED. Fix the files above (or, for a reviewed false positive, add a line to privacy-allowlist.txt).');
process.exit(worst);

311
scripts/public-tree.mjs Normal file
View file

@ -0,0 +1,311 @@
#!/usr/bin/env node
// Builds the exact tree that becomes the single initial commit of the public repository, in a
// scratch directory OUTSIDE the working tree, and checks it. Re-runnable: it always starts from
// the committed HEAD (git archive), never from the working tree.
//
// node scripts/public-tree.mjs [--out <dir>] [--fw-commit <sha>] [--fw-url <url>] [--no-history-scan]
//
// Default --out is %USERPROFILE%/Desktop/twttr/public-dryrun. It writes
// <out>/tree/ the file set (no .git)
// <out>/repo/ the same set as one commit, authored as CRT (a throwaway repository)
// <out>/REPORT.md file count, size, exclusions and why, scan results, the commands to publish
//
// Nothing is pushed or uploaded. The privacy scan uses the framework's `waybetter privacy-scan`
// with the terms file named in waybetter.release.json; no term is ever printed (hits are masked)
// and the machine user's name is masked in every path this script prints.
import { execFileSync, spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
process.on('uncaughtException', error => { console.error(`public-tree: ${String(error?.message ?? error).replace(process.env.USERNAME || 'no-user', '<user>')}`); process.exit(1); });
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const args = process.argv.slice(2);
const opt = (name, fallback) => {
const at = args.indexOf(`--${name}`);
return at >= 0 && args[at + 1] ? args[at + 1] : fallback;
};
const out = path.resolve(opt('out', path.join(os.homedir(), 'Desktop', 'twttr', 'public-dryrun')));
const PUBLIC_REPO = 'https://git.crt.fyi/CRT/waybetter-for-x.git';
const FW_URL = opt('fw-url', 'https://git.crt.fyi/CRT/waybetter.git');
const UPDATE = args.includes('--update');
const MESSAGE = opt('message', '');
if (UPDATE && !MESSAGE) throw new Error('--update needs --message "<commit message>"');
const AUTHOR = { name: 'CRT', email: 'hi@crt.fyi' };
const MAX_FILE = 3_000_000; // bytes; larger files are listed for review
// Never print the machine user's name or the home folder.
const user = os.userInfo().username;
const mask = text =>
String(text)
.split(os.homedir()).join('%USERPROFILE%')
.split(os.homedir().replace(/\\/g, '/')).join('%USERPROFILE%')
.replace(new RegExp(user.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), '<user>');
const show = p => mask(p);
const git = (cwd, ...a) => execFileSync('git', a, { cwd, encoding: 'utf8', maxBuffer: 1 << 28 }).trim();
const head = git(root, 'rev-parse', 'HEAD');
// ---------------------------------------------------------------------------------------------
// What is left out, and why. First match wins. Keep the reasons honest: they go in the report.
const EXCLUDE = [
[/^\.omc\//, 'agent plans, research and notes (local tool state)'],
[/^\.claude\//, 'agent worktrees and local settings'],
[/^(HANDOFF|CLAUDE)\.md$/, 'private working notes for the maintainer\'s tools'],
[/^verification\//, 'screenshots, recordings and QA reports from live sessions on real accounts (about 87 MB); they can show account content and are not part of the product'],
[/^releases\//, 'built installers and old private builds'],
[/^ecosystem\.config\.cjs$/, 'the maintainer\'s own server process configuration'],
[/^docs\/IMPLEMENTATION-CONTRACT\.md$/, 'the first private working contract (says "Private local working repository"); superseded by the code and the other docs'],
[/^apps\/desktop\/(tmp|test-results)\//, 'scratch output'],
[/^main\.bundle$/, 'a git bundle'],
[/\.(log|db|sqlite3?|pem|key|p12|pfx)$/i, 'logs, databases and key material'],
// The reviewed allowlist names the context around each hit, and a context can give the private
// word away (a well-known header name with the word cut out is the word): never public.
[/(^|\/)privacy-allowlist[^/]*\.txt$/, 'the privacy scan\'s reviewed contexts (a context can reveal the private term)'],
];
// Files that must exist in the tree because a public doc links to them (checked below).
const files = execFileSync('git', ['ls-tree', '-r', '-z', head], { cwd: root, encoding: 'utf8', maxBuffer: 1 << 28 })
.split('\0').filter(Boolean).map(line => {
const tab = line.indexOf('\t');
const [mode, type, sha] = line.slice(0, tab).split(' ');
return { mode, type, sha, path: line.slice(tab + 1) };
});
const gitlink = files.find(f => f.mode === '160000' && f.path === 'waybetter');
const fwCommit = opt('fw-commit', gitlink?.sha);
if (!fwCommit) throw new Error('no waybetter gitlink at HEAD');
const kept = [];
const excluded = new Map(); // reason -> { count, bytes, samples }
for (const file of files) {
if (file.type === 'commit') continue; // the submodule: re-added below as a gitlink
const rule = EXCLUDE.find(([re]) => re.test(file.path));
if (rule) {
const entry = excluded.get(rule[1]) ?? { count: 0, bytes: 0, samples: [] };
entry.count++;
if (entry.samples.length < 3) entry.samples.push(file.path);
excluded.set(rule[1], entry);
} else kept.push(file);
}
// ---------------------------------------------------------------------------------------------
// Extract HEAD into <out>/tree, then delete what is excluded.
fs.rmSync(out, { recursive: true, force: true });
fs.mkdirSync(path.join(out, 'tree'), { recursive: true });
const tree = path.join(out, 'tree');
{
const archive = spawnSync('git', ['archive', '--format=tar', head], { cwd: root, maxBuffer: 1 << 30 });
if (archive.status !== 0) throw new Error('git archive failed');
const untar = spawnSync('tar', ['-x'], { cwd: tree, input: archive.stdout, maxBuffer: 1 << 28 });
if (untar.status !== 0) throw new Error(`tar failed: ${mask(untar.stderr)}`);
}
const keepSet = new Set(kept.map(f => f.path));
let removed = 0;
const walk = dir => {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
const rel = path.relative(tree, full).split(path.sep).join('/');
if (entry.isDirectory()) walk(full);
else if (!keepSet.has(rel)) { fs.rmSync(full); removed++; }
}
};
walk(tree);
// Empty directories left by the exclusions (and the empty submodule folder).
const prune = dir => {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) if (entry.isDirectory()) prune(path.join(dir, entry.name));
if (dir !== tree && fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);
};
prune(tree);
// .gitmodules: the public framework URL, no comments about the maintainer's servers.
fs.writeFileSync(path.join(tree, '.gitmodules'),
`[submodule "waybetter"]\n\tpath = waybetter\n\turl = ${FW_URL}\n\tbranch = main\n`);
// ---------------------------------------------------------------------------------------------
// Inventory
const all = [];
const scanDir = dir => {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) scanDir(full);
else all.push({ rel: path.relative(tree, full).split(path.sep).join('/'), full, size: fs.statSync(full).size });
}
};
scanDir(tree);
const totalBytes = all.reduce((sum, f) => sum + f.size, 0);
for (const [, entry] of excluded) entry.bytes = 0;
const big = all.filter(f => f.size > MAX_FILE).sort((a, b) => b.size - a.size);
const images = all.filter(f => /\.(png|jpe?g|webp|gif|svg|ico|icns|mp4|webm)$/i.test(f.rel));
const reviewedFile = path.join(root, 'scripts', 'public-tree.reviewed-images.json');
const reviewed = fs.existsSync(reviewedFile) ? JSON.parse(fs.readFileSync(reviewedFile, 'utf8')).reviewed : {};
const unreviewed = images.filter(f => !/^apps\/web\/public\/(og\/items|store\/previews)\//.test(f.rel) && reviewed[f.rel] !== createHash('sha256').update(fs.readFileSync(f.full)).digest('hex')).map(f => f.rel);
// ---------------------------------------------------------------------------------------------
// Checks on the tree
const textFile = f => !/\.(png|jpe?g|webp|gif|ico|icns|mp4|webm|woff2?|ttf|otf|zip|gz|exe|dll|bin|pdf)$/i.test(f.rel) && f.size < 5_000_000;
const pathPatterns = [
[/C:\\Users\\[^\\\s"'`]+/g],
[/C:\/Users\/[^/\s"'`]+/g],
[/\/Users\/(?!<)[A-Za-z0-9._-]+/g],
[/\/home\/(?!<)[A-Za-z0-9._-]+/g, '/home/<user>'],
];
const pathHits = [];
for (const f of all.filter(textFile)) {
const text = fs.readFileSync(f.full, 'utf8');
if (!/Users|home/.test(text)) continue;
text.split('\n').forEach((line, i) => {
for (const [re] of pathPatterns) {
re.lastIndex = 0;
const m = line.match(re);
if (m) pathHits.push(`${f.rel}:${i + 1}: ${m.map(x => mask(x)).join(', ')}`);
}
});
}
// Relative links in kept Markdown that point at something the tree does not have.
const present = new Set(all.map(f => f.rel));
const dirs = new Set();
for (const rel of present) for (let d = path.posix.dirname(rel); d !== '.'; d = path.posix.dirname(d)) dirs.add(d);
const deadLinks = [];
for (const f of all.filter(f => f.rel.endsWith('.md'))) {
const text = fs.readFileSync(f.full, 'utf8');
for (const m of text.matchAll(/\]\(([^)\s#]+)(?:#[^)]*)?\)/g)) {
const target = m[1];
if (/^([a-z]+:|\/\/|#|mailto:)/i.test(target)) continue;
const resolved = path.posix.normalize(path.posix.join(path.posix.dirname(f.rel), target));
if (resolved.startsWith('waybetter/')) continue; // the submodule
if (!present.has(resolved) && !dirs.has(resolved.replace(/\/$/, ''))) deadLinks.push(`${f.rel}: ${target}`);
}
}
// Names of files and the whole tree through the framework's scan (terms from the keys folder).
const cli = path.join(root, 'waybetter', 'packages', 'waybetter', 'bin', 'waybetter.mjs');
const { TERMS_ENV, privacyConfig } = await import(pathToFileURL(path.join(root, 'waybetter', 'packages', 'waybetter', 'cli', 'privacy.mjs')).href);
const configured = process.env[TERMS_ENV] || privacyConfig(root).forbiddenTerms;
const termsArgs = configured && fs.existsSync(configured) ? ['--terms', configured] : [];
const allowArgs = ['--allow', path.join(root, 'privacy-allowlist.txt')];
const runScan = (cwd, ...scanArgs) => {
const r = spawnSync(process.execPath, [cli, 'privacy-scan', ...scanArgs, ...termsArgs, ...allowArgs], {
cwd, encoding: 'utf8', maxBuffer: 1 << 28,
});
return { status: r.status, text: mask(`${r.stdout ?? ''}${r.stderr ?? ''}`).trim(), terms: termsArgs.length > 0 };
};
const scanTree = runScan(root, tree);
// ---------------------------------------------------------------------------------------------
// The single commit, authored as CRT, in a throwaway repository next to the tree.
const repo = path.join(out, 'repo');
const emptyConfig = path.join(out, 'empty.gitconfig');
fs.writeFileSync(emptyConfig, '');
const env = { ...process.env, GIT_AUTHOR_NAME: AUTHOR.name, GIT_AUTHOR_EMAIL: AUTHOR.email, GIT_COMMITTER_NAME: AUTHOR.name, GIT_COMMITTER_EMAIL: AUTHOR.email, GIT_CONFIG_GLOBAL: emptyConfig, GIT_CONFIG_NOSYSTEM: '1' };
const g = (...a) => execFileSync('git', a, { cwd: repo, env, encoding: 'utf8', maxBuffer: 1 << 28 }).trim();
if (UPDATE) {
// One new commit on top of the public repository's current main: its history is the only history.
execFileSync('git', ['clone', '-q', '--branch', 'main', PUBLIC_REPO, repo], { env, encoding: 'utf8', maxBuffer: 1 << 28 });
g('config', 'core.autocrlf', 'false');
for (const entry of fs.readdirSync(repo)) if (entry !== '.git') fs.rmSync(path.join(repo, entry), { recursive: true, force: true });
fs.cpSync(tree, repo, { recursive: true });
} else {
fs.cpSync(tree, repo, { recursive: true });
g('init', '-q', '-b', 'main');
g('config', 'core.autocrlf', 'false');
}
g('add', '-A');
g('update-index', '--add', '--cacheinfo', `160000,${fwCommit},waybetter`);
if (UPDATE && !g('status', '--porcelain')) throw new Error('nothing changed: the public main already has this tree');
g('commit', '-q', '-m', UPDATE ? MESSAGE : 'wayBetter for X');
const commit = g('rev-parse', 'HEAD');
const parent = UPDATE ? g('rev-parse', 'HEAD~1') : null;
const changed = UPDATE ? g('diff', '--stat', 'HEAD~1', 'HEAD').split('\n').pop() : '';
const identity = g('log', '-1', '--format=%an <%ae> | %cn <%ce>');
const scanHistory = args.includes('--no-history-scan') ? { status: null, text: 'skipped' } : runScan(repo, '--history', '.');
const subStatus = g('ls-tree', 'HEAD', 'waybetter');
const gitmodules = g('show', 'HEAD:.gitmodules');
// ---------------------------------------------------------------------------------------------
// The framework's unpushed commits: authors, messages and the diff range through the same scan.
const fwDir = path.join(root, 'waybetter');
const fwGit = (...a) => execFileSync('git', a, { cwd: fwDir, encoding: 'utf8', maxBuffer: 1 << 28 }).trim();
let fwSection;
try {
try { fwGit('fetch', 'origin'); } catch { /* offline: use the refs as they are */ }
const upstream = fwGit('rev-parse', '--abbrev-ref', '@{upstream}');
const base = fwGit('merge-base', 'HEAD', upstream);
const ahead = fwGit('rev-list', '--count', `${base}..HEAD`);
const behind = fwGit('rev-list', '--count', `HEAD..${upstream}`);
const idents = fwGit('log', '--format=%an <%ae> | %cn <%ce>', `${base}..HEAD`).split('\n').filter(Boolean);
const counts = [...new Set(idents)].map(i => `${idents.filter(x => x === i).length} x ${i}`);
const tmp = path.join(out, 'fw-range');
fs.mkdirSync(tmp, { recursive: true });
fs.writeFileSync(path.join(tmp, 'range.patch'), fwGit('log', '-p', '--format=commit %H%nAuthor: %an <%ae>%nCommitter: %cn <%ce>%n%n%B', `${base}..HEAD`));
fs.writeFileSync(path.join(tmp, 'names.txt'), fwGit('diff', '--name-only', `${base}..HEAD`));
const scanRange = runScan(root, tmp);
const scanAll = runScan(fwDir, '--history', '.');
const log = fwGit('log', '--format=- %h %s', `${base}..HEAD`).split('\n').map(l => l.slice(0, 160));
fwSection = ['', '## Framework unpushed commits', '',
`Local branch is ${ahead} ahead and ${behind} behind ${upstream} (base ${base.slice(0, 10)}, head ${fwGit('rev-parse', 'HEAD').slice(0, 10)}).`, '',
`Authors and committers: ${counts.join('; ')}`, '',
`- Privacy scan over the patch text (messages, authors, every added and removed line) and the changed file names: exit ${scanRange.status}`, '', '```', scanRange.text, '```', '',
`- Privacy scan over the framework's whole history (every blob, path, message, identity): exit ${scanAll.status}`, '', '```', scanAll.text, '```', '',
'<details><summary>Commits</summary>', '', ...log, '', '</details>'];
fs.rmSync(tmp, { recursive: true, force: true });
} catch (error) {
fwSection = ['', '## Framework unpushed commits', '', `Could not be computed: ${mask(error.message).split('\n')[0]}`];
}
// ---------------------------------------------------------------------------------------------
// Report
const mb = n => (n / 1e6).toFixed(1);
const lines = [];
const p = (...t) => lines.push(...t);
p('# Public tree dry run', '',
`Generated by \`node scripts/public-tree.mjs\` from app HEAD \`${head.slice(0, 12)}\` and framework commit \`${fwCommit.slice(0, 12)}\` (the gitlink at HEAD unless \`--fw-commit\` was given). Re-run it whenever HEAD moves.`, '',
'## Result', '',
`- Files: **${all.length}** (HEAD has ${files.length - 1} plus the submodule; ${files.length - 1 - kept.length} excluded)`,
`- Size: **${mb(totalBytes)} MB** (git objects will be smaller: compressed)`,
`- Images and media in the set: ${images.length}`,
`- Initial commit: \`${commit.slice(0, 12)}\`, author and committer: ${identity}`,
`- Submodule entry: \`${subStatus}\``, '', '```', gitmodules, '```', '',
'## Excluded, and why', '', '| Files | Reason | Examples |', '| ---: | --- | --- |');
for (const [reason, entry] of excluded) p(`| ${entry.count} | ${reason} | ${entry.samples.map(s => `\`${s}\``).join(', ')} |`);
p('', 'Everything else tracked at HEAD is in the set. `.gitmodules` is rewritten to the public framework URL.', '',
'## Scans', '',
`- Forbidden-terms file: ${scanTree.terms ? 'present and used' : 'MISSING (only the machine account name was checked)'}`,
`- Privacy scan over the tree (file contents, binaries, archives and file names): exit ${scanTree.status}`, '', '```', scanTree.text || '(no output)', '```', '',
`- Privacy scan over the new repository's history (blobs, paths, commit message, identity): exit ${scanHistory.status}`, '', '```', scanHistory.text || '(no output)', '```', '',
`- Absolute user paths (\`C:\\Users\\\`, \`/Users/\`, \`/home/\`): **${pathHits.length}** hit(s), user names masked`);
if (pathHits.length) p('', '```', ...pathHits.slice(0, 60), pathHits.length > 60 ? `... ${pathHits.length - 60} more` : '', '```');
p('', `- Relative Markdown links to files that are not in the set: **${deadLinks.length}**`);
if (deadLinks.length) p('', '```', ...deadLinks, '```');
p('', `- Files over ${mb(MAX_FILE)} MB (review): ${big.length}`);
if (big.length) p('', ...big.map(f => ` - \`${f.rel}\` ${mb(f.size)} MB`));
p('', '## Images', '',
`${images.length} image and media files; ${images.length - unreviewed.length} match the reviewed list (scripts/public-tree.reviewed-images.json: path and sha256 of what a person looked at, or a generated card). Unreviewed or changed, to look at before publishing: **${unreviewed.length}**`, '', ...unreviewed.map(r => '- ' + r), '',
'## Publish (the coordinator runs these)', '',
'The framework goes first: push it, then use its pushed commit as the submodule pointer. Re-run this script with `--fw-commit <that sha>` if it differs from the gitlink above.', '',
...(UPDATE ? ['Update mode: one new commit on top of the public main (' + parent.slice(0, 12) + '): ' + changed + '. Push it with:', '', '```sh', `cd "${show(repo)}"`, 'git push origin main', '```', ''] : []),
'```sh',
'# 1. framework (already public; its remote is behind the local branch)',
'# after reading section "Framework unpushed commits" of the report and fixing what it lists:',
'# git -C waybetter push origin main',
'',
`# 2. re-run the dry run and read the report again`,
`node scripts/public-tree.mjs`,
'',
'# 3. the new repository: an empty repo at ' + PUBLIC_REPO + ' first (created on the forge by the owner or coordinator), then',
`cd "${show(repo)}"`,
`git remote add origin ${PUBLIC_REPO}`,
'git push -u origin main',
'```', '',
`The commit in \`${show(repo)}\` is already authored as ${AUTHOR.name} <${AUTHOR.email}> with the message "wayBetter for X". To use another message or a date, amend it there before pushing (\`git commit --amend\` with the same identity in the environment).`, '');
lines.push(...fwSection, '');
fs.writeFileSync(path.join(out, 'REPORT.md'), lines.join('\n'));
fs.writeFileSync(path.join(out, 'images.txt'), images.map(f => `${f.rel}\t${f.size}`).join('\n') + '\n');
if (UPDATE) console.log(`update commit ${commit.slice(0, 12)} on public main ${parent.slice(0, 12)}: ${changed}\npush: cd "${show(repo)}" && git push origin main`);
console.log(`public tree: ${all.length} files, ${mb(totalBytes)} MB, commit ${commit.slice(0, 12)}`);
console.log(`scan tree: exit ${scanTree.status}; scan history: exit ${scanHistory.status}; path hits: ${pathHits.length}; dead links: ${deadLinks.length}`);
console.log(`report: ${show(path.join(out, 'REPORT.md'))}`);

View file

@ -0,0 +1,49 @@
{
"note": "Images looked at by a person (hero, fix-like, thread-reader frames shown only @CRTkafa and @otheraccount; the rest are logos, icons and generated cards). Generated cards under apps/web/public/og/items and store/previews are covered by pattern. Anything not listed or with another hash is reported as unreviewed.",
"reviewed": {
"apps/desktop/src-tauri/icons/128x128.png": "4f9cbaaa7bc493b8d5194af3dc6291f27b091ee2a19c54cba70eeda7c1269e3d",
"apps/desktop/src-tauri/icons/128x128@2x.png": "5db8610d37798eccbfa97912e06ec6f3ea5d090a871766ed4035877cd43931bb",
"apps/desktop/src-tauri/icons/32x32.png": "900f86a59e78d33a50d23e400f8f35c8a6b7bf40e3b2bd89ef057a015fe15b08",
"apps/desktop/src-tauri/icons/64x64.png": "ec94bcc56ecb7d483fa424629855ad58ee12af11856954a7f02508e4f8d591f8",
"apps/desktop/src-tauri/icons/app-icon.png": "55804f5efdb837223362c56cd39c4041d0d030e33a5db153b702dbc3d43e6ce8",
"apps/desktop/src-tauri/icons/icon.icns": "d9658badddd2ed3d96a9da8ce6c4428efa979818ef5441a13a7b9a9b37391161",
"apps/desktop/src-tauri/icons/icon.ico": "422cd8b400e0c0a107bdcc0e8dc91d797f8e8b279aaaf363d5d4037c409e280a",
"apps/desktop/src-tauri/icons/icon.png": "cc9357e5d149b8d1e2f8fefea1ffee26fb0f72423f224bc19b5d9e3a2809db98",
"apps/web/public/app-icon.png": "55804f5efdb837223362c56cd39c4041d0d030e33a5db153b702dbc3d43e6ce8",
"apps/web/public/brand/brush-swash.svg": "9680bc3e94c9f159f8e702abeda48fd4bdec8cc054377ee778cd62bd253eca98",
"apps/web/public/brand/wb-icon-128.png": "056705755ecd72a704558e668be887ae6ad87bd25f5fc51668445270d52f1b76",
"apps/web/public/brand/wb-icon-256.png": "33a989958398e6cb547f8964d361d103f8c09bbe430744a9698daabe5ed72c2c",
"apps/web/public/brand/wb-icon-32.png": "f2961851434245ad5abb33cfce62285a844eb440af9f0bb72f2bdbf160e2d522",
"apps/web/public/brand/wb-icon-512.png": "e0425c029a5b3784164d16728ea45cf542164ea55f5312e4768d90ef5716a3b7",
"apps/web/public/brand/wb-icon-64.png": "940246b4f9d8789497e983c22c9b22bc1b4cbcd2f539b4aa5ca3d6053ed0ac2d",
"apps/web/public/brand/wb-icon.svg": "c0e43b05c111c4b6cbe813158bdd5cf19df1e34168a3fc456be1142cb6ac10b6",
"apps/web/public/brand/wb-mark-128.png": "40f249a1f33f7ffbcbce4c920e62144b162765fa537bac428c4d57a1802cff09",
"apps/web/public/brand/wb-mark-256.png": "1a6bf95513f796538a791a6d3b868f6dbceb34c80388d83db2f13dbe48562c92",
"apps/web/public/brand/wb-mark-32.png": "33152842c6431ea6da07015223020ad2734eebda9a640a1f8900ed4cb4dc47e2",
"apps/web/public/brand/wb-mark-512.png": "584dc90c4568a186a3c19446500b48c8e7ccb390081e8341bd8e5ad122e7284e",
"apps/web/public/brand/wb-mark-64.png": "c5b766c2a3232ea68d12d84cb05b1eb7d1c6374e53b6c883a007fb544271eb16",
"apps/web/public/brand/wb-mark-light.svg": "2007ba9de2b59139f5d8462290b789ce7d60f762943498b0e643a8af2c41ab9c",
"apps/web/public/brand/wb-mark-simple.svg": "0aaf4d04edf0d41218d872673e1ac980d53d16eb79f35dac3c3658ced9f71cb6",
"apps/web/public/brand/wb-mark.svg": "9140015c771cde09ece44ec8a11d76025c90e2ca947045758651b0f374f274f6",
"apps/web/public/demo/fix-like-m.jpg": "6143ad2df62d38eb8abce1f3ac624fc2323b2a34ee4a350c2d09845ed11fd4ac",
"apps/web/public/demo/fix-like-m.mp4": "b536b2d687270acf3196ca59139eb83a660cd32a5c9d366cbc1f803d6040383f",
"apps/web/public/demo/fix-like-m.webp": "4f0134b06cb34e9907997afc6b970e5c419498e65d52f64f0aadd7f1a46eab0e",
"apps/web/public/demo/fix-like.jpg": "6bd9b88581f7999f9cda94051e17581cfc7283b9c69d64d94dbcedb8d5ce54d1",
"apps/web/public/demo/fix-like.mp4": "6af489657b9f0ca46a7835e9d6b3fcf9ebbc760541137f5e0d28c9c182c3a380",
"apps/web/public/demo/fix-like.webp": "ee2c107f747f1f48f6954849cb75120c697a18791d0494856c5dc118c41bdbf7",
"apps/web/public/demo/hero.jpg": "3f951c12bb061d529f2d07638129bb76ddfd717902c2dd0729d44401eb42574b",
"apps/web/public/demo/hero.mp4": "abe14a93ea9e6f272de5a4706a26068e17a407d55ab4e6e7b6ac6780b472b3d9",
"apps/web/public/demo/hero.webp": "48a1f58e2a8bae501745e95fb46fe30b3a42061c5f2b9e582fa07963a97ae82a",
"apps/web/public/git-crt-logo.svg": "997bea1b94c9b40a4f59d45b127119a51b364edb7d9d689045d4a97876739e89",
"apps/web/public/og/home.png": "7ce32572720777713b26f7ad3d42f04db116e16a18da6ab42cf3053702e070f6",
"apps/web/public/og/store.png": "6eb9b284a3bccf173dd72befca20fb6f3e9955a8c1083df09f0a81efc7e66d80",
"apps/web/public/og/x.png": "128e751ba1a2d270cf2a1266594b934f2487601db4054c87b51cb8bc93ac62d8",
"apps/web/public/wb-mark.svg": "19f08a0321c008b94c8ea691b8ac9fb5f107c6fa8b083418d4a8cb4f82d62e53",
"docs/brand/logo-source.png": "b8f1a64b7104be1ed2d32f1b1714d27782c2ee273b204a3c9fde7f08b8e90695",
"store/x/areas/reader/media/copy-as-markdown.png": "d9aa931d19a3d84282c4cc1776b8cab4bce64496bd0278898a730fe7723720a8",
"store/x/areas/reader/media/cover.webp": "c5f7d41a144c6a2e7be278df14b21bbbfd07c384cfe618fbc6530d01598ae05f",
"store/x/areas/reader/media/demo.mp4": "e74810ddf6210ddbd185e37123d41cfcc214c9bcae5eee3152a6392ee92cc1b1",
"store/x/areas/reader/media/demo.webp": "62ee097cdab833b2cc1dc10d1503fa2a16a501d1a97a4ac7d62c616438e7d1b2",
"store/x/areas/reader/media/reading-view.webp": "3c24634b09d7c9a2fa79bf4fa62c7d9704ed15a38281ef253ae2bcbf6410c3f7"
}
}

21
scripts/release-linux.mjs Normal file
View file

@ -0,0 +1,21 @@
#!/usr/bin/env node
// Adds the Linux build to the release (a wrapper of `waybetter release linux`, see
// waybetter/packages/waybetter/cli/release.mjs; configured by waybetter.release.json).
//
// node scripts/release-linux.mjs --wsl [Ubuntu-22.04] build the COMMITTED state in WSL, scan it here, then:
// node scripts/release-linux.mjs --appimage <f.AppImage> --deb <f.deb>
// signs the AppImage here (the Linux update payload; the key stays on this machine), copies both
// into releases/upload and adds linux-x86_64 to releases/native/latest.json.
//
// Run scripts/release.mjs (Windows) first: latest.json must exist for this version. Nothing is uploaded.
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { releaseCommand } from '../waybetter/packages/waybetter/cli/release.mjs';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
try {
await releaseCommand(['linux', ...process.argv.slice(2)], { cwd: root });
} catch (error) {
console.error(`release-linux: ${error instanceof Error ? error.message : error}`);
process.exit(1);
}

51
scripts/release-macos.mjs Normal file
View file

@ -0,0 +1,51 @@
#!/usr/bin/env node
// Adds a macOS build to the release: signs the updater bundle here (the private key never leaves
// this machine), copies the files into releases/upload/ and adds the darwin platforms to
// releases/native/latest.json next to the ones already there. It never uploads anything.
//
// Or let the framework do the build too, from the COMMITTED state (HEAD + the submodule at its pointer,
// exported with git archive, built on the Mac over SSH, scanned here):
// WAYBETTER_MAC_SSH=<user>@<host> WAYBETTER_MAC_SSH_KEY=<key file> node scripts/release-macos.mjs --build-only
// (without --build-only it continues with the signing below). The manual steps that follow are what it runs.
//
// The macOS build itself runs on the MacBook, unsigned (no TAURI_SIGNING_PRIVATE_KEY there), from
// a clean checkout of the release commit:
// bun install && bun run --cwd packages/contracts build
// echo '{"bundle":{"macOS":{"signingIdentity":"-"}}}' > /tmp/adhoc.json # no Developer ID yet
// cd apps/desktop && bun ../../waybetter/packages/waybetter/bin/waybetter.mjs build-env -- \
// bunx tauri build --target universal-apple-darwin --bundles app,dmg --ci --config /tmp/adhoc.json
// (`waybetter build-env`: without it the binary holds about 1,800 absolute build paths with the
// Mac account name; with it they read /cargo, /rustup, /src and /home.)
// (rustup with the aarch64-apple-darwin and x86_64-apple-darwin targets; Homebrew rust lacks the
// x86_64 std.) The ad-hoc signature seals the bundle, so a downloaded copy gets Gatekeeper's
// "unidentified developer" path (System Settings > Privacy & Security > Open Anyway) instead of
// "is damaged". Tauri still writes the updater bundle (<target>/universal-apple-darwin/release/bundle/macos/
// wayBetter for X.app.tar.gz) and then exits non-zero because it cannot sign it; that is expected.
// Copy the .dmg and the .app.tar.gz back here, then:
//
// node scripts/release-macos.mjs --dmg <file.dmg> --updater <file.app.tar.gz>
//
// Both files go through `waybetter privacy-scan` first (the dmg's image and the .app inside the
// updater bundle are opened): a forbidden name in either stops this script before anything is
// copied or signed.
//
// A universal build serves both darwin-aarch64 and darwin-x86_64. Run scripts/release.mjs (Windows)
// first: this script keeps every platform already in latest.json and refuses a version mismatch.
//
// The work is the framework's (`waybetter release macos`, waybetter/packages/waybetter/cli/release.mjs),
// configured by waybetter.release.json.
//
// Env:
// BT_KEYS_DIR folder holding native.key (default: ~/.better-twttr-keys). Never commit it.
// CDN_BASE public base URL (default: https://cdn1.crt.fyi/better-twttr)
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { releaseCommand } from '../waybetter/packages/waybetter/cli/release.mjs';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
try {
await releaseCommand(['macos', ...process.argv.slice(2)], { cwd: root });
} catch (error) {
console.error(`release-macos: ${error instanceof Error ? error.message : error}`);
process.exit(1);
}

33
scripts/release.mjs Normal file
View file

@ -0,0 +1,33 @@
#!/usr/bin/env node
// Builds a signed Windows release and writes the update manifest. It never uploads anything:
// it prints the exact upload steps for the owner to run. The work is the framework's
// (`waybetter release windows`, waybetter/packages/waybetter/cli/release.mjs), configured by
// waybetter.release.json (product and file names, key folder, CDN and API URLs, and the shared
// contract's NativeRelease schema as the manifest validator).
//
// node scripts/release.mjs [--skip-build] [--notes "text"]
//
// Privacy: the build runs with `waybetter build-env` (no absolute build path, so no account name,
// in the binary), and the installer (opened with 7-Zip), the binary and the front end must pass
// `waybetter privacy-scan` against ~/.better-twttr-keys/forbidden-names.txt before anything is
// copied to releases/. The .pdb next to the binary holds every path: never publish it.
//
// Env:
// CARGO_TARGET_DIR optional; the bundle is read from <it>/release/bundle/nsis
// BT_KEYS_DIR folder holding native.key (default: ~/.better-twttr-keys). Never commit it.
// CDN_BASE public base URL for installers (default: https://cdn1.crt.fyi/better-twttr)
// DEPLOY_TARGET ssh target for the printed steps, e.g. user@host (no default: printed as a placeholder)
// CDN_DIR remote folder behind CDN_BASE (placeholder when unset)
// RELEASES_DIR remote API RELEASES_DIR (placeholder when unset)
// WAYBETTER_FORBIDDEN_TERMS another terms file; WAYBETTER_7Z 7-Zip when it is not installed in Program Files
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { releaseCommand } from '../waybetter/packages/waybetter/cli/release.mjs';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
try {
await releaseCommand(['windows', ...process.argv.slice(2)], { cwd: root });
} catch (error) {
console.error(`release: ${error instanceof Error ? error.message : error}`);
process.exit(1);
}

49
scripts/sign-store.mjs Normal file
View file

@ -0,0 +1,49 @@
#!/usr/bin/env node
// Signs the wayBetter Store catalog with the store's Ed25519 key (detached signature), through the
// framework CLI (`waybetter store sign|verify`, waybetter/packages/waybetter/cli/store.mjs) with
// wayBetter for X's defaults.
//
// node scripts/sign-store.mjs --init create the store key once (never overwrites)
// node scripts/sign-store.mjs [catalog.json] sign (default apps/web/public/store/catalog.json)
// node scripts/sign-store.mjs --verify [file] verify only (signature and catalog rules)
//
// Options: --key <path> (private key, default ~/.better-twttr-keys/store.key or $WAYBETTER_STORE_KEY),
// --pub <path> (public key, default apps/desktop/src-tauri/keys/store.pub, compiled into the app).
//
// The signature file `<catalog>.sig` is the base64 of the 64-byte Ed25519 signature over the exact
// catalog bytes. The public key file is the base64 of the raw 32-byte key. The private key is a
// PKCS#8 PEM that stays in the key folder: nothing here prints, copies or moves it.
import { homedir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { storeCommand } from '../waybetter/packages/waybetter/cli/store.mjs';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const DEFAULT_KEY = process.env.WAYBETTER_STORE_KEY || join(homedir(), '.better-twttr-keys', 'store.key');
const DEFAULT_PUB = join(ROOT, 'apps/desktop/src-tauri/keys/store.pub');
const DEFAULT_CATALOG = join(ROOT, 'apps/web/public/store/catalog.json');
function args(argv) {
const out = { init: false, verifyOnly: false, key: DEFAULT_KEY, pub: DEFAULT_PUB, file: DEFAULT_CATALOG };
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === '--init') out.init = true;
else if (arg === '--verify') out.verifyOnly = true;
else if (arg === '--key') out.key = resolve(argv[++i]);
else if (arg === '--pub') out.pub = resolve(argv[++i]);
else if (arg.startsWith('--')) throw new Error(`unknown option ${arg}`);
else out.file = resolve(arg);
}
return out;
}
try {
const o = args(process.argv.slice(2));
const argv = o.init ? ['sign', '--init', '--key', o.key, '--pub', o.pub]
: o.verifyOnly ? ['verify', o.file, '--pub', o.pub, '--app', 'x']
: ['sign', o.file, '--key', o.key, '--pub', o.pub];
for (const line of await storeCommand(argv)) console.log(line);
} catch (error) {
console.error(`sign-store: ${error.message}`);
process.exit(1);
}

42
scripts/store.config.mjs Normal file
View file

@ -0,0 +1,42 @@
// wayBetter for X's part of the shared wayBetter Store (app id "x"), for `waybetter store build`
// (the framework CLI; `node scripts/build-store.mjs` runs it with the paths below).
//
// The items are the folders under store/x/ (one per item; layout in store/README.md, read by
// scripts/store/source.mjs): a pull request that adds a folder adds an item. The build writes
// plugins/<file>.plugin.js the plugin exactly as its folder (or the app, for bundled ones) has it
// themes/<id>.json the theme file (built-in themes exported like Appearance → Export does)
// previews/<kind>-<id>.svg the folder's preview, else one drawn from the item (scripts/store/preview.mjs)
// The first-party plugins are read from $WAYBETTER_STORE_PLUGINS when set (e.g. an export of
// committed files), else from apps/desktop/src-tauri/bundled-plugins.
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { readStoreSource } from './store/source.mjs';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
export const APP = 'x';
/** The folders under store/x/ as build entries, with the problems that would stop a build. */
export async function source() {
const { BUILTIN_THEMES } = await import('../apps/desktop/src/inject/themeSpec.ts');
const { THEME_SCHEMA_URL } = await import('../waybetter/packages/runtime/src/themeApi.ts');
const { sanitizeSpec } = await import('../waybetter/packages/runtime/src/themeSpec.ts');
const { X_TABLE } = await import('../apps/desktop/src/areas/table.ts');
const { supersededFiles } = await import('../waybetter/packages/runtime/src/featureTable.ts');
return readStoreSource({
// Bundled files a built-in feature replaced ("bt-<name>.plugin.js" installed, "<name>.plugin.js" bundled).
superseded: supersededFiles(X_TABLE).map(entry => entry.file.replace(/^bt-/, '')),
root: ROOT, app: APP,
bundledDir: process.env.WAYBETTER_STORE_PLUGINS || join(ROOT, 'apps/desktop/src-tauri/bundled-plugins'),
builtinThemes: BUILTIN_THEMES, themeSchemaUrl: THEME_SCHEMA_URL, sanitizeTheme: sanitizeSpec,
});
}
export default {
app: APP,
name: 'wayBetter Store',
async items() {
const { entries, problems } = await source();
if (problems.length) throw new Error(`the Store source has problems (node scripts/check-store.mjs explains each):\n ${problems.join('\n ')}`);
return entries;
},
};

43
scripts/store/areas.mjs Normal file
View file

@ -0,0 +1,43 @@
// The area plugins on the site: Compose+, Reader+, … are built into wayBetter for X (feature
// modules compiled into the app, docs/AREA-PLUGINS.md), so they are never in the signed catalog and
// have nothing to install. Each still gets a page in the Store (/store/areas/<id>/) from one folder:
//
// store/<app>/areas/<id>/item.json { "category", "tags", "license", "credits", cover/screenshots/video }
//
// The folder name is the area's id in the app's feature table; the name, description and feature
// list come from the table and the app's own words, so the page and the app cannot disagree.
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
import { join } from 'node:path';
export const AREA_CATEGORIES = ['reading', 'writing', 'filters', 'focus', 'tools'];
const FIELDS = ['category', 'tags', 'license', 'credits', 'cover', 'screenshots', 'video'];
const text = (value, max) => typeof value === 'string' && [...value].length <= max && !/[<>]|[\u0000-\u001f\u007f]/.test(value);
/**
* Reads store/<app>/areas/. `ids`: the areas of the app's feature table, in its order. Returns one
* entry per area ({ id, category, tags, license, credits, dir }) and the problems (a missing or
* extra folder, unknown fields, bad values).
*/
export function readAreaSource({ root, app, ids }) {
const base = join(root, 'store', app, 'areas');
const problems = [];
const entries = [];
const folders = existsSync(base) ? readdirSync(base).filter(name => statSync(join(base, name)).isDirectory()).sort() : [];
for (const extra of folders.filter(name => !ids.includes(name))) problems.push(`store/${app}/areas/${extra}: no area of the app has this id (${ids.join(', ')})`);
for (const id of ids) {
const where = `store/${app}/areas/${id}`;
const path = join(base, id, 'item.json');
if (!existsSync(path)) { problems.push(`${where}: item.json is missing (every area has a page)`); continue; }
let info;
try { info = JSON.parse(readFileSync(path, 'utf8')); } catch (error) { problems.push(`${where}/item.json: not valid JSON (${error.message})`); continue; }
if (!info || typeof info !== 'object' || Array.isArray(info)) { problems.push(`${where}/item.json: must be an object`); continue; }
for (const key of Object.keys(info)) if (!FIELDS.includes(key)) problems.push(`${where}/item.json: unknown field "${key}" (allowed: ${FIELDS.join(', ')})`);
if (!AREA_CATEGORIES.includes(info.category)) problems.push(`${where}/item.json: "category" must be one of ${AREA_CATEGORIES.join(', ')}`);
const tags = Array.isArray(info.tags) ? info.tags : [];
if (!Array.isArray(info.tags) || tags.length > 12 || tags.some(tag => typeof tag !== 'string' || !tag.trim() || [...tag].length > 32)) problems.push(`${where}/item.json: tags: a list of at most 12 words, each 1 to 32 characters`);
if (info.license !== undefined && (!text(info.license, 60) || !info.license.trim())) problems.push(`${where}/item.json: "license" is 1 to 60 plain characters`);
if (info.credits !== undefined && !text(info.credits, 600)) problems.push(`${where}/item.json: "credits" is at most 600 plain characters`);
entries.push({ id, category: info.category, tags: tags.filter(tag => typeof tag === 'string'), license: info.license, credits: info.credits, dir: where });
}
return { entries, problems };
}

107
scripts/store/og-images.mjs Normal file
View file

@ -0,0 +1,107 @@
#!/usr/bin/env node
// Link-preview pictures (Open Graph / Twitter card, 1200×630) for the site, drawn with the site's
// own look and a headless Chromium (Playwright, a dev dependency of apps/desktop):
// apps/web/public/og/home.png, x.png, store.png the pages
// apps/web/public/og/items/<kind>-<slug>.jpg one per Store item in the published catalog
// The site build uses an item's picture when the file exists and the Store's otherwise
// (apps/web/store-pages.ts), so this is optional after adding an item: run it, commit the new file.
//
// node scripts/store/og-images.mjs draw what is missing
// node scripts/store/og-images.mjs --all redraw everything
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync } from 'node:fs';
import { createRequire } from 'node:module';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
const PUBLIC = join(ROOT, 'apps/web/public');
const OUT = join(PUBLIC, 'og');
const all = process.argv.includes('--all');
const { chromium } = createRequire(join(ROOT, 'apps/desktop/package.json'))('playwright');
const { itemSlugs } = await import('../../apps/web/seo.ts');
const { appInfo } = await import('../../apps/web/site.config.ts');
const esc = value => String(value).replace(/[&<>"]/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[ch]);
const dataUrl = (path, type) => `data:${type};base64,${readFileSync(path).toString('base64')}`;
const mark = dataUrl(join(PUBLIC, 'brand/wb-mark-simple.svg'), 'image/svg+xml');
const catalog = JSON.parse(readFileSync(join(PUBLIC, 'store/catalog.json'), 'utf8'));
const preview = item => dataUrl(join(PUBLIC, 'store', item.preview.slice('https://waybetter.fyi/store/'.length)), item.preview.endsWith('.png') ? 'image/png' : 'image/svg+xml');
const page = body => `<!doctype html><html><head><meta charset="utf-8">
<link href="https://fonts.googleapis.com/css2?family=Geist:wght@400..800&family=Geist+Mono:wght@500&family=Instrument+Serif:ital@1&display=block" rel="stylesheet">
<style>
* { box-sizing: border-box; margin: 0; }
html, body { width: 1200px; height: 630px; }
body { position: relative; overflow: hidden; background: #07080c; color: #eef0f7; font-family: Geist, 'Segoe UI', sans-serif; -webkit-font-smoothing: antialiased; }
.wash { position: absolute; inset: 0; background:
radial-gradient(46% 60% at 82% 38%, rgba(120, 86, 255, 0.34), transparent 70%),
radial-gradient(36% 48% at 60% 8%, rgba(34, 211, 238, 0.16), transparent 70%),
radial-gradient(34% 44% at 4% 0%, rgba(79, 107, 255, 0.26), transparent 70%); }
.dots { position: absolute; inset: 0; background-image: radial-gradient(rgba(142, 149, 171, 0.2) 1px, transparent 1px); background-size: 28px 28px;
-webkit-mask-image: radial-gradient(70% 80% at 70% 30%, #000 10%, transparent 75%); }
.in { position: absolute; inset: 0; padding: 64px 72px; display: flex; flex-direction: column; }
.brand { display: flex; align-items: center; gap: 16px; font-size: 30px; font-weight: 650; letter-spacing: -0.02em; }
.brand img { height: 40px; }
.brand span { color: #8e95ab; font-weight: 500; }
.kicker { margin-top: auto; font: 500 19px 'Geist Mono', monospace; letter-spacing: 0.08em; text-transform: uppercase; color: #8e95ab; }
.kicker b { color: #3ddc97; font-weight: 500; }
h1 { margin-top: 18px; font-size: 104px; line-height: 0.94; font-weight: 700; letter-spacing: -0.052em; max-width: 640px; }
h1.long { font-size: 78px; }
h1.longer { font-size: 62px; }
em { white-space: nowrap; font-family: 'Instrument Serif', serif; font-style: italic; font-weight: 400; font-size: 1.1em; letter-spacing: -0.025em;
background: linear-gradient(128deg, #7cc8ff 0%, #1d9bf0 42%, #7856ff 100%); -webkit-background-clip: text; color: transparent; padding-right: 0.08em; }
.sub { margin-top: 22px; font-size: 27px; line-height: 1.35; color: #c3c7d4; max-width: 600px; letter-spacing: -0.01em; }
.line { position: absolute; left: 0; right: 0; bottom: 0; height: 6px; background: linear-gradient(90deg, #4f6bff, #22d3ee 55%, #a855f7); }
.art img { position: absolute; border-radius: 16px; box-shadow: 0 0 0 1px rgba(238, 240, 247, 0.14), 0 40px 90px -20px rgba(0, 0, 0, 0.9), 0 70px 130px -40px rgba(79, 107, 255, 0.6); }
.a1 { width: 420px; right: 150px; top: 60px; transform: rotate(-7deg); }
.a2 { width: 420px; right: -40px; top: 170px; transform: rotate(5deg); }
.a3 { width: 420px; right: 96px; top: 310px; transform: rotate(-1.5deg); }
.one { width: 520px; right: 56px; top: 150px; transform: rotate(3deg); }
.glow { position: absolute; right: 40px; top: 120px; width: 560px; height: 420px; border-radius: 50%; filter: blur(70px); opacity: 0.75;
background: radial-gradient(50% 60% at 30% 60%, rgba(79, 107, 255, 0.6), transparent 70%), radial-gradient(50% 60% at 80% 40%, rgba(168, 85, 247, 0.5), transparent 70%); }
.wide h1 { max-width: none; }
.wide .sub { max-width: 900px; }
</style></head><body><div class="wash"></div><div class="dots"></div>${body}<div class="line"></div></body></html>`;
const brand = (sub = '') => `<div class="brand"><img src="${mark}" alt="">wayBetter${sub ? ` <span>${esc(sub)}</span>` : ''}</div>`;
const featured = (() => {
const path = join(ROOT, 'store/featured.json');
const keys = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : [];
const picked = keys.map(key => catalog.items.find(item => item.apps.some(app => `${app}/${item.kind}/${item.id}` === key))).filter(Boolean);
return (picked.length >= 3 ? picked : catalog.items).slice(0, 3);
})();
const count = kind => catalog.items.filter(item => item.kind === kind).length;
const jobs = [
{ file: 'home.png', html: page(`<div class="in wide">${brand()}<p class="kicker"><b>(FOSS)</b> Everything is an app now.</p><h1>The apps you use, <em>way better.</em></h1><p class="sub">A light native window, themes, plugins and fixes for the apps you already use. Free and open source.</p></div>`) },
{ file: 'x.png', html: page(`<div class="in wide">${brand('for X')}<p class="kicker"><b>(FOSS)</b> Free &amp; open source · GPL-3.0</p><h1>X, <em>extended.</em></h1><p class="sub">Tabs, split panes, every account side by side, themes, plugins and fixes for X's own bugs.</p></div>`) },
{ file: 'store.png', html: page(`<div class="glow"></div><div class="art">${featured.map((item, index) => `<img class="a${index + 1}" src="${preview(item)}" alt="">`).join('')}</div><div class="in">${brand('Store')}<p class="kicker"><b>(FOSS)</b> One signed catalog</p><h1>Make every app <em>yours.</em></h1><p class="sub">${count('theme')} themes and ${count('plugin')} plugins. Read the code, then install in one click.</p></div>`) },
];
const slugs = itemSlugs(catalog.items);
const wanted = new Set();
for (const item of catalog.items) {
const file = `items/${item.kind}-${slugs.get(item)}.jpg`;
wanted.add(file);
const size = item.name.length > 22 ? 'longer' : item.name.length > 12 ? 'long' : '';
jobs.push({
file, jpeg: true,
html: page(`<div class="glow"></div><div class="art"><img class="one" src="${preview(item)}" alt=""></div><div class="in">${brand('Store')}<p class="kicker">${item.kind === 'plugin' ? 'Plugin' : 'Theme'} · for ${esc(item.apps.map(app => appInfo(app).site).join(', '))}</p><h1 class="${size}" style="max-width: 560px">${esc(item.name)}</h1><p class="sub" style="max-width: 520px">${esc(item.author ? `by ${item.author} · ` : '')}v${esc(item.version)} · free in the wayBetter Store</p></div>`),
});
}
mkdirSync(join(OUT, 'items'), { recursive: true });
// A picture whose item left the catalog goes too.
for (const name of readdirSync(join(OUT, 'items'))) if (!wanted.has(`items/${name}`)) rmSync(join(OUT, 'items', name));
const todo = jobs.filter(job => all || !existsSync(join(OUT, job.file)));
if (todo.length) {
const browser = await chromium.launch();
const tab = await (await browser.newContext({ viewport: { width: 1200, height: 630 }, deviceScaleFactor: 1 })).newPage();
for (const job of todo) {
await tab.setContent(job.html, { waitUntil: 'networkidle' });
await tab.evaluate(() => document.fonts.ready);
await tab.screenshot({ path: join(OUT, job.file), ...(job.jpeg ? { type: 'jpeg', quality: 86 } : { type: 'png' }) });
}
await browser.close();
}
console.log(`og images: ${todo.length} drawn, ${jobs.length - todo.length} kept → apps/web/public/og/`);

141
scripts/store/preview.mjs Normal file
View file

@ -0,0 +1,141 @@
// Store previews as SVG, drawn from the same data the app uses: a theme's colors, shape, layout
// and background become a miniature X timeline (left rail, column of posts, sidebar); a plugin gets
// a card with its name, category glyph and permissions. Used by scripts/build-store.mjs; the site's
// /themes/ and /plugins/ pages and the in-app store show the files it writes.
const esc = value => String(value).replace(/[&<>"']/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[ch]);
const hex = value => (/^#[0-9a-f]{6}$/i.test(value ?? '') ? value : null);
/** X's own default (light) palette, for a theme that keeps X's colors. */
const X_LIGHT = { page: '#ffffff', bg: '#ffffff', surface: '#f7f9f9', elevated: '#eff3f4', border: '#eff3f4', text: '#0f1419', muted: '#536471', accent: '#1d9bf0', inverse: '#0f1419', onInverse: '#ffffff' };
function palette(theme) {
const c = theme.colors ?? X_LIGHT;
const pick = (key, fallback) => hex(c[key]) ?? fallback;
const bg = pick('bg', X_LIGHT.bg);
const text = pick('text', X_LIGHT.text);
const accent = pick('accent', X_LIGHT.accent);
return {
page: pick('page', bg), bg, surface: pick('surface', bg), elevated: pick('elevated', bg), border: pick('border', pick('surface', bg)),
text, muted: pick('muted', text), accent, inverse: pick('inverse', accent), onInverse: pick('onInverse', bg),
};
}
function backgroundDefs(theme, p, W, H) {
const bg = theme.background ?? { kind: 'none' };
if (bg.kind === 'gradient' && hex(bg.from) && hex(bg.to)) {
const angle = ((Number(bg.angle) || 180) - 90) * Math.PI / 180;
const x = Math.cos(angle) / 2, y = Math.sin(angle) / 2;
const glow = hex(bg.glow);
return {
defs: `<linearGradient id="g" x1="${0.5 - x}" y1="${0.5 - y}" x2="${0.5 + x}" y2="${0.5 + y}"><stop offset="0" stop-color="${bg.from}"/><stop offset="1" stop-color="${bg.to}"/></linearGradient>`
+ (glow ? `<radialGradient id="glow" cx="0.5" cy="0.15" r="0.6"><stop offset="0" stop-color="${glow}" stop-opacity="0.55"/><stop offset="1" stop-color="${glow}" stop-opacity="0"/></radialGradient>` : ''),
fill: `<rect width="${W}" height="${H}" fill="url(#g)"/>${glow ? `<rect width="${W}" height="${H}" fill="url(#glow)"/>` : ''}`,
};
}
if (bg.kind === 'image' && typeof bg.url === 'string' && /^data:image\/(png|jpeg|webp|gif|avif);base64,/.test(bg.url)) {
const dim = Math.min(0.9, Math.max(0, Number(bg.dim) || 0));
return { defs: '', fill: `<rect width="${W}" height="${H}" fill="${p.page}"/><image href="${bg.url}" width="${W}" height="${H}" preserveAspectRatio="xMidYMid slice"/><rect width="${W}" height="${H}" fill="${p.page}" opacity="${dim}"/>` };
}
if (bg.kind === 'pattern' && hex(bg.ink)) {
const opacity = Math.min(0.6, Math.max(0.04, Number(bg.opacity) || 0.1));
const shapes = {
dots: `<circle cx="6" cy="6" r="1.4" fill="${bg.ink}"/>`,
grid: `<path d="M12 0V12H0" fill="none" stroke="${bg.ink}" stroke-width="0.8"/>`,
diagonal: `<path d="M0 12L12 0" stroke="${bg.ink}" stroke-width="0.8"/>`,
scanlines: `<rect width="12" height="1" y="0" fill="${bg.ink}"/><rect width="12" height="1" y="6" fill="${bg.ink}"/>`,
paper: `<circle cx="3" cy="4" r="0.6" fill="${bg.ink}"/><circle cx="9" cy="9" r="0.5" fill="${bg.ink}"/>`,
clouds: `<ellipse cx="6" cy="7" rx="5" ry="2.4" fill="${bg.ink}"/>`,
};
const size = bg.pattern === 'clouds' ? 48 : 12;
return {
defs: `<pattern id="pt" width="${size}" height="${size}" patternUnits="userSpaceOnUse"><g transform="scale(${size / 12})" opacity="${opacity}">${shapes[bg.pattern] ?? shapes.dots}</g></pattern>`,
fill: `<rect width="${W}" height="${H}" fill="${p.page}"/><rect width="${W}" height="${H}" fill="url(#pt)"/>`,
};
}
return { defs: '', fill: `<rect width="${W}" height="${H}" fill="${p.page}"/>` };
}
/** A 640×400 miniature of X in `theme` (a sanitized ThemeSpec). */
export function themePreviewSvg(theme) {
const W = 640, H = 400;
const p = palette(theme);
const radius = Math.min(18, Math.max(0, Number(theme.shape?.radius ?? 16))) * 0.7;
const pill = Math.min(20, Number(theme.shape?.button ?? 9999)) ;
const avatar = theme.shape?.avatar ?? 'circle';
const cards = Boolean(theme.layout?.cards);
const frame = Boolean(theme.layout?.frame);
const density = theme.layout?.density ?? 'default';
const postH = density === 'compact' ? 88 : density === 'comfortable' ? 110 : 98;
const { defs, fill } = backgroundDefs(theme, p, W, H);
const colX = 170, colW = 300, sideX = 490, sideW = 130;
const out = [];
out.push(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${H}" width="${W}" height="${H}" role="img" aria-label="${esc(theme.name)} theme preview">`);
out.push(`<title>${esc(theme.name)}</title><defs>${defs}<clipPath id="clip"><rect width="${W}" height="${H}" rx="14"/></clipPath></defs><g clip-path="url(#clip)">${fill}`);
// Left rail: logo, nav items, the Post button.
out.push(`<circle cx="118" cy="34" r="11" fill="${p.text}"/>`);
for (let i = 0; i < 6; i += 1) {
const y = 72 + i * 34;
out.push(`<circle cx="104" cy="${y}" r="7" fill="none" stroke="${p.text}" stroke-width="2"/><rect x="118" y="${y - 4}" width="${28 + (i * 13) % 24}" height="8" rx="4" fill="${p.text}" opacity="${i === 0 ? 1 : 0.8}"/>`);
}
out.push(`<rect x="92" y="290" width="68" height="30" rx="${Math.min(15, pill)}" fill="${p.inverse}"/><rect x="112" y="301" width="28" height="8" rx="4" fill="${p.onInverse}"/>`);
// Timeline column.
if (!cards) out.push(`<rect x="${colX}" y="0" width="${colW}" height="${H}" fill="${p.bg}"${frame ? ` stroke="${p.border}"` : ''}/>`);
out.push(`<rect x="${colX + 16}" y="16" width="70" height="10" rx="5" fill="${p.text}"/><rect x="${colX + 150}" y="40" width="70" height="3" rx="1.5" fill="${p.accent}"/>`);
out.push(`<rect x="${colX}" y="48" width="${colW}" height="1" fill="${p.border}"/>`);
const avatarShape = (x, y, color) => avatar === 'circle' ? `<circle cx="${x + 15}" cy="${y + 15}" r="15" fill="${color}"/>` : `<rect x="${x}" y="${y}" width="30" height="30" rx="${avatar === 'rounded' ? 8 : 2}" fill="${color}"/>`;
const tones = [p.accent, p.muted, p.inverse];
for (let i = 0; i < 3; i += 1) {
const top = 58 + i * (postH + (cards ? 10 : 0));
if (cards) out.push(`<rect x="${colX + 4}" y="${top - 4}" width="${colW - 8}" height="${postH}" rx="${radius}" fill="${p.bg}" stroke="${p.border}"/>`);
out.push(avatarShape(colX + 14, top + 6, tones[i % tones.length]));
out.push(`<rect x="${colX + 54}" y="${top + 8}" width="${60 + i * 14}" height="8" rx="4" fill="${p.text}"/><rect x="${colX + 124 + i * 14}" y="${top + 8}" width="46" height="8" rx="4" fill="${p.muted}" opacity="0.7"/>`);
const lines = [210, 226 - i * 30, 150 + i * 20].slice(0, density === 'compact' ? 2 : 3);
lines.forEach((width, line) => out.push(`<rect x="${colX + 54}" y="${top + 26 + line * 14}" width="${width}" height="7" rx="3.5" fill="${p.text}" opacity="0.72"/>`));
const actions = top + postH - 20;
for (let a = 0; a < 4; a += 1) {
const liked = i === 1 && a === 2;
out.push(`<circle cx="${colX + 60 + a * 58}" cy="${actions}" r="4.5" fill="${liked ? p.accent : 'none'}" stroke="${liked ? p.accent : p.muted}" stroke-width="1.6"/><rect x="${colX + 69 + a * 58}" y="${actions - 3}" width="14" height="6" rx="3" fill="${liked ? p.accent : p.muted}" opacity="0.8"/>`);
}
if (!cards) out.push(`<rect x="${colX}" y="${top + postH - 6}" width="${colW}" height="1" fill="${p.border}"/>`);
}
// Sidebar: search pill and a "What's happening" card.
out.push(`<rect x="${sideX}" y="12" width="${sideW}" height="28" rx="14" fill="${p.surface}" stroke="${p.border}"/><circle cx="${sideX + 16}" cy="26" r="5" fill="none" stroke="${p.muted}" stroke-width="1.6"/>`);
out.push(`<rect x="${sideX}" y="54" width="${sideW}" height="170" rx="${radius}" fill="${p.surface}" stroke="${p.border}"/><rect x="${sideX + 12}" y="68" width="86" height="9" rx="4.5" fill="${p.text}"/>`);
for (let i = 0; i < 4; i += 1) {
out.push(`<rect x="${sideX + 12}" y="${92 + i * 32}" width="44" height="6" rx="3" fill="${p.muted}" opacity="0.8"/><rect x="${sideX + 12}" y="${103 + i * 32}" width="${70 + (i * 17) % 30}" height="7" rx="3.5" fill="${p.text}"/>`);
}
out.push(`<rect x="${sideX}" y="236" width="${sideW}" height="52" rx="${radius}" fill="${p.elevated}" stroke="${p.border}"/><rect x="${sideX + 12}" y="252" width="60" height="7" rx="3.5" fill="${p.text}"/><rect x="${sideX + 84}" y="248" width="34" height="16" rx="${Math.min(8, pill)}" fill="${p.inverse}"/>`);
out.push('</g></svg>');
return out.join('');
}
const GLYPHS = {
reading: 'M4 6h9a3 3 0 0 1 3 3v11a2 2 0 0 0-2-2H4zM28 6h-9a3 3 0 0 0-3 3v11a2 2 0 0 1 2-2h10z',
writing: 'M6 26l1.5-6L21 6.5l4.5 4.5L12 24.5zM18.5 9l4.5 4.5',
filters: 'M5 7h22l-8.5 10v7l-5 2.5V17z',
focus: 'M16 9a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM16 4v3M16 25v3M4 16h3M25 16h3',
tools: 'M20 5a6 6 0 0 0-5.6 8.2L5 22.6 9.4 27l9.4-9.4A6 6 0 0 0 27 12l-4 4-4-1-1-4 4-4a6 6 0 0 0-2-2z',
};
const HUES = { reading: '#5b8cff', writing: '#c084fc', filters: '#f472b6', focus: '#2dd4bf', tools: '#fbbf24' };
const CATEGORY = { reading: 'Reading', writing: 'Writing', filters: 'Filters', focus: 'Focus', tools: 'Tools' };
/** A 640×400 banner for a plugin: Night Ink, a large category glyph, the name and category. */
export function pluginPreviewSvg(plugin) {
const W = 640, H = 400;
const glyph = GLYPHS[plugin.category] ?? GLYPHS.tools;
const hue = HUES[plugin.category] ?? HUES.tools;
const name = esc(plugin.name);
const size = plugin.name.length > 18 ? 34 : 40;
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${H}" width="${W}" height="${H}" role="img" aria-label="${name} plugin">`
+ `<title>${name}</title><defs>`
+ `<radialGradient id="glow" cx="0.3" cy="0.35" r="0.8"><stop offset="0" stop-color="${hue}" stop-opacity="0.34"/><stop offset="1" stop-color="#07080c" stop-opacity="0"/></radialGradient>`
+ `<pattern id="grid" width="32" height="32" patternUnits="userSpaceOnUse"><path d="M32 0H0V32" fill="none" stroke="#ffffff" stroke-opacity="0.045"/></pattern></defs>`
+ `<rect width="${W}" height="${H}" rx="14" fill="#07080c"/><rect width="${W}" height="${H}" rx="14" fill="url(#grid)"/><rect width="${W}" height="${H}" rx="14" fill="url(#glow)"/>`
+ `<rect x="64" y="96" width="128" height="128" rx="32" fill="#0d1017" stroke="${hue}" stroke-opacity="0.55" stroke-width="1.5"/>`
+ `<g transform="translate(80 112) scale(3)"><path d="${glyph}" fill="none" stroke="${hue}" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></g>`
+ `<text x="64" y="${278 + (40 - size) / 2}" font-family="Geist, 'Segoe UI', system-ui, sans-serif" font-size="${size}" font-weight="650" fill="#eef0f7" letter-spacing="-0.5">${name}</text>`
+ `<text x="64" y="316" font-family="'Geist Mono', Consolas, ui-monospace, monospace" font-size="15" fill="${hue}" letter-spacing="1.5">${esc((CATEGORY[plugin.category] ?? 'Plugin').toUpperCase())} · WAYBETTER PLUGIN</text>`
+ `</svg>`;
}

189
scripts/store/source.mjs Normal file
View file

@ -0,0 +1,189 @@
// The Store's source: one folder per item under store/<app>/plugins/<id>/, store/<app>/themes/<id>/
// and store/<app>/strings/<id>/
// (layout and rules: store/README.md). A contributor adds one folder in one pull request; this module
// turns the folders into the entries `waybetter store build` takes (scripts/store.config.mjs) and
// lists what is wrong with them (scripts/check-store.mjs).
//
// item.json what the item file cannot say itself: category, tags (plugins), version (themes)
// <name>.plugin.js a plugin; name, author, version, description and permissions are its header
// theme.json a theme, as Appearance → Export writes it; name, author, description, mode
// <name>.strings.json a string pack (waybetter/docs/STRING-PACKS.md); name, authors, version,
// description and language are the pack's own
// preview.svg|.png optional 640×400 picture; without one the preview is drawn from the item
// media/… optional cover, screenshots and one video for the item's page on the site,
// named in item.json ("cover", "screenshots", "video"); never in the catalog
//
// First-party items keep their one source of truth in the app: `"bundled": "<file>"` takes the plugin
// the app ships (apps/desktop/src-tauri/bundled-plugins), `"builtin": true` exports the built-in
// theme with the folder's id. So the app's copy and the Store's copy cannot drift.
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { pluginHeader, validFileName } from '../../waybetter/packages/waybetter/cli/store.mjs';
import { pluginPreviewSvg, themePreviewSvg } from './preview.mjs';
export const ITEM_ID = /^[a-z0-9-]{1,40}$/;
/** Categories the apps translate (`wb.store.category.*`); the Store's filters are these. */
export const CATEGORIES = { plugin: ['reading', 'writing', 'filters', 'focus', 'tools'], theme: ['dark', 'light'], strings: ['language'] };
// cover, screenshots and video are for the website only (apps/web/store-media.ts): the catalog never names them.
const MEDIA_FIELDS = ['cover', 'screenshots', 'video'];
// license and credits go into the catalog as they are (optional on every kind).
const FIELDS = { plugin: ['bundled', 'file', 'category', 'tags', 'preview', 'license', 'credits', ...MEDIA_FIELDS], theme: ['builtin', 'version', 'category', 'tags', 'preview', 'license', 'credits', ...MEDIA_FIELDS], strings: ['category', 'tags', 'preview', 'license', 'credits', ...MEDIA_FIELDS] };
const PREVIEW_NAMES = ['preview.svg', 'preview.png'];
const HEX = /^#[0-9a-f]{6}$/i;
const dirs = path => (existsSync(path) ? readdirSync(path).filter(name => statSync(join(path, name)).isDirectory()).sort() : []);
function readItemJson(dir, kind, problems, where) {
const path = join(dir, 'item.json');
if (!existsSync(path)) { problems.push(`${where}: item.json is missing`); return null; }
let info;
try { info = JSON.parse(readFileSync(path, 'utf8')); } catch (error) { problems.push(`${where}/item.json: not valid JSON (${error.message})`); return null; }
if (!info || typeof info !== 'object' || Array.isArray(info)) { problems.push(`${where}/item.json: must be an object`); return null; }
for (const key of Object.keys(info)) if (!FIELDS[kind].includes(key)) problems.push(`${where}/item.json: unknown field "${key}" (allowed: ${FIELDS[kind].join(', ')})`);
if (info.tags !== undefined && (!Array.isArray(info.tags) || info.tags.some(tag => typeof tag !== 'string'))) { problems.push(`${where}/item.json: tags must be a list of words`); info.tags = []; }
if (info.license !== undefined && (typeof info.license !== 'string' || !info.license.trim() || [...info.license].length > 60)) problems.push(`${where}/item.json: "license" is 1 to 60 characters`);
if (info.credits !== undefined && (typeof info.credits !== 'string' || [...info.credits].length > 600)) problems.push(`${where}/item.json: "credits" is at most 600 characters`);
return info;
}
/** The folder's own preview picture (item.json `preview`, else preview.svg / preview.png), or null. */
function ownPreview(dir, info, kind, id, problems, where) {
const name = info.preview ?? PREVIEW_NAMES.find(file => existsSync(join(dir, file)));
if (!name) return null;
if (typeof name !== 'string' || !/^[\w.-]+\.(svg|png)$/.test(name) || !existsSync(join(dir, name))) {
problems.push(`${where}: preview "${name}" must be an .svg or .png file in this folder`);
return null;
}
return { path: `previews/${kind}-${id}.${name.endsWith('.png') ? 'png' : 'svg'}`, bytes: readFileSync(join(dir, name)), own: true };
}
/**
* Reads store/<app>/ under `root`. Returns the entries for `buildStore` (plus `dir` and `firstParty`
* for the checks) and the problems that stop a build.
*
* options: { root, app, bundledDir, builtinThemes, themeSchemaUrl, sanitizeTheme, superseded }
* (`superseded`: bundled plugin files a built-in feature replaced; they stay in the app for the
* one-time move of an install, and are not Store items any more.)
*/
export function readStoreSource(options) {
const { root, app, bundledDir, builtinThemes = [], themeSchemaUrl, sanitizeTheme = theme => theme, superseded = [] } = options;
const base = join(root, 'store', app);
const problems = [];
const entries = [];
// ---- Plugins (sorted by id) ---------------------------------------------------------------
const bundledSeen = new Set();
for (const id of dirs(join(base, 'plugins'))) {
const where = `store/${app}/plugins/${id}`;
const dir = join(base, 'plugins', id);
if (!ITEM_ID.test(id)) { problems.push(`${where}: the folder name is the item id: a-z, 0-9 and -, at most 40 characters`); continue; }
const info = readItemJson(dir, 'plugin', problems, where);
if (!info) continue;
const own = readdirSync(dir).filter(file => file.endsWith('.plugin.js'));
let bytes;
let file;
if (info.bundled !== undefined) {
if (typeof info.bundled !== 'string' || !validFileName(info.bundled) || !existsSync(join(bundledDir, info.bundled))) { problems.push(`${where}: "bundled" must name a plugin the app ships (${info.bundled})`); continue; }
if (own.length) { problems.push(`${where}: a bundled plugin's file lives in the app, not here (remove ${own.join(', ')})`); continue; }
bundledSeen.add(info.bundled);
bytes = readFileSync(join(bundledDir, info.bundled));
file = info.file;
if (!file) { problems.push(`${where}: a bundled plugin needs "file", the name it is installed under`); continue; }
} else {
if (own.length !== 1) { problems.push(`${where}: exactly one *.plugin.js file is needed (found ${own.length})`); continue; }
bytes = readFileSync(join(dir, own[0]));
file = info.file ?? own[0];
}
if (!validFileName(file)) { problems.push(`${where}: the file name must look like name.plugin.js (letters, digits, - _ . and spaces)`); continue; }
let meta;
try { meta = pluginHeader(bytes.toString('utf8')); } catch (error) { problems.push(`${where}/${file}: ${error.message}`); continue; }
if (!meta.name || !meta.version) { problems.push(`${where}/${file}: the header needs @name and @version`); continue; }
const category = info.category ?? '';
entries.push({
kind: 'plugin', id, name: meta.name, author: meta.author, version: meta.version, description: meta.description,
category, tags: info.tags ?? [], file, permissions: meta.permissions, path: `plugins/${file}`, bytes,
preview: ownPreview(dir, info, 'plugin', id, problems, where) ?? { path: `previews/plugin-${id}.svg`, bytes: pluginPreviewSvg({ ...meta, category }) },
...(info.license !== undefined ? { license: info.license } : {}), ...(info.credits !== undefined ? { credits: info.credits } : {}),
dir: where, firstParty: info.bundled !== undefined,
});
}
// Every plugin the app ships is in the Store (the app offers their updates from it).
if (existsSync(bundledDir)) {
for (const name of readdirSync(bundledDir).filter(file => file.endsWith('.plugin.js')).sort()) {
if (superseded.includes(name)) { if (bundledSeen.has(name)) problems.push(`store/${app}/plugins: ${name} became a built-in feature; its Store folder goes (the area's page is store/${app}/areas/)`); continue; }
if (!bundledSeen.has(name)) problems.push(`bundled plugin ${name} has no Store folder: add store/${app}/plugins/${name.replace(/\.plugin\.js$/, '')}/item.json with "bundled", "file", "category" and "tags"`);
}
}
// ---- Themes (built-in ones in the app's order, then the rest by id) ------------------------
const themeDirs = dirs(join(base, 'themes'));
const builtinIds = builtinThemes.map(theme => theme.id);
const ordered = [...builtinIds.filter(id => themeDirs.includes(id)), ...themeDirs.filter(id => !builtinIds.includes(id))];
for (const id of ordered) {
const where = `store/${app}/themes/${id}`;
const dir = join(base, 'themes', id);
if (!ITEM_ID.test(id)) { problems.push(`${where}: the folder name is the item id: a-z, 0-9 and -, at most 40 characters`); continue; }
const info = readItemJson(dir, 'theme', problems, where);
if (!info) continue;
if (typeof info.version !== 'string' || !info.version) { problems.push(`${where}/item.json: "version" is needed (for example "1.0.0")`); continue; }
const hasFile = existsSync(join(dir, 'theme.json'));
let theme;
let bytes;
let raw;
if (info.builtin !== undefined) {
theme = builtinThemes.find(candidate => candidate.id === id);
if (info.builtin !== true || !theme) { problems.push(`${where}: "builtin": true needs a built-in theme with the id ${id}`); continue; }
if (hasFile) { problems.push(`${where}: a built-in theme is exported from the app (remove theme.json)`); continue; }
// Exactly what Appearance → Export writes.
bytes = `${JSON.stringify({ $schema: themeSchemaUrl, ...theme }, null, 2)}\n`;
raw = theme;
} else {
if (!hasFile) { problems.push(`${where}: theme.json is missing (Appearance → Export in the app, or npm create waybetter theme)`); continue; }
bytes = readFileSync(join(dir, 'theme.json'));
try { raw = JSON.parse(bytes.toString('utf8')); } catch (error) { problems.push(`${where}/theme.json: not valid JSON (${error.message})`); continue; }
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || typeof raw.name !== 'string' || !raw.name.trim()) { problems.push(`${where}/theme.json: a theme is an object with a "name"`); continue; }
try { theme = sanitizeTheme(raw); } catch (error) { problems.push(`${where}/theme.json: ${error.message}`); continue; }
}
const light = theme.mode === 'light';
const c = theme.colors;
const category = info.category ?? (light ? 'light' : 'dark');
entries.push({
kind: 'theme', id, name: raw.name, author: typeof raw.author === 'string' ? raw.author : '', version: info.version,
description: typeof raw.description === 'string' ? raw.description : '', category, tags: info.tags ?? [info.builtin ? theme.mode : category],
path: `themes/${id}.json`, bytes,
preview: ownPreview(dir, info, 'theme', id, problems, where) ?? { path: `previews/theme-${id}.svg`, bytes: themePreviewSvg(theme) },
colors: c && HEX.test(c.page ?? c.bg) && HEX.test(c.text) && HEX.test(c.accent) ? { bg: c.page ?? c.bg, surface: c.surface, text: c.text, accent: c.accent } : null,
...(info.license !== undefined ? { license: info.license } : {}), ...(info.credits !== undefined ? { credits: info.credits } : {}),
dir: where, firstParty: info.builtin === true, theme: raw,
});
}
// ---- String packs (sorted by id): data that replaces the site's own words --------------------
for (const id of dirs(join(base, 'strings'))) {
const where = `store/${app}/strings/${id}`;
const dir = join(base, 'strings', id);
if (!ITEM_ID.test(id)) { problems.push(`${where}: the folder name is the item id: a-z, 0-9 and -, at most 40 characters`); continue; }
const info = readItemJson(dir, 'strings', problems, where);
if (!info) continue;
const own = readdirSync(dir).filter(file => file.endsWith('.strings.json'));
if (own.length !== 1) { problems.push(`${where}: exactly one *.strings.json file is needed (found ${own.length})`); continue; }
const bytes = readFileSync(join(dir, own[0]));
let pack;
try { pack = JSON.parse(bytes.toString('utf8')); } catch (error) { problems.push(`${where}/${own[0]}: not valid JSON (${error.message})`); continue; }
if (!pack || typeof pack !== 'object' || pack.format !== 1 || typeof pack.name !== 'string' || typeof pack.language !== 'string') { problems.push(`${where}/${own[0]}: a string pack has "format": 1, a "name" and a "language"`); continue; }
if (pack.site !== app) { problems.push(`${where}/${own[0]}: the pack is for "${pack.site}", this folder is ${app}'s`); continue; }
const category = info.category ?? 'language';
entries.push({
kind: 'strings', id, name: pack.name, author: Array.isArray(pack.authors) ? pack.authors.join(', ') : '', version: typeof pack.version === 'string' && pack.version ? pack.version : '1.0.0',
description: typeof pack.description === 'string' ? pack.description : '', category, tags: info.tags ?? [pack.language], language: pack.language,
path: `strings/${id}.strings.json`, bytes,
preview: ownPreview(dir, info, 'strings', id, problems, where) ?? { path: `previews/strings-${id}.svg`, bytes: pluginPreviewSvg({ name: pack.name, category: 'language' }) },
...(info.license !== undefined ? { license: info.license } : {}), ...(info.credits !== undefined ? { credits: info.credits } : {}),
dir: where, firstParty: false, pack, file: own[0],
});
}
// Every built-in theme except the site's own look ("x" is not something to install) is in the Store.
for (const theme of builtinThemes) {
if (theme.id !== 'x' && !themeDirs.includes(theme.id)) problems.push(`built-in theme ${theme.id} has no Store folder: add store/${app}/themes/${theme.id}/item.json with "builtin": true and "version"`);
}
return { entries, problems };
}