From 748be340a86877c61192ddf1b181e14b752d0d86 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 30 Sep 2026 17:48:27 +0700 Subject: [PATCH 01/72] build-env: MSVC C and C++ lose the build paths too (/d1trimfile in CL, /PDBALTPATH in LINK) A library a build script compiles with MSVC (CMake, the cc crate) kept its absolute source paths through __FILE__: -ffile-prefix-map exists only on gcc and clang. cl.exe and link.exe read CL and LINK themselves, so the roots are trimmed whatever runs the compiler. Longest root first: the first match wins. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 ++++- packages/waybetter/README.md | 2 +- packages/waybetter/cli/buildenv.mjs | 17 ++++++++++++++--- packages/waybetter/tests/privacy-cli.test.mjs | 11 +++++++++++ 4 files changed, 30 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 62a9419..cbac421 100644 --- a/README.md +++ b/README.md @@ -462,7 +462,10 @@ The npm package adds the app-side tooling: registry, the rustup toolchain, the workspace: about 1,400 strings holding the account name in one app), so `build-env` runs a build with those roots remapped to `/home`, `/src`, `/cargo`, `/rustup` and `/target` (`--remap-path-prefix` appended to the flags already set, - `/PDBALTPATH:%_PDB%` on MSVC, `-ffile-prefix-map` for C sources on gcc and clang): + `/PDBALTPATH:%_PDB%` on MSVC, `-ffile-prefix-map` for C sources on gcc and clang). MSVC has no + prefix map, so there the C and C++ a build script compiles (a CMake library, the cc crate) lose + the same roots through `/d1trimfile:` in the `CL` variable, and any PDB they link through + `/PDBALTPATH` in `LINK`; cl.exe and link.exe read both themselves, whatever runs them: `waybetter build-env -- tauri build`, on every platform. `privacy-scan` is the proof: it searches files, binaries (UTF-8, UTF-16), archives (npm tarballs, zip, tar, .deb, DMG; NSIS installers and AppImages through 7-Zip), git-tracked files and, with `--history`, every blob, path, commit diff --git a/packages/waybetter/README.md b/packages/waybetter/README.md index 32b22ac..06f0337 100644 --- a/packages/waybetter/README.md +++ b/packages/waybetter/README.md @@ -114,7 +114,7 @@ const Shell = createShell({ ...site, panel: { id: 'app', title: 'wayBetter', com - `waybetter store sign [--init] --key ` / `waybetter store verify --pub `: Ed25519 signature over the exact catalog bytes; any listed public key verifies (rotation). The private key is never printed or copied. - `waybetter i18n check [--write] [--verbose] [locale…]`: checks an app's catalogs (and the framework's in the same languages) with the `waybetter/i18n/check` rules, bundled plugins' inline English and the generated files; `--write` regenerates `languages.json` and the native localization files (macOS, Linux). `waybetter i18n extract [--missing]`: keys the code looks up that English lacks, and English keys without a literal lookup. Both read `waybetter.i18n.json` in the app's root (`locales`, `sources`, `nativeSources`, `bundledPlugins`, `runtimeKeys`, `supported`, `native`; schema: `i18n-config.schema.json`). `supported` lists the languages in the supported tier; every other catalog gets `tier: "community"` in the generated `languages.json` (`languages.schema.json`), and an app resolves its automatic language choices only to supported ones (`createLanguage({ supported })`). - `waybetter release windows|macos`: signed native releases and the update manifest (`waybetter.release.json`). The Windows build runs path-free (below) and every artifact must pass the privacy scan before anything is copied or signed. -- `waybetter build-env -- `: runs a build (`tauri build`, `cargo build`) so the binary holds none of the machine's paths: the home folder, the workspace, `CARGO_HOME`, `RUSTUP_HOME` and `CARGO_TARGET_DIR` become `/home`, `/src`, `/cargo`, `/rustup` and `/target` (`--remap-path-prefix` appended to the flags already in `RUSTFLAGS`/`CARGO_ENCODED_RUSTFLAGS`, `/PDBALTPATH` on MSVC, `-ffile-prefix-map` for C sources elsewhere). Without a command it prints that environment (`--json`). +- `waybetter build-env -- `: runs a build (`tauri build`, `cargo build`) so the binary holds none of the machine's paths: the home folder, the workspace, `CARGO_HOME`, `RUSTUP_HOME` and `CARGO_TARGET_DIR` become `/home`, `/src`, `/cargo`, `/rustup` and `/target` (`--remap-path-prefix` appended to the flags already in `RUSTFLAGS`/`CARGO_ENCODED_RUSTFLAGS`, `/PDBALTPATH` on MSVC; for C and C++ a build script compiles, `-ffile-prefix-map` on gcc and clang and, on MSVC, `/d1trimfile:` in `CL` and `/PDBALTPATH` in `LINK`, which reach the cc crate, CMake and MSBuild alike). Without a command it prints that environment (`--json`). - `waybetter privacy-scan [--terms ] [--tracked] [--history]`: searches files, binaries (UTF-8 and UTF-16), archives (zip, tar, gzip, zstd, .deb, DMG; NSIS installers, AppImages and xz with 7-Zip or the matching tool), git-tracked files and a repository's whole history for forbidden terms: the lines of a file kept outside every repository (`--terms`, `WAYBETTER_FORBIDDEN_TERMS`, or `"forbiddenTerms"` in `waybetter.release.json`) plus this machine's account name. A name is a hit as a whole word in any case; a name of three characters or fewer only in a path or as the capitalized word. Output shows file and line or offset with the term masked (`m***`); exit 1 on a hit, 2 when a container could not be opened. Reviewed false positives: `"privacyAllowlist"`, lines of `: >`. - `windows/languages/.nsh`: the Windows installer's messages for the languages Tauri does not ship, next to the installer template (`windows/installer.nsi`). diff --git a/packages/waybetter/cli/buildenv.mjs b/packages/waybetter/cli/buildenv.mjs index bf8fe78..8dfe9ad 100644 --- a/packages/waybetter/cli/buildenv.mjs +++ b/packages/waybetter/cli/buildenv.mjs @@ -9,8 +9,11 @@ // // (`--remap-path-prefix`, added to CARGO_ENCODED_RUSTFLAGS after the flags RUSTFLAGS or // CARGO_ENCODED_RUSTFLAGS already hold), keeps the PDB's name but not its folder on MSVC -// (`/PDBALTPATH:%_PDB%`) and gives C sources compiled by build scripts the same mapping -// (`-ffile-prefix-map` in CFLAGS/CXXFLAGS on gcc and clang). +// (`/PDBALTPATH:%_PDB%`) and gives C and C++ sources compiled by build scripts the same treatment: +// `-ffile-prefix-map` in CFLAGS/CXXFLAGS on gcc and clang; on MSVC `/d1trimfile:` in the CL +// variable and `/PDBALTPATH:%_PDB%` in the LINK variable, which cl.exe and link.exe read themselves, +// so the cc crate, CMake and MSBuild are all covered (`__FILE__` in a library a build script +// compiles: there a root is cut off, not renamed, and the path stays relative). // // waybetter build-env -- tauri build run a command with that environment // waybetter build-env [--json] show it @@ -26,6 +29,7 @@ export const BUILD_ENV_USAGE = `Usage: Runs the command (tauri build, cargo build, ...) so the binary holds no build path: the home folder, the workspace, CARGO_HOME, RUSTUP_HOME and CARGO_TARGET_DIR become /home, /src, /cargo, /rustup and /target. Flags already in RUSTFLAGS or CARGO_ENCODED_RUSTFLAGS are kept. + C and C++ compiled by build scripts: -ffile-prefix-map (gcc, clang), /d1trimfile in CL (MSVC). waybetter build-env [--json] [--root ] Prints that environment. The workspace root is --root, else the folder of the nearest waybetter.release.json, else the git work tree, else the working directory.`; @@ -71,7 +75,14 @@ export function pathFreeBuildEnv({ root, env = process.env, platform = process.p if (msvc) add('-Clink-arg=/PDBALTPATH:%_PDB%'); const out = { CARGO_ENCODED_RUSTFLAGS: flags.join(SEPARATOR) }; - if (!msvc) { + if (msvc) { + // cl.exe takes the first /d1trimfile prefix that matches (any case, either slash), so the + // longest root goes first. Quoted, and closed with a slash: a backslash would escape the quote. + const trims = roots.map(([from]) => from).filter(from => !from.includes('"')).sort((a, b) => b.length - a.length).map(from => `"/d1trimfile:${from}/"`); + out.CL = [...new Set([env.CL, ...trims])].filter(Boolean).join(' '); + // C and C++ linked with debug info (a CMake RelWithDebInfo library) name their PDB the same way. + out.LINK = [...new Set([env.LINK, '/PDBALTPATH:%_PDB%'])].filter(Boolean).join(' '); + } else { // gcc and clang (cc crate: sqlite, ring and other bundled C). A flag cannot hold a space there. const prefixMaps = maps.filter(([from]) => !/\s/.test(from)).map(([from, to]) => `-ffile-prefix-map=${from}=${to}`); if (prefixMaps.length < maps.length) notes.push('a build path contains a space: C sources keep it (CFLAGS cannot express it)'); diff --git a/packages/waybetter/tests/privacy-cli.test.mjs b/packages/waybetter/tests/privacy-cli.test.mjs index e61bd04..9accf80 100644 --- a/packages/waybetter/tests/privacy-cli.test.mjs +++ b/packages/waybetter/tests/privacy-cli.test.mjs @@ -241,12 +241,23 @@ test('build-env: roots remapped general to specific, existing flags kept, per pl assert.ok(flags.includes('--remap-path-prefix=\\\\?\\C:\\Users\\dev\\.rustup=/rustup')); assert.equal(flags.at(-1), '-Clink-arg=/PDBALTPATH:%_PDB%'); assert.equal(windows.env.CFLAGS, undefined); + // MSVC C and C++: cl.exe takes the first /d1trimfile that matches, so the longest root leads. + assert.deepEqual(windows.env.CL.split(' '), ['C:/Users/dev/.rustup', 'C:/Users/dev/.cargo', 'C:/Users/dev/app', 'C:/Users/dev'].map(dir => `"/d1trimfile:${dir.replaceAll('/', '\\')}/"`)); + assert.equal(windows.env.LINK, '/PDBALTPATH:%_PDB%'); + const kept = pathFreeBuildEnv({ root: 'D:\\my apps\\app', home: 'C:\\Users\\dev', platform: 'win32', env: { CL: '/MP', LINK: '/DEBUG:NONE', CARGO_TARGET_DIR: 'D:\\t' } }); + assert.ok(kept.env.CL.startsWith('/MP "/d1trimfile:C:\\Users\\dev\\.rustup/" ')); + assert.ok(kept.env.CL.includes(' "/d1trimfile:D:\\my apps\\app/" ') && kept.env.CL.endsWith(' "/d1trimfile:D:\\t/"')); + assert.equal(kept.env.LINK, '/DEBUG:NONE /PDBALTPATH:%_PDB%'); + const gnu = pathFreeBuildEnv({ root: 'C:\\Users\\dev\\app', home: 'C:\\Users\\dev', platform: 'win32', env: { CARGO_BUILD_TARGET: 'x86_64-pc-windows-gnu' } }); + assert.equal(gnu.env.CL, undefined); + assert.equal(gnu.env.LINK, undefined); const encoded = pathFreeBuildEnv({ root: '/home/dev/app', home: '/home/dev', platform: 'linux', env: { CARGO_ENCODED_RUSTFLAGS: '-Cfoo\x1f--remap-path-prefix=/home/dev=/home', CARGO_HOME: '/opt/cargo', CARGO_TARGET_DIR: '/tmp/t', CFLAGS: '-O2' } }); assert.deepEqual(encoded.env.CARGO_ENCODED_RUSTFLAGS.split('\x1f'), ['-Cfoo', '--remap-path-prefix=/home/dev=/home', '--remap-path-prefix=/home/dev/app=/src', '--remap-path-prefix=/tmp/t=/target', '--remap-path-prefix=/opt/cargo=/cargo', '--remap-path-prefix=/home/dev/.rustup=/rustup']); assert.match(encoded.env.CFLAGS, /^-O2 -ffile-prefix-map=\/home\/dev=\/home .*-ffile-prefix-map=\/opt\/cargo=\/cargo/); assert.equal(encoded.env.CXXFLAGS.split(' ').length, 5); + assert.equal(encoded.env.CL, undefined); }); test('release: an artifact holding a term stops the release before anything is written', async () => { From ca9eec05abf87ccbaf79135f9be68c00725a5306 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 30 Sep 2026 18:11:42 +0700 Subject: [PATCH 02/72] Feature modules: a feature table (areas, flags, modes), a registry that runs a module only on its surfaces, one shared observer for every feature and plugin, settings from a schema, selector health with self-pause - featureTable.ts: areas, per-feature flags, core flags, modes as presets; sparse storage, ownership (an area that is off turns off what it owns), mode switching that keeps or drops manual changes, table validation - featureModules.ts: createFeatureRegistry (flag + surface gating, scoped context, palette commands under the area with a budget of 5, settings dialog, probes, hotfix selector overrides and kill flags) - settingsForm.ts: a settings schema normalizes stored values and draws the controls from the UI kit - domHub observeSelector; api.observe goes through the shared hub (a root of the caller's own keeps its observer) - createFeatureFlags: a delivery is the whole state (a flag it does not name is at its default), resolve() for ownership, current() Co-Authored-By: Claude Opus 5.5 --- packages/runtime/src/domHub.ts | 47 ++ packages/runtime/src/featureModules.ts | 476 +++++++++++++++++++++ packages/runtime/src/featureTable.ts | 233 ++++++++++ packages/runtime/src/pluginApi.ts | 13 +- packages/runtime/src/settingsForm.ts | 135 ++++++ packages/runtime/src/siteRuntime.ts | 53 ++- packages/runtime/tests/features.test.ts | 386 +++++++++++++++++ packages/runtime/tests/siteRuntime.test.ts | 26 +- 8 files changed, 1339 insertions(+), 30 deletions(-) create mode 100644 packages/runtime/src/featureModules.ts create mode 100644 packages/runtime/src/featureTable.ts create mode 100644 packages/runtime/src/settingsForm.ts create mode 100644 packages/runtime/tests/features.test.ts diff --git a/packages/runtime/src/domHub.ts b/packages/runtime/src/domHub.ts index 5c48796..34b79fd 100644 --- a/packages/runtime/src/domHub.ts +++ b/packages/runtime/src/domHub.ts @@ -122,6 +122,53 @@ function hubFor(win: DomWindow): Hub { return hub; } +type SelectorSub = { selector: string; callback: (element: Element) => void; seen: WeakSet; report(error: unknown): void }; +type SelectorHub = { subs: SelectorSub[]; handle: DomWatchHandle | null }; +// One per window and heavy-page behaviour: every selector observer of that kind shares its watch. +const selectorHubs = new WeakMap>(); + +export type ObserveOptions = { + /** Skip on the site's heavy pages (default false). */ + offOnHeavy?: boolean; + /** A callback that throws is handed here (default: the hub's console line). */ + report?(error: unknown): void; +}; + +/** + * Calls `callback` once for every element matching `selector`, now and as the page renders more. + * Every call shares the hub's one MutationObserver and one frame: a page with a hundred selector + * observers still has one observer, and a mutation costs one frame in which each observer looks + * for elements it has not seen yet. Returns the disposer. + */ +export function observeSelector(win: DomWindow, selector: string, callback: (element: Element) => void, options: ObserveOptions = {}): () => void { + const offOnHeavy = !!options.offOnHeavy; + let kinds = selectorHubs.get(win); + if (!kinds) { kinds = new Map(); selectorHubs.set(win, kinds); } + let hub = kinds.get(offOnHeavy); + if (!hub) { hub = { subs: [], handle: null }; kinds.set(offOnHeavy, hub); } + const owner = hub; + const report = options.report ?? ((error: unknown) => console.error(`[${config.label}] DOM feature failed`, error)); + const sub: SelectorSub = { selector, callback, seen: new WeakSet(), report }; + const scan = (target: SelectorSub) => { + for (const element of Array.from(win.document.querySelectorAll(target.selector))) { + if (target.seen.has(element)) continue; + target.seen.add(element); + try { target.callback(element); } catch (error) { target.report(error); } + } + }; + owner.subs.push(sub); + owner.handle ??= watchDom(win, () => { for (const item of owner.subs.slice()) scan(item); }, { offOnHeavy }); + if (!(offOnHeavy && isHeavyPath(win.location.pathname ?? ''))) scan(sub); + let active = true; + return () => { + if (!active) return; + active = false; + const index = owner.subs.indexOf(sub); + if (index >= 0) owner.subs.splice(index, 1); + if (!owner.subs.length) { owner.handle?.dispose(); owner.handle = null; } + }; +} + /** * Runs `run` in the next animation frame after body mutations of the watched kinds (child list * always), or whenever `schedule()` is called (scroll, popstate, input, ...). Several calls in one diff --git a/packages/runtime/src/featureModules.ts b/packages/runtime/src/featureModules.ts new file mode 100644 index 0000000..9ce8ea0 --- /dev/null +++ b/packages/runtime/src/featureModules.ts @@ -0,0 +1,476 @@ +// Feature modules: the code side of the feature table (featureTable.ts). An app's area plugins +// ("Navigation+") are sets of small modules, one per feature; the registry starts a module only +// while its flag is on, its area's switch is on and the page is on one of its surfaces, and +// disposes everything it did when any of those stops being true. A hundred features then cost what +// the ones on screen cost: +// +// const registry = createFeatureRegistry({ win, table, api, label, surfaces, message }); +// registry.define({ id: 'navigation.keyboardPlus', start(ctx) { ctx.onKey(...); } }); +// registry.setFlags(effectiveFlags(table, flags)); // from the app's feature flags +// +// A module's `start(ctx)` gets a context whose every helper is undone on stop: CSS, listeners, +// nodes, DOM watching through the shared hub (one MutationObserver for every feature, domHub.ts), +// palette commands under its area's name, its words, its storage and its settings. A module with a +// `settings` schema gets a settings dialog drawn from the UI kit (settingsForm.ts); each area with +// such a feature gets one "settings" palette command. +// +// Health: a module names the selectors it depends on (`probes`). After the page has settled, a +// probe that matches nothing is a miss; three misses in a row (three visits) pause that one feature +// for the session, with one toast and a note in the settings dialog. The site's markup changed; the +// rest of the area keeps working. A signed hotfix may replace a probe's selector +// (`selectors["."]`) or switch a feature off (`flags[""] = false`). + +import { isHeavyPath, observeSelector, watchDom, type DomWatch, type DomWatchHandle, type DomWindow } from './domHub.ts'; +import { areaFlag, type AreaSpec, type FeatureSpec, type FeatureTable, type Flags } from './featureTable.ts'; +import { formatMessage, type Params } from './i18n.ts'; +import type { CommandDefinition } from './commands.ts'; +import type { PluginI18n } from './pluginI18n.ts'; +import type { Dispose, PluginScope, PluginStorage } from './pluginApi.ts'; +import { buildSettingsForm, normalizeSettings, validateSchema, type SettingValues, type SettingsSchema } from './settingsForm.ts'; +import type { UiKit } from './ui.ts'; + +/** Palette commands one area may register: its "settings" entry and four actions (the tab reports at most 48). */ +export const AREA_COMMAND_BUDGET = 5; +/** Misses in a row (separate visits) before a feature pauses itself. */ +export const PROBE_STRIKES = 3; + +/** The registry's own words in the page (English source; `kit.feature.*` in the framework catalogs). */ +export const FEATURE_MESSAGES = { + 'kit.feature.paused': '{feature} ({area}) is paused: this page changed.', + 'kit.feature.pausedOne': 'A feature of {area} is paused: this page changed.', + 'kit.feature.needsEnglish': '{feature} needs the site in English.', + 'kit.feature.settings': '{name} settings', + 'kit.feature.save': 'Save', + 'kit.cancel': 'Cancel', + 'kit.failed': 'Something went wrong.', +} as const; + +/** A selector a feature depends on; `english`: it reads an English label, so it only counts on an English page. */ +export type Probe = string | { selector: string; english?: boolean }; + +export type FeatureSettings = { + /** The stored values, normalized by the schema. */ + get(): SettingValues; + /** Saves (merged over the current values). False when storage refused it. */ + set(patch: SettingValues): boolean; + /** Calls `callback(values)` after a save, until the feature stops. */ + onChange(callback: (values: SettingValues) => void): void; + /** Opens this feature's settings dialog. */ + open(): void; +}; + +export type FeatureContext = { + /** The flag id and the feature's own name (`navigation.focusMode` -> `focusMode`). */ + readonly id: string; + readonly name: string; + readonly area: AreaSpec; + /** The app's plugin API, unrestricted: a feature module is the app's own code. */ + readonly api: Api; + /** This feature's stylesheet (one per `name`, replaced in place, cleared by an empty string; removed on stop). */ + css(css: string, name?: string): void; + /** `callback` once per element matching `selector`, through the shared hub; paused on heavy pages unless the feature says `heavy`. */ + observe(selector: string, callback: (element: Element) => void): void; + /** A raw hub subscription (domHub `watchDom`), disposed on stop. */ + watch(run: () => void, options?: DomWatch): DomWatchHandle; + on(target: EventTarget, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + onKey(callback: (event: KeyboardEvent, item: Element | null) => void): void; + onRouteChange(callback: (href: string, previous: string) => void): void; + /** Tracks a node the feature inserted; removed on stop. */ + add(node: T): T; + /** Runs `fn` on stop. */ + defer(fn: Dispose): void; + /** The UI kit; what the feature opened is closed on stop. */ + readonly ui: UiKit; + /** A palette command under the area's name (counts towards `AREA_COMMAND_BUDGET`), removed on stop. */ + command(definition: CommandDefinition): void; + /** The feature's word `key`: `plugin...` in the app's catalog. */ + t(key: string, params?: Params): string; + /** The feature's storage (its module's `storage` namespace). */ + readonly storage: PluginStorage; + /** Its settings (a module with a `settings` schema; otherwise empty values). */ + readonly settings: FeatureSettings; + /** The selector of probe `name` (a hotfix override wins). */ + selector(name: string): string; + /** The surfaces the page is on right now. */ + surfaces(): readonly string[]; +}; + +export type FeatureModule = { + /** The flag id; the table must list it with `backing: 'module'`. */ + id: string; + /** Selectors it depends on, by name (read them back with `ctx.selector(name)`). */ + probes?: Readonly>; + /** Storage namespace (default `.`; a ported plugin keeps its old one). */ + storage?: string; + /** The key its settings are stored under (default `settings`). */ + settingsKey?: string; + settings?: SettingsSchema; + start(ctx: FeatureContext): void; +}; + +/** What the registry needs of the plugin API (the core API has all of it). */ +export type RegistryApi = { + scope(): PluginScope; + injectCSS(id: string, css: string): void; + clearCSS(id: string): void; + storage(namespace: string): PluginStorage; + onRouteChange(callback: (href: string, previous: string) => void): Dispose; + ui: UiKit; + i18n: PluginI18n; + commands: { withOwner(owner: string, fn: () => T): T }; +}; + +export type HotfixData = { selectors?: Readonly>; flags?: Readonly> }; + +export type FeatureHealth = { id: string; area: string; state: 'paused' | 'needs-english'; probes: string[] }; + +export type FeatureRegistryOptions = { + win: Window & typeof globalThis; + table: FeatureTable; + api: Api; + /** Console prefix (the app's name). */ + label: string; + /** The surfaces the page is on (`['timeline', 'home']`); the app's classifier. */ + surfaces(): readonly string[]; + /** The app catalog's message for `key` in the active language (the registry's `kit.feature.*` words). */ + message?(key: string): string | undefined; + locale?(): string; + /** The signed hotfix data, when the app has any (selector overrides and kill flags). */ + hotfix?(): HotfixData | null | undefined; + /** The page has rendered its content (the site's main column is there); default: the body has children. */ + settled?(): boolean; + /** The page's language is English (probes marked `english` only count then); default: `` starts with `en`. */ + english?(): boolean; + /** ms after the page settled before probes are judged (default 3000) and between settle checks (default 500). */ + settleMs?: number; + pollMs?: number; + timers?: { setTimeout(fn: () => void, ms: number): unknown; clearTimeout(id: unknown): void }; +}; + +export type FeatureRegistry = { + define(module: FeatureModule): void; + /** The effective flags (featureTable `effectiveFlags`): starts and stops modules to match. */ + setFlags(flags: Readonly): void; + /** Re-checks surfaces (the registry also does it on every route change). */ + refresh(): void; + /** The ids of the modules running right now. */ + active(): string[]; + /** Paused features and features waiting for an English page. */ + health(): FeatureHealth[]; + /** Opens the settings dialog of an area (or of one feature). False when nothing in it has settings right now. */ + openSettings(area: string, feature?: string): boolean; + /** Stops everything (the runtime is going away; tests). */ + dispose(): void; +}; + +type Running = { + module: FeatureModule; + spec: FeatureSpec; + area: AreaSpec; + scope: PluginScope; + commands: number; + listeners: Set<(values: SettingValues) => void>; + settings: FeatureSettings; + visit: number; + timer: unknown; +}; + +const featureName = (id: string) => id.slice(id.indexOf('.') + 1); + +export function createFeatureRegistry(options: FeatureRegistryOptions): FeatureRegistry { + const { win, table, api, label } = options; + const doc = win.document; + const timers = options.timers ?? { setTimeout: (fn: () => void, ms: number) => win.setTimeout(fn, ms), clearTimeout: (id: unknown) => win.clearTimeout(id as number) }; + const settleMs = options.settleMs ?? 3000; + const pollMs = options.pollMs ?? 500; + const specs = new Map(table.features.map(feature => [feature.id, feature])); + const areas = new Map(table.areas.map(area => [area.id, area])); + const modules = new Map>(); + const running = new Map>(); + const areaScopes = new Map(); + const strikes = new Map(); + const paused = new Map(); + const waiting = new Map(); + let flags: Readonly = {}; + let stopRoutes: Dispose | null = null; + let visit = 0; + + const text = (key: keyof typeof FEATURE_MESSAGES, params: Params = {}) => + formatMessage(options.message?.(key) ?? FEATURE_MESSAGES[key], params, options.locale?.() ?? 'en'); + const hotfix = (): HotfixData => { try { return options.hotfix?.() ?? {}; } catch { return {}; } }; + const english = () => options.english?.() ?? /^en\b/i.test(doc.documentElement?.getAttribute?.('lang') ?? 'en'); + const settled = () => options.settled?.() ?? !!doc.body?.firstElementChild; + const words = (area: AreaSpec) => api.i18n.namespace(area.namespace); + /** A feature's label in the page, when the page has it (`plugin.*` words only reach a site tab). */ + const featureLabel = (spec: FeatureSpec, area: AreaSpec) => { + const i18n = words(area); + const key = `feature.${featureName(spec.id)}.label`; + return i18n.has(key) ? i18n.t(key) : null; + }; + + const selectorOf = (module: FeatureModule, name: string) => { + const override = hotfix().selectors?.[`${module.id}.${name}`]; + if (typeof override === 'string' && override.trim()) return override; + const probe = module.probes?.[name]; + if (probe === undefined) throw new Error(`${module.id}: no probe named ${JSON.stringify(name)}`); + return typeof probe === 'string' ? probe : probe.selector; + }; + + function wanted(module: FeatureModule): boolean { + const spec = specs.get(module.id)!; + if (flags[module.id] !== true || paused.has(module.id) || hotfix().flags?.[module.id] === false) return false; + if (!spec.heavy && isHeavyPath(win.location.pathname ?? '')) return false; + if (!spec.surfaces?.length) return true; + const on = options.surfaces(); + return spec.surfaces.some(surface => on.includes(surface)); + } + + function settingsOf(module: FeatureModule, area: AreaSpec, listeners: Set<(values: SettingValues) => void>): FeatureSettings { + const schema = module.settings ?? []; + const store = () => api.storage(module.storage ?? `${area.namespace}.${featureName(module.id)}`); + const key = module.settingsKey ?? 'settings'; + const get = () => normalizeSettings(schema, store().get(key, null)); + return { + get, + set(patch) { + const next = normalizeSettings(schema, { ...get(), ...patch }); + const saved = store().set(key, next); + for (const listener of [...listeners]) { + try { listener(next); } catch (error) { console.error(`[${label}] ${module.id} settings listener failed`, error); } + } + return saved; + }, + onChange(callback) { listeners.add(callback); }, + open() { openSettings(area.id, module.id); }, + }; + } + + function start(module: FeatureModule) { + const spec = specs.get(module.id)!; + const area = areas.get(spec.area!)!; + const scope = api.commands.withOwner(area.owner, () => api.scope()); + const listeners = new Set<(values: SettingValues) => void>(); + const entry: Running = { module, spec, area, scope, commands: 0, listeners, settings: settingsOf(module, area, listeners), visit: -1, timer: null }; + const name = featureName(module.id); + const domWin = win as unknown as DomWindow; + const styles = new Set(); + const ctx: FeatureContext = { + id: module.id, + name, + area, + api, + css(css, part = '') { + const styleId = `wbf-${module.id}${part ? `-${part}` : ''}`; + if (!styles.has(styleId)) { styles.add(styleId); scope.defer(() => api.clearCSS(styleId)); } + if (css) api.injectCSS(styleId, css); else api.clearCSS(styleId); + }, + observe(selector, callback) { + scope.defer(observeSelector(domWin, selector, callback, { offOnHeavy: !spec.heavy, report: error => console.error(`[${label}] ${module.id} failed`, error) })); + }, + watch(run, watchOptions = {}) { + const handle = watchDom(domWin, run, { offOnHeavy: !spec.heavy, ...watchOptions }); + scope.defer(() => handle.dispose()); + return handle; + }, + on: (target, type, listener, listenerOptions) => scope.on(target, type, listener, listenerOptions), + onKey: callback => scope.onKey(callback), + onRouteChange: callback => scope.onRouteChange(callback), + add: node => scope.add(node), + defer: fn => scope.defer(fn), + get ui() { return scope.ui; }, + command(definition) { + const reserved = table.features.some(feature => feature.area === area.id && feature.settings) ? 1 : 0; + const used = [...running.values()].filter(other => other.area.id === area.id).reduce((sum, other) => sum + other.commands, 0); + if (used + reserved >= AREA_COMMAND_BUDGET) throw new Error(`${area.name}: at most ${AREA_COMMAND_BUDGET} palette commands per area`); + scope.commands.register(definition); + entry.commands += 1; + }, + t: (key, params) => words(area).t(`${name}.${key}`, params), + get storage() { return api.storage(module.storage ?? `${area.namespace}.${name}`); }, + settings: entry.settings, + selector: probe => selectorOf(module, probe), + surfaces: () => options.surfaces(), + }; + running.set(module.id, entry); + try { + module.start(ctx); + } catch (error) { + console.error(`[${label}] ${module.id} failed`, error); + stop(module.id); + return; + } + scheduleProbes(entry); + } + + function stop(id: string) { + const entry = running.get(id); + if (!entry) return; + running.delete(id); + if (entry.timer !== null) timers.clearTimeout(entry.timer); + entry.listeners.clear(); + entry.scope.dispose(); + } + + // ---- Health ---------------------------------------------------------------------------------- + + function scheduleProbes(entry: Running) { + if (!entry.module.probes || !Object.keys(entry.module.probes).length || entry.visit === visit) return; + entry.visit = visit; + if (entry.timer !== null) timers.clearTimeout(entry.timer); + const mine = visit; + let tries = 0; + const waitForSettle = () => { + entry.timer = null; + if (running.get(entry.module.id) !== entry || mine !== visit) return; + if (!settled()) { + tries += 1; + // A page that never settles (an error page, a sign-in wall) is no verdict. + if (tries <= 20) entry.timer = timers.setTimeout(waitForSettle, pollMs); + return; + } + entry.timer = timers.setTimeout(judge, settleMs); + }; + const judge = () => { + entry.timer = null; + if (running.get(entry.module.id) !== entry || mine !== visit) return; + const id = entry.module.id; + const missing: string[] = []; + const needEnglish: string[] = []; + const inEnglish = english(); + for (const [name, probe] of Object.entries(entry.module.probes ?? {})) { + if (typeof probe !== 'string' && probe.english && !inEnglish) { needEnglish.push(name); continue; } + let found = false; + try { found = !!doc.querySelector(selectorOf(entry.module, name)); } catch { found = false; } + if (!found) missing.push(name); + } + if (needEnglish.length) waiting.set(id, needEnglish); else waiting.delete(id); + if (!missing.length) { strikes.delete(id); return; } + const count = (strikes.get(id) ?? 0) + 1; + strikes.set(id, count); + if (count < PROBE_STRIKES) return; + paused.set(id, missing); + stop(id); + syncAreas(); + console.warn(`[${label}] ${id} paused: nothing matches ${missing.join(', ')}`); + const feature = featureLabel(entry.spec, entry.area); + try { + api.ui.toast(feature ? text('kit.feature.paused', { feature, area: entry.area.name }) : text('kit.feature.pausedOne', { area: entry.area.name }), { tone: 'warning', duration: 8000 }); + } catch { /* a page without a body yet: the note in the settings dialog remains */ } + }; + entry.timer = timers.setTimeout(waitForSettle, pollMs); + } + + // ---- Settings dialog and the area's command -------------------------------------------------- + + function openSettings(areaId: string, only?: string): boolean { + const area = areas.get(areaId); + if (!area) return false; + const entries = [...running.values()].filter(entry => entry.area.id === areaId && entry.module.settings?.length && (!only || entry.module.id === only)); + const notes = health().filter(note => note.area === areaId); + if (!entries.length && !notes.length) return false; + const ui = api.ui; + const h = ui.h; + const forms = entries.map(entry => { + const name = featureName(entry.module.id); + const i18n = words(area); + return { entry, title: featureLabel(entry.spec, area) ?? name, form: buildSettingsForm(h, entry.module.settings!, entry.settings.get(), key => i18n.t(`${name}.${key}`)) }; + }); + const single = forms.length === 1 && !notes.length ? forms[0]! : null; + ui.dialog({ + title: text('kit.feature.settings', { name: single ? single.title : area.name }), + content: body => { + forms.forEach((item, index) => { + if (index > 0) body.append(h('div', { class: 'wb-divider' })); + if (!single) body.append(h('p', { class: 'wb-label' }, item.title)); + body.append(...item.form.nodes); + }); + for (const note of notes) { + const spec = specs.get(note.id)!; + const feature = featureLabel(spec, area) ?? featureName(note.id); + body.append(h('p', { class: 'wb-hint' }, note.state === 'paused' ? text('kit.feature.paused', { feature, area: area.name }) : text('kit.feature.needsEnglish', { feature }))); + } + }, + actions: forms.length ? [ + { label: text('kit.cancel') }, + { + label: text('kit.feature.save'), tone: 'primary', default: true, + onClick: handle => { + const failed = forms.filter(item => !item.entry.settings.set(item.form.read())); + if (failed.length) { handle.setError(text('kit.failed')); return false; } + return undefined; + }, + }, + ] : undefined, + }); + return true; + } + + /** Each area with a running feature that has settings gets its one "settings" palette command. */ + function syncAreas() { + for (const area of table.areas) { + const needs = [...running.values()].some(entry => entry.area.id === area.id && entry.module.settings?.length); + const scope = areaScopes.get(area.id); + if (needs && !scope) { + const created = api.commands.withOwner(area.owner, () => api.scope()); + areaScopes.set(area.id, created); + try { + created.commands.register({ id: 'settings', title: text('kit.feature.settings', { name: area.name }), keywords: `settings options configure ${area.name}`, run: () => { openSettings(area.id); } }); + } catch (error) { console.error(`[${label}] ${area.name} settings command failed`, error); } + } else if (!needs && scope) { + scope.dispose(); + areaScopes.delete(area.id); + } + } + } + + function health(): FeatureHealth[] { + const out: FeatureHealth[] = []; + for (const [id, probes] of paused) out.push({ id, area: specs.get(id)!.area!, state: 'paused', probes }); + for (const [id, probes] of waiting) if (!paused.has(id)) out.push({ id, area: specs.get(id)!.area!, state: 'needs-english', probes }); + return out; + } + + function refresh() { + for (const module of modules.values()) { + const on = running.has(module.id); + const want = wanted(module); + if (want && !on) start(module); + else if (!want && on) stop(module.id); + else if (want && on) scheduleProbes(running.get(module.id)!); + } + syncAreas(); + } + + return { + define(module) { + const spec = specs.get(module.id); + if (!spec || spec.backing !== 'module' || spec.area === null || !areas.has(spec.area)) throw new Error(`${label}: ${module.id} is not a feature module in the table`); + if (modules.has(module.id)) throw new Error(`${label}: ${module.id} is defined twice`); + const problems = validateSchema(module.settings ?? []); + if (problems.length) throw new Error(`${label}: ${module.id} settings: ${problems.join('; ')}`); + if (!!module.settings?.length !== !!spec.settings) throw new Error(`${label}: ${module.id}: the table's "settings" and the module's schema disagree`); + modules.set(module.id, module); + stopRoutes ??= api.onRouteChange(() => { visit += 1; refresh(); }); + if (wanted(module)) { start(module); syncAreas(); } + }, + setFlags(next) { + flags = { ...next }; + refresh(); + }, + refresh, + active: () => [...running.keys()], + health, + openSettings, + dispose() { + stopRoutes?.(); + stopRoutes = null; + for (const id of [...running.keys()]) stop(id); + for (const scope of areaScopes.values()) scope.dispose(); + areaScopes.clear(); + modules.clear(); + }, + }; +} + +/** Whether an area's switch is on in `flags` (a missing value counts as on). */ +export const areaEnabled = (flags: Readonly, area: string) => flags[areaFlag(area)] !== false; diff --git a/packages/runtime/src/featureTable.ts b/packages/runtime/src/featureTable.ts new file mode 100644 index 0000000..ee3eae6 --- /dev/null +++ b/packages/runtime/src/featureTable.ts @@ -0,0 +1,233 @@ +// The feature table: one data description of everything an app lets its owner switch, shared by the +// page runtime (which flags exist, who owns them), the panel (the area cards, the Fixes list, the +// onboarding modes) and the app's native side (the migration list it generates from it). Pure data +// and pure functions: no DOM, no storage. +// +// - An AREA is one card in the Plugins list ("Navigation+"): a master switch and the features it +// owns. Its switch is the flag `area.`. +// - A FEATURE is one on/off flag. It belongs to an area, or to nobody (`area: null`: a core flag +// such as a reliability fix, which no plugin switch can turn off). Where its code lives is its +// `backing`: a feature module in the registry (featureModules.ts), a part of the app runtime +// (request hubs, native commands, document-start timing), or an old plugin file that has not +// been ported yet (then it is not a flag at all: its switch is that file's enabled state). +// - A MODE is a preset (Basic / Advanced / Power User): the flag values it starts from. A mode is a +// starting point, not a lock: every flag stays individually switchable afterwards. +// +// Flags are stored sparsely (`sparseFlags`): only values that differ from the table's defaults. + +/** Flags a store may hold (the native cap, waybetter-host `settings::MAX_FEATURES`). */ +export const FLAG_LIMIT = 256; +/** Characters in a flag key (the native cap). */ +export const FLAG_KEY_LIMIT = 64; + +export type FeatureBacking = 'module' | 'app' | 'plugin'; + +export type FeatureSpec = { + /** The flag key. Existing names stay as they are; new ones are `.`. */ + id: string; + /** The owning area, or null for a core flag. */ + area: string | null; + /** The rows it is listed with inside its card (words: `features.group.`). */ + group?: string; + /** Its value when nothing is stored. */ + default: boolean; + /** + * Where its code lives: `module` = a feature module (featureModules.ts); `app` = a part of the + * app runtime that installs on the flag; `plugin` = an old plugin file until it is ported. + */ + backing: FeatureBacking; + /** `backing: 'plugin'`: that file. Its enabled state is the switch; `id` is the flag it becomes. */ + file?: string; + /** The old plugin file this feature replaces: the one-time migration turns its enabled state into this flag. */ + supersedes?: string; + /** Surfaces it runs on (ids from the app's surface classifier); omitted = every page. */ + surfaces?: readonly string[]; + /** Also runs on the site's heavy pages (domHub `heavyPath`). */ + heavy?: boolean; + /** Catalog key of its label (default `features..label`). */ + label?: string; + /** Catalog key of its description (default `features..description`). */ + description?: string; + /** It has settings of its own (a settings schema on its module): the card offers "Settings". */ + settings?: boolean; + /** Extra words the panel search matches (an old plugin's name). */ + keywords?: string; + /** The gated plugin API it uses (shown on the card). */ + permissions?: readonly string[]; +}; + +export type AreaSpec = { + /** `navigation`: lowercase letters, digits and `-`. */ + id: string; + /** The card's name: a product name, the same in every language. */ + name: string; + /** Catalog key of the card's description. */ + description: string; + /** A 16x16 stroke path for the card's icon. */ + icon?: string; + /** + * The owner of its palette commands and the file it ships as once it is a plugin file + * (`bt-navigation-plus.plugin.js`). A valid plugin file name. + */ + owner: string; + /** Its words in the page: `plugin..*` (`navigation-plus`). */ + namespace: string; +}; + +export type ModeSpec = { + id: string; + /** Catalog keys of its name and one-line description. */ + name: string; + description: string; + /** The preselected one on the first-run screen. */ + recommended?: boolean; + /** Flag values that differ from the table's defaults. */ + flags: Readonly>; +}; + +export type FeatureTable = { + areas: readonly AreaSpec[]; + features: readonly FeatureSpec[]; + modes: readonly ModeSpec[]; +}; + +export type Flags = Record; + +/** The flag that is an area's master switch. */ +export const areaFlag = (area: string) => `area.${area}`; + +/** Features that are flags (everything but the ones still backed by an old plugin file). */ +export const flagFeatures = (table: FeatureTable) => table.features.filter(feature => feature.backing !== 'plugin'); + +export const areaFeatures = (table: FeatureTable, area: string) => table.features.filter(feature => feature.area === area); +export const coreFeatures = (table: FeatureTable) => table.features.filter(feature => feature.area === null); + +/** The catalog keys of a feature's label and description. */ +export function featureWords(feature: FeatureSpec): { label: string; description: string } { + return { label: feature.label ?? `features.${feature.id}.label`, description: feature.description ?? `features.${feature.id}.description` }; +} + +/** Every flag with its default: the features that are flags, and each area's switch (on). */ +export function tableDefaults(table: FeatureTable): Flags { + const out: Flags = {}; + for (const feature of flagFeatures(table)) out[feature.id] = feature.default; + for (const area of table.areas) out[areaFlag(area.id)] = true; + return out; +} + +/** The full flag map for `input`: unknown keys are dropped, anything not a boolean takes the default. */ +export function normalizeFlags(table: FeatureTable, input: unknown): Flags { + const source = input && typeof input === 'object' ? input as Record : {}; + const out = tableDefaults(table); + for (const key of Object.keys(out)) if (typeof source[key] === 'boolean') out[key] = source[key] as boolean; + return out; +} + +/** What is stored: only the flags whose value differs from the default. */ +export function sparseFlags(table: FeatureTable, flags: Readonly>): Flags { + const defaults = tableDefaults(table); + const out: Flags = {}; + for (const [key, fallback] of Object.entries(defaults)) { + const value = flags[key]; + if (typeof value === 'boolean' && value !== fallback) out[key] = value; + } + return out; +} + +/** + * What runs: a feature owned by an area is off while that area's switch is off. Core flags and the + * area switches themselves pass through. + */ +export function effectiveFlags(table: FeatureTable, flags: Readonly): Flags { + const out: Flags = { ...flags }; + for (const feature of flagFeatures(table)) { + if (feature.area !== null && flags[areaFlag(feature.area)] === false) out[feature.id] = false; + } + return out; +} + +export const modeById = (table: FeatureTable, id: string | null | undefined) => table.modes.find(mode => mode.id === id) ?? null; + +/** The full flag map a mode starts from (an unknown or null mode: the defaults). */ +export function modeFlags(table: FeatureTable, mode: string | null | undefined): Flags { + const out = tableDefaults(table); + const preset = modeById(table, mode)?.flags ?? {}; + for (const [key, value] of Object.entries(preset)) if (key in out) out[key] = value; + return out; +} + +/** The flags whose value is not what `mode` starts from: the owner's own changes. */ +export function manualChanges(table: FeatureTable, flags: Readonly, mode: string | null | undefined): string[] { + const preset = modeFlags(table, mode); + return Object.keys(preset).filter(key => typeof flags[key] === 'boolean' && flags[key] !== preset[key]); +} + +/** + * The flags after choosing mode `to` while on mode `from` (null = never chosen). `keep`: the + * owner's own changes (whatever differs from `from`) stay on top of the new mode; otherwise the + * new mode's values apply as they are. + */ +export function switchMode(table: FeatureTable, flags: Readonly, from: string | null | undefined, to: string, keep: boolean): Flags { + const next = modeFlags(table, to); + if (keep) for (const key of manualChanges(table, flags, from)) next[key] = flags[key]!; + return next; +} + +/** The old plugin files the table's features replace, for the app's native migration list. */ +export function supersededFiles(table: FeatureTable): { file: string; flag: string }[] { + return table.features.filter(feature => feature.supersedes && feature.backing !== 'plugin').map(feature => ({ file: feature.supersedes!, flag: feature.id })); +} + +const FLAG_ID = /^[A-Za-z][A-Za-z0-9]*(?:\.[A-Za-z][A-Za-z0-9]*)?$/; +const AREA_ID = /^[a-z][a-z0-9-]{0,31}$/; +const MODE_ID = /^[a-z][a-z0-9-]{0,31}$/; +const PLUGIN_FILE = /^[A-Za-z0-9_\- ][A-Za-z0-9_.\- ]{0,117}\.plugin\.js$/; + +/** Problems in a table (an empty list: valid). Run it in the app's tests. */ +export function validateTable(table: FeatureTable): string[] { + const problems: string[] = []; + const areas = new Set(); + for (const area of table.areas) { + if (!AREA_ID.test(area.id)) problems.push(`area ${JSON.stringify(area.id)}: invalid id`); + if (areas.has(area.id)) problems.push(`area ${area.id}: listed twice`); + areas.add(area.id); + if (!PLUGIN_FILE.test(area.owner)) problems.push(`area ${area.id}: owner must be a plugin file name`); + if (!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(area.namespace)) problems.push(`area ${area.id}: invalid namespace`); + if (!area.name.trim() || !area.description.trim()) problems.push(`area ${area.id}: name and description are required`); + } + const ids = new Set(); + const files = new Set(); + for (const feature of table.features) { + if (!FLAG_ID.test(feature.id) || feature.id.length > FLAG_KEY_LIMIT) problems.push(`feature ${JSON.stringify(feature.id)}: invalid id`); + if (feature.id.startsWith('area.')) problems.push(`feature ${feature.id}: "area." is kept for the area switches`); + if (ids.has(feature.id)) problems.push(`feature ${feature.id}: owned twice`); + ids.add(feature.id); + if (feature.area !== null && !areas.has(feature.area)) problems.push(`feature ${feature.id}: unknown area ${feature.area}`); + if (feature.backing === 'plugin') { + if (!feature.file || !PLUGIN_FILE.test(feature.file)) problems.push(`feature ${feature.id}: a plugin-backed feature names its file`); + if (feature.area === null) problems.push(`feature ${feature.id}: a plugin-backed feature belongs to an area`); + if (feature.default) problems.push(`feature ${feature.id}: a plugin file is off until its owner turns it on`); + } else if (feature.file) problems.push(`feature ${feature.id}: only a plugin-backed feature names a file`); + for (const file of [feature.file, feature.supersedes]) { + if (!file) continue; + if (!PLUGIN_FILE.test(file)) problems.push(`feature ${feature.id}: invalid file ${JSON.stringify(file)}`); + if (files.has(file)) problems.push(`feature ${feature.id}: ${file} is named twice`); + files.add(file); + } + if (feature.backing !== 'module' && feature.settings) problems.push(`feature ${feature.id}: only a feature module has a settings schema`); + } + const defaults = tableDefaults(table); + if (Object.keys(defaults).length > FLAG_LIMIT) problems.push(`${Object.keys(defaults).length} flags: at most ${FLAG_LIMIT}`); + const modes = new Set(); + for (const mode of table.modes) { + if (!MODE_ID.test(mode.id)) problems.push(`mode ${JSON.stringify(mode.id)}: invalid id`); + if (modes.has(mode.id)) problems.push(`mode ${mode.id}: listed twice`); + modes.add(mode.id); + for (const [key, value] of Object.entries(mode.flags)) { + if (!(key in defaults)) problems.push(`mode ${mode.id}: unknown flag ${key}`); + else if (value === defaults[key]) problems.push(`mode ${mode.id}: ${key} is already the default`); + } + } + if (table.modes.length && table.modes.filter(mode => mode.recommended).length !== 1) problems.push('exactly one mode is the recommended one'); + return problems; +} diff --git a/packages/runtime/src/pluginApi.ts b/packages/runtime/src/pluginApi.ts index 2379385..735e1cd 100644 --- a/packages/runtime/src/pluginApi.ts +++ b/packages/runtime/src/pluginApi.ts @@ -9,6 +9,7 @@ import { createThemeApi, type ThemeApi, type ThemeSource } from './themeApi.ts'; import { createUiKit, type UiKit } from './ui.ts'; import { adoptStyles, type RootStyles } from './styles.ts'; +import { observeSelector } from './domHub.ts'; import { createCommandRegistry, type CommandDefinition, type CommandInfo, type CommandRegistry } from './commands.ts'; import { createPluginI18n, type I18nSource, type PluginI18n, type PluginMessages } from './pluginI18n.ts'; @@ -60,7 +61,10 @@ export type CorePluginApi = { storage(namespace: string): PluginStorage; /** Called after the page changes route (pushState/replaceState/back/forward). */ onRouteChange(callback: (href: string, previous: string) => void): Dispose; - /** Calls `callback` once for every element matching `selector`, now and as the page renders more. */ + /** + * Calls `callback` once for every element matching `selector`, now and as the page renders more. + * Page-wide observers share one MutationObserver (domHub.ts); pass `root` only for a tree of your own. + */ observe(selector: string, callback: (element: Element) => void, root?: ParentNode): Dispose; /** * Single-key shortcuts: `callback(event, focusedItem)` runs only when the user is not typing, no @@ -263,13 +267,16 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi }; }, observe(selector, callback, root) { + // The whole page: the shared hub (one MutationObserver and one frame for every plugin and + // feature). A root of the caller's own (a shadow root, a detached tree) keeps its own observer. + if (!root || root === doc) return observeSelector(win, selector, callback, { report }); const seen = new WeakSet(); let frame = 0; let disposed = false; const scan = () => { frame = 0; if (disposed) return; - for (const element of Array.from((root ?? doc).querySelectorAll(selector))) { + for (const element of Array.from(root.querySelectorAll(selector))) { if (seen.has(element)) continue; seen.add(element); try { callback(element); } catch (error) { report(error); } @@ -278,7 +285,7 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi const observer = new win.MutationObserver(() => { if (!frame) frame = win.requestAnimationFrame(scan); }); - observer.observe((root as Node | undefined) ?? doc.documentElement, { childList: true, subtree: true }); + observer.observe(root as Node, { childList: true, subtree: true }); scan(); return () => { disposed = true; diff --git a/packages/runtime/src/settingsForm.ts b/packages/runtime/src/settingsForm.ts new file mode 100644 index 0000000..61d719f --- /dev/null +++ b/packages/runtime/src/settingsForm.ts @@ -0,0 +1,135 @@ +// A settings schema: what a feature (or a plugin) lets its owner adjust, as data. The same schema +// gives the stored values their shape (`normalizeSettings`: anything missing or of the wrong type +// takes the field's default, so an old or damaged store never breaks a feature) and draws the +// controls from the UI kit's form parts (`buildSettingsForm`: check boxes, number, text, select and +// list fields inside a kit dialog). Labels and hints are catalog keys the caller translates. + +import type { UiKit } from './ui.ts'; + +type FieldBase = { + /** The key in the stored values. */ + key: string; + /** Catalog key of the label. */ + label: string; + /** Catalog key of a line under the label. */ + hint?: string; +}; + +export type SettingField = + | (FieldBase & { type: 'toggle'; default: boolean }) + | (FieldBase & { type: 'number'; default: number; min?: number; max?: number; step?: number }) + | (FieldBase & { type: 'text'; default: string; maxLength?: number; multiline?: boolean; placeholder?: string }) + | (FieldBase & { type: 'select'; default: string; options: ReadonlyArray<{ value: string; label: string }> }) + /** Lines of text (patterns, handles): one per line in the form. */ + | (FieldBase & { type: 'list'; default: readonly string[]; maxItems?: number; maxLength?: number }) + | { type: 'divider' }; + +export type SettingsSchema = readonly SettingField[]; +export type SettingValue = boolean | number | string | string[]; +export type SettingValues = Record; + +export const SETTINGS_LIMITS = Object.freeze({ fields: 64, text: 2000, listItems: 500, listItem: 500 }); + +type ValueField = Exclude; +const valueFields = (schema: SettingsSchema) => schema.filter((field): field is ValueField => field.type !== 'divider'); + +function fieldValue(field: ValueField, value: unknown): SettingValue { + switch (field.type) { + case 'toggle': + return typeof value === 'boolean' ? value : field.default; + case 'number': { + if (typeof value !== 'number' || !Number.isFinite(value)) return field.default; + return Math.min(field.max ?? Infinity, Math.max(field.min ?? -Infinity, value)); + } + case 'text': + return typeof value === 'string' ? value.slice(0, Math.min(field.maxLength ?? SETTINGS_LIMITS.text, SETTINGS_LIMITS.text)) : field.default; + case 'select': + return typeof value === 'string' && field.options.some(option => option.value === value) ? value : field.default; + case 'list': { + if (!Array.isArray(value)) return [...field.default]; + const max = Math.min(field.maxLength ?? SETTINGS_LIMITS.listItem, SETTINGS_LIMITS.listItem); + return value.filter((item): item is string => typeof item === 'string' && item.trim() !== '').map(item => item.slice(0, max)).slice(0, Math.min(field.maxItems ?? SETTINGS_LIMITS.listItems, SETTINGS_LIMITS.listItems)); + } + } +} + +/** The values for `schema` from whatever was stored: every field present, every value of its type and in range. */ +export function normalizeSettings(schema: SettingsSchema, stored: unknown): SettingValues { + const source = stored && typeof stored === 'object' ? stored as Record : {}; + const out: SettingValues = {}; + for (const field of valueFields(schema)) out[field.key] = fieldValue(field, source[field.key]); + return out; +} + +/** Problems in a schema (an empty list: valid). */ +export function validateSchema(schema: SettingsSchema): string[] { + const problems: string[] = []; + const keys = new Set(); + const fields = valueFields(schema); + if (fields.length > SETTINGS_LIMITS.fields) problems.push(`at most ${SETTINGS_LIMITS.fields} fields`); + for (const field of fields) { + if (!/^[A-Za-z][A-Za-z0-9]{0,39}$/.test(field.key)) problems.push(`invalid key ${JSON.stringify(field.key)}`); + if (keys.has(field.key)) problems.push(`${field.key}: listed twice`); + keys.add(field.key); + if (!field.label) problems.push(`${field.key}: a label is required`); + if (field.type === 'select' && !field.options.some(option => option.value === field.default)) problems.push(`${field.key}: the default is not an option`); + if (field.type === 'number' && (field.min ?? -Infinity) > (field.max ?? Infinity)) problems.push(`${field.key}: min is above max`); + } + return problems; +} + +export type SettingsForm = { + /** The controls, in schema order: append them to a dialog's body. */ + nodes: HTMLElement[]; + /** The values as the controls show them now (normalized). */ + read(): SettingValues; +}; + +/** + * The controls for `schema` showing `values`, built with the kit's element builder and styled by the + * kit's form classes. `text(key)` translates a label, hint or option key. + */ +export function buildSettingsForm(h: UiKit['h'], schema: SettingsSchema, values: SettingValues, text: (key: string) => string): SettingsForm { + const readers: Array<[ValueField, () => unknown]> = []; + const nodes: HTMLElement[] = []; + for (const field of schema) { + if (field.type === 'divider') { nodes.push(h('div', { class: 'wb-divider' })); continue; } + const value = values[field.key]; + const hint = field.hint ? text(field.hint) : ''; + if (field.type === 'toggle') { + const input = h('input', { type: 'checkbox', checked: value === true }) as HTMLInputElement; + nodes.push(h('label', { class: 'wb-check' }, input, h('span', null, text(field.label), hint ? h('small', null, hint) : null))); + readers.push([field, () => input.checked]); + continue; + } + let control: HTMLElement; + if (field.type === 'number') { + const input = h('input', { type: 'number', value: String(value), min: field.min, max: field.max, step: field.step ?? 1 }) as HTMLInputElement; + readers.push([field, () => (input.value.trim() === '' ? NaN : Number(input.value))]); + control = input; + } else if (field.type === 'select') { + const select = h('select', null, field.options.map(option => h('option', { value: option.value, selected: option.value === value }, text(option.label)))) as HTMLSelectElement; + readers.push([field, () => select.value]); + control = select; + } else if (field.type === 'list') { + const area = h('textarea', { class: 'wb-mono', rows: 5, spellcheck: false, value: (value as string[]).join('\n') }) as HTMLTextAreaElement; + readers.push([field, () => area.value.split(/\r?\n/).map(line => line.trim()).filter(Boolean)]); + control = area; + } else { + const input = (field.multiline + ? h('textarea', { rows: 4, value: String(value), maxLength: field.maxLength, placeholder: field.placeholder }) + : h('input', { type: 'text', value: String(value), maxLength: field.maxLength, placeholder: field.placeholder })) as HTMLInputElement | HTMLTextAreaElement; + readers.push([field, () => input.value]); + control = input; + } + nodes.push(h('label', { class: 'wb-field' }, h('span', { class: 'wb-label' }, text(field.label)), control, hint ? h('p', { class: 'wb-hint' }, hint) : null)); + } + return { + nodes, + read() { + const raw: Record = {}; + for (const [field, read] of readers) raw[field.key] = read(); + return normalizeSettings(schema, raw); + }, + }; +} diff --git a/packages/runtime/src/siteRuntime.ts b/packages/runtime/src/siteRuntime.ts index c8b9152..32ee191 100644 --- a/packages/runtime/src/siteRuntime.ts +++ b/packages/runtime/src/siteRuntime.ts @@ -55,14 +55,22 @@ export type FeatureFlagsOptions> = { label: string; /** Parts that install when their flag turns on and dispose when it turns off, in install order. */ installers: ReadonlyArray>; - /** Every applied config, before the installers (flags that are CSS, or that another part reads). */ - apply?(config: Partial): void; + /** Every applied config (the full map), before the installers (flags that are CSS, or that another part reads). */ + apply?(config: Flags): void; + /** + * What owns what: given the delivered flags over the defaults, the flags that really run (an + * area whose switch is off turns its features off; featureTable `effectiveFlags`). + */ + resolve?(flags: Flags): Flags; /** The page's document: a column's flags delivered at document start wait for `` to exist. */ document?: Document; }; export type FeatureFlags> = { - /** The flags native code delivers (the owner's tweaks); a deck column's overrides stay on top. */ + /** + * The flags native code delivers (the owner's choices); a deck column's overrides stay on top. + * A delivery is the whole state, stored sparsely: a flag it does not name is at its default. + */ apply(config: Partial): void; /** * A deck column's flag overrides (allow-listed natively; unknown keys and non-booleans are @@ -75,6 +83,8 @@ export type FeatureFlags> = { set(flag: keyof Flags & string, enabled: boolean): void; /** Whether a flag's installer is installed right now. */ installed(flag: keyof Flags & string): boolean; + /** Every flag as it runs right now (defaults, the delivery, ownership, the column). */ + current(): Flags; }; export function createFeatureFlags>(options: FeatureFlagsOptions): FeatureFlags { @@ -99,38 +109,43 @@ export function createFeatureFlags>(option let globalFlags: Partial = {}; let columnFlags: Partial = {}; - const merged = (previous: Partial = {}): Partial => { - const restore = Object.fromEntries(Object.keys(previous).map(key => [key, defaults[key]])) as Partial; - return { ...restore, ...globalFlags, ...columnFlags }; - }; - const applyAll = (config: Partial) => { - options.apply?.(config); - for (const [flag] of installers) { - const enabled = config[flag]; - if (typeof enabled === 'boolean') set(flag, enabled); + const known = (input: unknown): Partial => { + const out: Record = {}; + if (input && typeof input === 'object') { + for (const [key, value] of Object.entries(input)) if (key in defaults && typeof value === 'boolean') out[key] = value; } + return out as Partial; + }; + // What runs: the defaults, the delivered flags over them, what owns what (`resolve`), and a + // column's own choices on top. + const current = (): Flags => { + const base = { ...defaults, ...globalFlags } as Flags; + return { ...(options.resolve ? options.resolve(base) : base), ...columnFlags }; + }; + const applyAll = () => { + const config = current(); + options.apply?.(config); + for (const [flag] of installers) set(flag, config[flag]); }; return { apply(config) { - globalFlags = { ...globalFlags, ...config }; - applyAll(Object.keys(columnFlags).length ? merged() : config); + globalFlags = known(config); + applyAll(); }, setColumnFlags(flags) { - const next: Partial = {}; - if (flags && typeof flags === 'object') { - for (const [key, value] of Object.entries(flags)) if (key in defaults && typeof value === 'boolean') (next as Record)[key] = value; - } + const next = known(flags); const previous = columnFlags; columnFlags = next; if (!Object.keys(previous).length && !Object.keys(next).length) return; - const apply = () => { try { applyAll(merged(previous)); } catch (error) { console.error(`[${label}] column flags failed`, error); } }; + const apply = () => { try { applyAll(); } catch (error) { console.error(`[${label}] column flags failed`, error); } }; const doc = options.document; if (!doc || doc.documentElement) apply(); else doc.addEventListener('DOMContentLoaded', apply, { once: true }); }, set, installed: flag => active.has(flag), + current, }; } diff --git a/packages/runtime/tests/features.test.ts b/packages/runtime/tests/features.test.ts new file mode 100644 index 0000000..aa49e9a --- /dev/null +++ b/packages/runtime/tests/features.test.ts @@ -0,0 +1,386 @@ +// The feature table (areas, flags, modes), the settings schema and the feature-module registry: +// flag and surface gating, ownership, one shared observer, the command budget, settings, hotfix +// overrides and the selector health check. +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { observeSelector, type DomWindow } from '../src/domHub.ts'; +import { AREA_COMMAND_BUDGET, PROBE_STRIKES, createFeatureRegistry, type FeatureModule, type HotfixData } from '../src/featureModules.ts'; +import { + areaFlag, effectiveFlags, manualChanges, modeFlags, normalizeFlags, sparseFlags, supersededFiles, switchMode, tableDefaults, validateTable, + type FeatureTable, +} from '../src/featureTable.ts'; +import { createCorePluginApi, type CorePluginApi, type PluginApiSite } from '../src/pluginApi.ts'; +import { normalizeSettings, validateSchema, type SettingsSchema } from '../src/settingsForm.ts'; + +const TABLE: FeatureTable = { + areas: [ + { id: 'navigation', name: 'Navigation+', description: 'plugin.navigation-plus.description', owner: 'wb-navigation-plus.plugin.js', namespace: 'navigation-plus' }, + { id: 'reader', name: 'Reader+', description: 'plugin.reader-plus.description', owner: 'wb-reader-plus.plugin.js', namespace: 'reader-plus' }, + ], + features: [ + { id: 'fixScroll', area: null, group: 'fixes', default: true, backing: 'app' }, + { id: 'hideTrends', area: 'navigation', default: false, backing: 'module', surfaces: ['timeline'] }, + { id: 'navigation.focusMode', area: 'navigation', default: false, backing: 'module', settings: true, supersedes: 'wb-focus-mode.plugin.js' }, + { id: 'navigation.keys', area: 'navigation', default: false, backing: 'module' }, + { id: 'hideAds', area: 'reader', default: true, backing: 'app' }, + { id: 'reader.cleanLinks', area: 'reader', default: false, backing: 'plugin', file: 'wb-clean-links.plugin.js' }, + ], + modes: [ + { id: 'basic', name: 'mode.basic', description: 'mode.basic.text', flags: { 'area.navigation': false, 'area.reader': false } }, + { id: 'advanced', name: 'mode.advanced', description: 'mode.advanced.text', recommended: true, flags: {} }, + { id: 'power', name: 'mode.power', description: 'mode.power.text', flags: { 'navigation.keys': true } }, + ], +}; + +test('feature table: defaults, normalizing, sparse storage and ownership', () => { + assert.deepEqual(validateTable(TABLE), []); + const defaults = tableDefaults(TABLE); + assert.deepEqual(defaults, { fixScroll: true, hideTrends: false, 'navigation.focusMode': false, 'navigation.keys': false, hideAds: true, 'area.navigation': true, 'area.reader': true }, + 'a feature still backed by a plugin file is not a flag; every area has its switch, on'); + assert.deepEqual(normalizeFlags(TABLE, { hideTrends: true, hideAds: 'yes', unknown: true, 'reader.cleanLinks': true }), { ...defaults, hideTrends: true }, 'unknown keys dropped, non-booleans take the default'); + assert.deepEqual(sparseFlags(TABLE, { ...defaults, hideTrends: true, hideAds: false }), { hideTrends: true, hideAds: false }, 'only what differs from the default is stored'); + assert.deepEqual(sparseFlags(TABLE, defaults), {}); + // An area that is off turns off what it owns; core flags and other areas are untouched. + const off = effectiveFlags(TABLE, { ...defaults, hideTrends: true, [areaFlag('reader')]: false }); + assert.equal(off.hideAds, false); + assert.equal(off.hideTrends, true); + assert.equal(off.fixScroll, true, 'no plugin switch turns a core flag off'); + assert.deepEqual(supersededFiles(TABLE), [{ file: 'wb-focus-mode.plugin.js', flag: 'navigation.focusMode' }]); +}); + +test('feature table: a mode is a starting point; changing it keeps or drops the manual changes', () => { + const defaults = tableDefaults(TABLE); + assert.deepEqual(modeFlags(TABLE, 'advanced'), defaults); + assert.deepEqual(modeFlags(TABLE, null), defaults, 'never chosen: the defaults'); + assert.equal(modeFlags(TABLE, 'basic')['area.reader'], false); + // The owner, on Advanced, turned trends hiding on and ads hiding off. + const mine = { ...defaults, hideTrends: true, hideAds: false }; + assert.deepEqual(manualChanges(TABLE, mine, 'advanced').sort(), ['hideAds', 'hideTrends']); + const kept = switchMode(TABLE, mine, 'advanced', 'power', true); + assert.deepEqual(kept, { ...defaults, 'navigation.keys': true, hideTrends: true, hideAds: false }); + const reset = switchMode(TABLE, mine, 'advanced', 'power', false); + assert.deepEqual(reset, { ...defaults, 'navigation.keys': true }); + // From Basic back to Advanced with "keep": the areas Basic switched off are not manual changes. + const basic = switchMode(TABLE, mine, 'advanced', 'basic', false); + assert.deepEqual(manualChanges(TABLE, basic, 'basic'), []); + assert.deepEqual(switchMode(TABLE, basic, 'basic', 'advanced', true), defaults); +}); + +test('feature table: problems are reported', () => { + const bad: FeatureTable = { + areas: [{ id: 'Nav', name: 'Nav', description: 'd', owner: 'nav.js', namespace: 'nav' }, ...TABLE.areas], + features: [ + ...TABLE.features, + { id: 'hideTrends', area: 'reader', default: false, backing: 'app' }, + { id: 'area.x', area: null, default: false, backing: 'app' }, + { id: 'lost', area: 'nowhere', default: false, backing: 'app' }, + { id: 'reader.x', area: 'reader', default: true, backing: 'plugin' }, + { id: 'reader.y', area: 'reader', default: false, backing: 'app', settings: true }, + ], + modes: [...TABLE.modes, { id: 'odd', name: 'n', description: 'd', recommended: true, flags: { nope: true, hideAds: true } }], + }; + const problems = validateTable(bad).join('\n'); + for (const expected of ['area "Nav": invalid id', 'owner must be a plugin file name', 'hideTrends: owned twice', 'area.x: "area." is kept', 'lost: unknown area', 'reader.x: a plugin-backed feature names its file', + 'reader.x: a plugin file is off', 'reader.y: only a feature module has a settings schema', 'mode odd: unknown flag nope', 'mode odd: hideAds is already the default', 'exactly one mode is the recommended one']) { + assert.ok(problems.includes(expected), `${expected}\n${problems}`); + } +}); + +const SCHEMA: SettingsSchema = [ + { key: 'enabled', type: 'toggle', default: true, label: 'enabled' }, + { type: 'divider' }, + { key: 'days', type: 'number', default: 30, min: 1, max: 365, label: 'days' }, + { key: 'mode', type: 'select', default: 'calm', options: [{ value: 'calm', label: 'calm' }, { value: 'zen', label: 'zen' }], label: 'mode' }, + { key: 'note', type: 'text', default: '', maxLength: 5, label: 'note' }, + { key: 'patterns', type: 'list', default: [], maxItems: 2, label: 'patterns' }, +]; + +test('settings schema: stored values are normalized to the schema, whatever was stored', () => { + assert.deepEqual(validateSchema(SCHEMA), []); + assert.deepEqual(normalizeSettings(SCHEMA, null), { enabled: true, days: 30, mode: 'calm', note: '', patterns: [] }); + assert.deepEqual(normalizeSettings(SCHEMA, { enabled: 'no', days: 9999, mode: 'loud', note: 'too long', patterns: ['a', '', 3, 'b', 'c'], extra: 1 }), + { enabled: true, days: 365, mode: 'calm', note: 'too l', patterns: ['a', 'b'] }); + assert.deepEqual(normalizeSettings(SCHEMA, { enabled: false, days: 7, mode: 'zen' }), { enabled: false, days: 7, mode: 'zen', note: '', patterns: [] }); + const bad: SettingsSchema = [{ key: 'a', type: 'toggle', default: true, label: 'a' }, { key: 'a', type: 'number', default: 1, min: 5, max: 2, label: '' }, { key: '1x', type: 'select', default: 'z', options: [], label: 'x' }]; + const problems = validateSchema(bad).join('\n'); + for (const expected of ['a: listed twice', 'a: a label is required', 'a: min is above max', 'invalid key "1x"', '1x: the default is not an option']) assert.ok(problems.includes(expected), `${expected}\n${problems}`); +}); + +// --------------------------------------------------------------------------------------------- +// A small page: one document, a body that can hold matching elements, counted observers. + +type Listener = (event: unknown) => void; +class FakeTarget { + listeners = new Map>(); + addEventListener(type: string, fn: Listener) { (this.listeners.get(type) ?? this.listeners.set(type, new Set()).get(type)!).add(fn); } + removeEventListener(type: string, fn: Listener) { this.listeners.get(type)?.delete(fn); } + emit(type: string, event: unknown = {}) { for (const fn of [...(this.listeners.get(type) ?? [])]) fn(event); } + count(type: string) { return this.listeners.get(type)?.size ?? 0; } +} + +const SITE: PluginApiSite = { + name: 'Demo', product: 'wayBetter for Test', storagePrefix: 'demo-plugin:', styleDataKey: 'demoPlugin', + toastId: 'demo-toast', toastBackground: '#111', itemSelector: 'article', chordKeys: [], +}; + +function page() { + const styles: { dataset: Record; textContent: string; isConnected: boolean; remove(): void }[] = []; + const matches = new Map(); + const observers: Array<() => void> = []; + const store = new Map(); + const doc = new FakeTarget() as FakeTarget & Record; + Object.assign(doc, { + activeElement: null, + documentElement: { getAttribute: () => 'en' }, + body: { firstElementChild: {} }, + head: { appendChild(node: { isConnected: boolean }) { node.isConnected = true; } }, + querySelectorAll: (selector: string) => matches.get(selector) ?? [], + querySelector: (selector: string) => (matches.get(selector) ?? [])[0] ?? null, + createElement: () => { + const node = { dataset: {} as Record, textContent: '', isConnected: false, remove() { node.isConnected = false; } }; + styles.push(node); + return node; + }, + }); + const win = new FakeTarget() as FakeTarget & Record; + const location = { href: 'https://site.test/home', pathname: '/home' }; + Object.assign(win, { + document: doc, + location, + localStorage: { get length() { return store.size; }, key: (i: number) => [...store.keys()][i] ?? null, getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => { store.set(k, v); }, removeItem: (k: string) => { store.delete(k); } }, + requestAnimationFrame: (fn: () => void) => { fn(); return 1; }, + cancelAnimationFrame: () => {}, + MutationObserver: class { constructor(fn: () => void) { observers.push(() => fn()); } observe() {} disconnect() {} }, + }); + const api = createCorePluginApi(win as unknown as Window & typeof globalThis, SITE); + return { + api, win: win as unknown as Window & typeof globalThis, doc, styles, matches, observers, store, location, + /** The site rendered something: every observer fires (one frame). */ + mutate() { for (const fire of observers) fire(); }, + go(path: string) { location.href = `https://site.test${path}`; location.pathname = path; win.emit('popstate'); }, + liveStyles: () => styles.filter(style => style.isConnected && style.textContent).map(style => style.textContent), + }; +} + +type Timer = { fn: () => void; ms: number; id: number; at: number }; +function fakeTimers() { + let now = 0; + let next = 1; + let queue: Timer[] = []; + return { + setTimeout(fn: () => void, ms: number) { const id = next++; queue.push({ fn, ms, id, at: now + ms }); return id; }, + clearTimeout(id: unknown) { queue = queue.filter(timer => timer.id !== id); }, + advance(ms: number) { + const end = now + ms; + for (;;) { + const due = queue.filter(timer => timer.at <= end).sort((a, b) => a.at - b.at)[0]; + if (!due) break; + queue = queue.filter(timer => timer !== due); + now = due.at; + due.fn(); + } + now = end; + }, + pending: () => queue.length, + }; +} + +function registryFor(env: ReturnType, extra: { surfaces?: () => string[]; hotfix?: () => HotfixData; timers?: ReturnType } = {}) { + return createFeatureRegistry({ + win: env.win, table: TABLE, api: env.api, label: 'Demo', + surfaces: extra.surfaces ?? (() => (env.location.pathname === '/home' ? ['timeline', 'home'] : ['profile'])), + hotfix: extra.hotfix, timers: extra.timers, settleMs: 3000, pollMs: 500, + }); +} + +test('registry: a module runs only while its flag is on and the page is on one of its surfaces, and leaves nothing behind', () => { + const env = page(); + const registry = registryFor(env); + const log: string[] = []; + registry.define({ id: 'hideTrends', start(ctx) { log.push('+trends'); ctx.css('.trends{display:none}'); ctx.defer(() => log.push('-trends')); } }); + registry.define({ id: 'navigation.keys', start(ctx) { log.push('+keys'); ctx.onKey(() => {}); ctx.defer(() => log.push('-keys')); } }); + assert.deepEqual(registry.active(), [], 'off until the flags say so'); + assert.equal(env.doc.count('keydown'), 0, 'an idle feature holds no listener'); + + registry.setFlags(effectiveFlags(TABLE, { ...tableDefaults(TABLE), hideTrends: true, 'navigation.keys': true })); + assert.deepEqual(registry.active().sort(), ['hideTrends', 'navigation.keys']); + assert.deepEqual(env.liveStyles(), ['.trends{display:none}']); + assert.equal(env.styles.at(-1)!.dataset.demoPlugin, 'wbf-hideTrends'); + assert.equal(env.doc.count('keydown'), 1); + + env.go('/someone'); + assert.deepEqual(registry.active(), ['navigation.keys'], 'not a timeline: the surface-bound feature stopped'); + assert.deepEqual(env.liveStyles(), []); + env.go('/home'); + assert.deepEqual(registry.active().sort(), ['hideTrends', 'navigation.keys']); + + // The area's switch off: everything it owns stops, without touching the features' own flags. + registry.setFlags(effectiveFlags(TABLE, { ...tableDefaults(TABLE), hideTrends: true, 'navigation.keys': true, 'area.navigation': false })); + assert.deepEqual(registry.active(), []); + assert.deepEqual(env.liveStyles(), []); + assert.equal(env.doc.count('keydown'), 0); + assert.deepEqual(log, ['+trends', '+keys', '-trends', '+trends', '-trends', '-keys']); + + assert.throws(() => registry.define({ id: 'hideAds', start() {} }), /hideAds is not a feature module in the table/); + assert.throws(() => registry.define({ id: 'hideTrends', start() {} }), /defined twice/); + registry.dispose(); +}); + +test('registry: one MutationObserver however many features observe; plugins share it too', () => { + const env = page(); + const registry = registryFor(env); + const seen: string[] = []; + const first = {}; + env.matches.set('article', [first]); + registry.define({ id: 'hideTrends', start(ctx) { ctx.observe('article', () => seen.push('a')); ctx.observe('aside', () => seen.push('aside')); } }); + registry.define({ id: 'navigation.keys', start(ctx) { ctx.observe('article', () => seen.push('b')); ctx.watch(() => seen.push('frame')); } }); + registry.setFlags({ hideTrends: true, 'navigation.keys': true }); + const stopPlugin = env.api.observe('article', () => seen.push('plugin')); + assert.equal(env.observers.length, 1, 'one observer for three selector observers, a raw watch and a plugin'); + assert.deepEqual(seen, ['a', 'b', 'plugin'], 'what is already there is reported at once, once'); + env.matches.set('article', [first, {}]); + env.matches.set('aside', [{}]); + env.mutate(); + assert.deepEqual(seen.slice(3).sort(), ['a', 'aside', 'b', 'frame', 'plugin'], 'only the new elements'); + stopPlugin(); + registry.dispose(); + const before = seen.length; + env.mutate(); + assert.equal(seen.length, before, 'nothing runs after dispose'); +}); + +test('registry: a failing module is contained; heavy pages pause features that did not ask for them', () => { + const env = page(); + const errors: unknown[] = []; + const original = console.error; + console.error = (...args: unknown[]) => { errors.push(args[0]); }; + try { + const registry = registryFor(env, { surfaces: () => ['timeline'] }); + registry.define({ id: 'hideTrends', start(ctx) { ctx.css('x{}'); throw new Error('markup changed'); } }); + registry.define({ id: 'navigation.keys', start() {} }); + registry.setFlags({ hideTrends: true, 'navigation.keys': true }); + assert.deepEqual(registry.active(), ['navigation.keys']); + assert.match(String(errors[0]), /\[Demo\] hideTrends failed/); + assert.deepEqual(env.liveStyles(), [], 'what it did before failing is undone'); + registry.dispose(); + } finally { console.error = original; } +}); + +test('registry: settings come from the schema, are stored under the module\'s namespace and reach the running feature', () => { + const env = page(); + const registry = registryFor(env); + const applied: unknown[] = []; + const module: FeatureModule = { + id: 'navigation.focusMode', + storage: 'focus-mode', + settings: [{ key: 'enabled', type: 'toggle', default: true, label: 'enabled' }, { key: 'trends', type: 'toggle', default: true, label: 'trends' }], + start(ctx) { + applied.push(ctx.settings.get()); + ctx.settings.onChange(values => applied.push(values)); + ctx.command({ id: 'focusMode.toggle', title: 'Toggle Focus Mode', run: () => { ctx.settings.set({ enabled: !ctx.settings.get().enabled }); } }); + }, + }; + env.store.set('demo-plugin:focus-mode:settings', JSON.stringify({ enabled: true, trends: false, gone: 1 })); + registry.define(module); + assert.throws(() => registryFor(env).define({ id: 'navigation.keys', settings: [{ key: 'a', type: 'toggle', default: true, label: 'a' }], start() {} }), /the table's "settings" and the module's schema disagree/); + registry.setFlags({ 'navigation.focusMode': true }); + assert.deepEqual(applied, [{ enabled: true, trends: false }], 'an old plugin\'s stored settings are read as they are'); + // The area got its one settings command next to the feature's own; both belong to the area's owner. + assert.deepEqual(env.api.commands.list().map(command => command.id).sort(), ['wb-navigation-plus.plugin.js:focusMode.toggle', 'wb-navigation-plus.plugin.js:settings']); + assert.equal(env.api.commands.list().find(command => command.id.endsWith(':settings'))!.title, 'Navigation+ settings'); + env.api.commands.run('wb-navigation-plus.plugin.js:focusMode.toggle'); + assert.deepEqual(applied.at(-1), { enabled: false, trends: false }); + assert.equal(env.store.get('demo-plugin:focus-mode:settings'), '{"enabled":false,"trends":false}'); + registry.setFlags({}); + assert.deepEqual(env.api.commands.list(), [], 'commands go with the feature'); + registry.dispose(); +}); + +test(`registry: an area registers at most ${AREA_COMMAND_BUDGET} palette commands`, () => { + const env = page(); + const errors: unknown[] = []; + const original = console.error; + console.error = (...args: unknown[]) => { errors.push(args[1]); }; + try { + const registry = registryFor(env); + // Navigation+ has a feature with settings, so one of the five is kept for its settings command. + registry.define({ id: 'navigation.keys', start(ctx) { for (let n = 0; n < AREA_COMMAND_BUDGET; n += 1) ctx.command({ id: `keys.${n}`, title: `Key ${n}`, run() {} }); } }); + registry.setFlags({ 'navigation.keys': true }); + assert.match(String(errors[0]), /at most 5 palette commands per area/); + assert.deepEqual(registry.active(), [], 'the feature that went over the budget does not run'); + assert.deepEqual(env.api.commands.list(), []); + registry.dispose(); + } finally { console.error = original; } +}); + +test(`registry: a probe that matches nothing ${PROBE_STRIKES} visits in a row pauses that one feature; a hotfix selector or kill flag applies`, () => { + const env = page(); + const timers = fakeTimers(); + let hotfix: HotfixData = {}; + const warnings: unknown[] = []; + const original = console.warn; + console.warn = (...args: unknown[]) => { warnings.push(args[0]); }; + try { + const registry = registryFor(env, { timers, hotfix: () => hotfix, surfaces: () => ['timeline'] }); + const used: string[] = []; + registry.define({ id: 'hideTrends', probes: { module: '[data-testid="trend"]', label: { selector: '[aria-label="Trending"]', english: true } }, start(ctx) { used.push(ctx.selector('module')); } }); + registry.define({ id: 'navigation.keys', start() {} }); + env.matches.set('[aria-label="Trending"]', [{}]); + registry.setFlags({ hideTrends: true, 'navigation.keys': true }); + const visit = () => { env.go(env.location.pathname === '/home' ? '/explore' : '/home'); timers.advance(500 + 3000); }; + + timers.advance(3500); + assert.deepEqual(registry.health(), [], 'one miss is not a verdict'); + visit(); + // The selector comes back for a visit: the count starts over. + env.matches.set('[data-testid="trend"]', [{}]); + visit(); + env.matches.delete('[data-testid="trend"]'); + visit(); + visit(); + assert.deepEqual(registry.active().sort(), ['hideTrends', 'navigation.keys']); + visit(); + assert.deepEqual(registry.active(), ['navigation.keys'], 'the feature paused itself; the rest of the area runs'); + assert.deepEqual(registry.health(), [{ id: 'hideTrends', area: 'navigation', state: 'paused', probes: ['module'] }]); + assert.match(String(warnings[0]), /\[Demo\] hideTrends paused: nothing matches module/); + registry.setFlags({ hideTrends: true, 'navigation.keys': true }); + assert.deepEqual(registry.active(), ['navigation.keys'], 'paused for the session'); + assert.equal(timers.pending(), 0, 'no timer left behind'); + registry.dispose(); + + // A signed hotfix replaces the selector, or switches the feature off. + hotfix = { selectors: { 'hideTrends.module': '[data-testid="trendV2"]' } }; + const patched = registryFor(env, { timers, hotfix: () => hotfix, surfaces: () => ['timeline'] }); + patched.define({ id: 'hideTrends', probes: { module: '[data-testid="trend"]' }, start(ctx) { used.push(ctx.selector('module')); } }); + patched.setFlags({ hideTrends: true }); + assert.deepEqual(used, ['[data-testid="trend"]', '[data-testid="trendV2"]']); + hotfix = { flags: { hideTrends: false } }; + patched.refresh(); + assert.deepEqual(patched.active(), []); + patched.dispose(); + } finally { console.warn = original; } +}); + +test('registry: a probe that reads an English label waits for an English page instead of counting misses', () => { + const env = page(); + const timers = fakeTimers(); + (env.doc.documentElement as { getAttribute(): string }).getAttribute = () => 'tr'; + const registry = registryFor(env, { timers, surfaces: () => ['timeline'] }); + registry.define({ id: 'hideTrends', probes: { label: { selector: '[aria-label="Trending"]', english: true } }, start() {} }); + registry.setFlags({ hideTrends: true }); + for (let n = 0; n < 5; n += 1) { env.go(n % 2 ? '/home' : '/explore'); timers.advance(3500); } + assert.deepEqual(registry.active(), ['hideTrends']); + assert.deepEqual(registry.health(), [{ id: 'hideTrends', area: 'navigation', state: 'needs-english', probes: ['label'] }]); + registry.dispose(); +}); + +test('observeSelector: heavy pages skip observers that ask for it', () => { + const env = page(); + const seen: string[] = []; + env.matches.set('article', [{}]); + env.location.pathname = '/home'; + const stop = observeSelector(env.win as unknown as DomWindow, 'article', () => seen.push('x'), { offOnHeavy: true }); + assert.deepEqual(seen, ['x']); + stop(); + stop(); +}); diff --git a/packages/runtime/tests/siteRuntime.test.ts b/packages/runtime/tests/siteRuntime.test.ts index f48028a..5751dc8 100644 --- a/packages/runtime/tests/siteRuntime.test.ts +++ b/packages/runtime/tests/siteRuntime.test.ts @@ -41,7 +41,7 @@ test('feature flags: parts install on enable and dispose on disable, in order, a assert.ok(flags.installed('gate') && !flags.installed('pill')); flags.apply({ gate: false, css: false }); assert.deepEqual(log, ['+gate', '-gate']); - assert.deepEqual(applied, [{ gate: false, css: false }]); + assert.deepEqual(applied, [{ gate: false, pill: false, css: false }], 'the full map: a flag the delivery does not name is at its default'); flags.apply({ gate: true, pill: true }); assert.deepEqual(log, ['+gate', '-gate', '+gate']); assert.equal(flags.installed('pill'), false); @@ -57,13 +57,16 @@ test('feature flags: a deck column overrides global flags; dropped overrides go const flags = createFeatureFlags({ defaults: { gate: true, pill: false, css: true }, label: 'Demo', installers: [], apply: config => applied.push(config) }); flags.apply({ pill: true }); flags.setColumnFlags({ pill: false, css: false, unknown: true, gate: 'yes' }); - assert.deepEqual(applied.at(-1), { pill: false, css: false }, 'only known booleans; the column wins'); - flags.apply({ css: true }); - assert.deepEqual(applied.at(-1), { pill: false, css: false }, 'a global change does not undo the column'); + assert.deepEqual(applied.at(-1), { gate: true, pill: false, css: false }, 'only known booleans; the column wins'); + flags.apply({ pill: true, css: true }); + assert.deepEqual(applied.at(-1), { gate: true, pill: false, css: false }, 'a global change does not undo the column'); flags.setColumnFlags({ pill: false }); - assert.deepEqual(applied.at(-1), { pill: false, css: true }, 'css is the global value again'); + assert.deepEqual(applied.at(-1), { gate: true, pill: false, css: true }, 'css is the global value again'); flags.setColumnFlags(null); - assert.deepEqual(applied.at(-1), { pill: true, css: true }, 'an ordinary tab again: the global flags'); + assert.deepEqual(applied.at(-1), { gate: true, pill: true, css: true }, 'an ordinary tab again: the global flags'); + flags.apply({}); + assert.deepEqual(applied.at(-1), { gate: true, pill: false, css: true }, 'a delivery is the whole state: what it does not name is at its default'); + assert.deepEqual(flags.current(), { gate: true, pill: false, css: true }); const before = applied.length; flags.setColumnFlags(undefined); assert.equal(applied.length, before, 'nothing to change'); @@ -75,9 +78,16 @@ test('feature flags: a deck column overrides global flags; dropped overrides go waiting.setColumnFlags({ css: false }); assert.deepEqual(late, []); waiting.apply({ pill: true }); - assert.deepEqual(late.at(-1), { pill: true, css: false }, 'recorded at once: a global delivery already respects it'); + assert.deepEqual(late.at(-1), { gate: true, pill: true, css: false }, 'recorded at once: a global delivery already respects it'); listeners[0]!(); - assert.deepEqual(late.at(-1), { pill: true, css: false }); + assert.deepEqual(late.at(-1), { gate: true, pill: true, css: false }); + // Ownership: `resolve` decides what runs; a column's own choice still wins. + const owned: Array> = []; + const gated = createFeatureFlags({ defaults: { gate: true, pill: false, css: true }, label: 'Demo', installers: [], apply: config => owned.push(config), resolve: all => (all.gate ? all : { ...all, css: false }) }); + gated.apply({ gate: false }); + assert.deepEqual(owned.at(-1), { gate: false, pill: false, css: false }, 'the owner is off, so what it owns is off'); + gated.setColumnFlags({ css: true }); + assert.deepEqual(owned.at(-1), { gate: false, pill: false, css: true }); }); function runtimeWindow(queued: Record = {}) { From e7e744f66d81d7908581846df4a3fd7227692eea Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 30 Sep 2026 18:34:13 +0700 Subject: [PATCH 03/72] Host: 256 feature flags, the onboarding mode (mode_get/mode_set, shell-only), and the one-time move of replaced plugin files to feature flags - settings: MAX_FEATURES 64 -> 256 (an older app's whole-map backup still validates) - modes: ModeState {mode, onboarded, existing} in modes.json; existing is decided natively on the first start - plugins::migrate: PluginHost.superseded (file -> flag); enabled and as shipped -> flag on and the file goes; edited -> kept, flag left off; marker written last, every step repeatable; map_backup for imported enabled lists - a superseded file is never written again by install_bundled - create-waybetter: the host command list and PluginHost.superseded Co-Authored-By: Claude Opus 5.5 --- crates/waybetter-host/src/app.rs | 48 ++- crates/waybetter-host/src/commands.rs | 2 + crates/waybetter-host/src/lib.rs | 3 + crates/waybetter-host/src/modes.rs | 85 +++++ crates/waybetter-host/src/plugins.rs | 7 +- crates/waybetter-host/src/plugins/migrate.rs | 316 +++++++++++++++++++ crates/waybetter-host/src/settings.rs | 17 +- crates/waybetter-host/src/store/install.rs | 1 + packages/create-waybetter/src/app.js | 4 +- 9 files changed, 477 insertions(+), 6 deletions(-) create mode 100644 crates/waybetter-host/src/modes.rs create mode 100644 crates/waybetter-host/src/plugins/migrate.rs diff --git a/crates/waybetter-host/src/app.rs b/crates/waybetter-host/src/app.rs index a0ffc15..9b223f4 100644 --- a/crates/waybetter-host/src/app.rs +++ b/crates/waybetter-host/src/app.rs @@ -22,6 +22,7 @@ use crate::{ host::{self, emit_shell, emit_tab_state, read_json, shell_only, site_tab_only, tab_only, tab_webview, write_json}, i18n::{self, NativeStrings}, layout, + modes::{ModeState, MODES_FILE}, plugins::{self, PluginHost, PluginStore, ScriptPlugin}, policy, profiles::{self, AccountSeen, ProfileSettings}, @@ -203,6 +204,8 @@ pub struct PageState { /// A JSON object of booleans ([`settings::validate_features`]). pub features: serde_json::Value, pub settings: ShellSettings, + /// The onboarding mode the owner started from and whether the first-run screen was answered. + pub modes: ModeState, } struct Profiles(Mutex); @@ -715,6 +718,25 @@ async fn features_set(webview: Webview, app: AppHandle, features: serde_json::Ma set_features(&app, features) } +/// The onboarding mode: what was chosen, whether the first-run screen was answered, and whether +/// this app was set up before modes existed. +#[tauri::command] +async fn mode_get(webview: Webview, app: AppHandle) -> Result { + shell_only(&webview)?; + Ok(page(&app)?.modes.clone()) +} + +/// Remembers the chosen mode (or none) and that the first-run screen was answered. The preset's +/// flags are the shell's to apply (`features_set`); this only records the choice. +#[tauri::command] +async fn mode_set(webview: Webview, app: AppHandle, mode: Option, onboarded: bool) -> Result { + shell_only(&webview)?; + let next = page(&app)?.modes.chosen(mode, onboarded)?; + write_json(&app, MODES_FILE, &next)?; + page(&app)?.modes = next.clone(); + Ok(next) +} + #[tauri::command] async fn settings_get(webview: Webview, app: AppHandle) -> Result { shell_only(&webview)?; @@ -952,6 +974,8 @@ fn host_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 's custom_css_set, features_get, features_set, + mode_get, + mode_set, settings_get, settings_set, tab_shortcut, @@ -1019,6 +1043,8 @@ impl App { } let directory = tauri_app.path().app_data_dir()?; std::fs::create_dir_all(&directory)?; + // Someone set this app up before (read before anything below writes a file). + let existing = [PROFILES_FILE, SETTINGS_FILE, FEATURES_FILE, PLUGINS_DIR].iter().any(|name| directory.join(name).exists()); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; @@ -1042,10 +1068,28 @@ impl App { let settings = read_json::(&handle, SETTINGS_FILE) .and_then(|value| ShellSettings::from_value(value, &home).ok()) .unwrap_or_else(|| ShellSettings::defaults(&home)); - let features = read_json::(&handle, FEATURES_FILE) + let mut features = read_json::(&handle, FEATURES_FILE) .filter(serde_json::Value::is_object) .unwrap_or_else(|| serde_json::json!({})); - tauri_app.manage(Page(Mutex::new(PageState { plugins, features, settings }))); + // Plugin files the app turned into features: what was enabled becomes its flag, once + // (plugins::migrate). The flags are saved before any file is touched. + let migrated = plugins.migrate_superseded(config.plugins.superseded, |flags| { + let Some(map) = features.as_object_mut().filter(|_| !flags.is_empty()) else { return Ok(()) }; + for flag in flags { + map.insert(flag.clone(), serde_json::Value::Bool(true)); + } + settings::validate_features(map)?; + write_json(&handle, FEATURES_FILE, &*map) + }); + if let Err(error) = migrated { + eprintln!("{}: {error}", config.title); + } + let modes = read_json::(&handle, MODES_FILE).and_then(|state| state.validated().ok()).unwrap_or_else(|| { + let state = ModeState::first_run(existing); + let _ = write_json(&handle, MODES_FILE, &state); + state + }); + tauri_app.manage(Page(Mutex::new(PageState { plugins, features, settings, modes }))); tauri_app.manage(Host { config, hooks }); if let Some(setup) = setup { setup(&handle)?; diff --git a/crates/waybetter-host/src/commands.rs b/crates/waybetter-host/src/commands.rs index 7cfbf5a..cd744bb 100644 --- a/crates/waybetter-host/src/commands.rs +++ b/crates/waybetter-host/src/commands.rs @@ -28,6 +28,8 @@ pub const SHELL: &[&str] = &[ "custom_css_set", "features_get", "features_set", + "mode_get", + "mode_set", "settings_get", "settings_set", ]; diff --git a/crates/waybetter-host/src/lib.rs b/crates/waybetter-host/src/lib.rs index b940963..2db229c 100644 --- a/crates/waybetter-host/src/lib.rs +++ b/crates/waybetter-host/src/lib.rs @@ -10,6 +10,7 @@ //! - [`policy`]: webview labels, origin checks and the tab rectangle clamp (security boundary). //! - [`profiles`]: account profiles, one WebView data directory each, with the account seen inside. //! - [`plugins`]: owner-installed `*.plugin.js` files, custom CSS and bundled-plugin upgrades; +//! [`plugins::migrate`]: the one-time move of replaced plugin files to feature flags; //! [`plugins::commands`]: the palette commands site tabs report and the script that runs one. //! - [`hotfix`]: the signed, data-only hotfix channel. //! - [`update`]: silent-update scheduling and the crash handshake. @@ -25,6 +26,7 @@ //! - [`devmode`]: developer mode's debounced watcher of plugins, custom CSS and a theme file. //! - [`settings`]: the shell's settings (home page, where links open, session restore) and the page's //! feature flags, as validated data and the scripts that hand them to site tabs. +//! - [`modes`]: the onboarding mode the owner started from (the presets are the app's feature table). //! - [`alerts`]: local keyword alerts (keywords, snippets, per-item/per-keyword rate limits). //! - [`media`]: gallery folders (path containment) and the opt-in clipboard history (private copies skipped). //! - [`gfonts`]: self-hosted Google Fonts: CSS parsing, URL/woff2 checks, the cache format, the page script; @@ -54,6 +56,7 @@ pub mod hotfix; pub mod i18n; pub mod layout; pub mod media; +pub mod modes; pub mod plugins; pub mod policy; pub mod profiles; diff --git a/crates/waybetter-host/src/modes.rs b/crates/waybetter-host/src/modes.rs new file mode 100644 index 0000000..5dccdf0 --- /dev/null +++ b/crates/waybetter-host/src/modes.rs @@ -0,0 +1,85 @@ +//! The onboarding mode: which preset (Basic / Advanced / Power User, whatever the app defines) the +//! owner started from, and whether the first-run screen was answered. A mode is a starting point: +//! the presets themselves are the app's (its feature table) and are applied by the shell through +//! `features_set`; native code only remembers the choice (`modes.json`), so the screen shows once. +//! +//! `existing` is decided natively, once, on the first start of a version that has modes: an app +//! data folder that already held settings belongs to someone who set the app up before. They keep +//! exactly what they have, and the screen they see can be dismissed without choosing. + +use serde::{Deserialize, Serialize}; + +pub const MODES_FILE: &str = "modes.json"; +const MAX_MODE_ID: usize = 32; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct ModeState { + /// The mode chosen last; `None` = never chosen (the app's defaults, or an earlier setup). + pub mode: Option, + /// The first-run screen was answered or dismissed. + pub onboarded: bool, + /// The app was set up before modes existed. + pub existing: bool, +} + +/// A mode id: lowercase letters, digits and `-`, starting with a letter, at most 32 characters. +pub fn valid_mode(id: &str) -> bool { + !id.is_empty() + && id.len() <= MAX_MODE_ID + && id.as_bytes()[0].is_ascii_lowercase() + && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') +} + +impl ModeState { + /// The state on the first start: nothing chosen, the screen still to be shown. + pub fn first_run(existing: bool) -> Self { + Self { mode: None, onboarded: false, existing } + } + + pub fn validated(self) -> Result { + if self.mode.as_deref().is_some_and(|mode| !valid_mode(mode)) { + return Err("VALIDATION: invalid mode".into()); + } + Ok(self) + } + + /// What the shell may change: the chosen mode and that the screen was answered. `existing` + /// stays what native code decided. + pub fn chosen(&self, mode: Option, onboarded: bool) -> Result { + Self { mode, onboarded, existing: self.existing }.validated() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn mode_ids_are_short_plain_words() { + for good in ["basic", "advanced", "power-user", "m2"] { + assert!(valid_mode(good), "{good}"); + } + for bad in ["", "Basic", "2fast", "a b", "a/b", "../x", &"a".repeat(33)] { + assert!(!valid_mode(bad), "{bad}"); + } + } + + #[test] + fn the_shell_chooses_a_mode_but_never_what_kind_of_install_this_is() { + let fresh = ModeState::first_run(false); + assert_eq!(fresh, ModeState { mode: None, onboarded: false, existing: false }); + let existing = ModeState::first_run(true); + let dismissed = existing.chosen(None, true).unwrap(); + assert_eq!(dismissed, ModeState { mode: None, onboarded: true, existing: true }, "dismissed without choosing: nothing else changes"); + let chosen = dismissed.chosen(Some("power".into()), true).unwrap(); + assert_eq!(chosen.mode.as_deref(), Some("power")); + assert!(chosen.existing); + assert!(existing.chosen(Some(" \\ ${x} `y`")).unwrap()); + assert!(script.contains(r#"window.find("it's \"quoted\" \\ ${x} `y`",false,false,true"#), "{script}"); + assert!(script.contains("removeAllRanges"), "a new query starts from the top"); + let next = fallback_script(&request("next", Some("a")).unwrap()); + assert!(next.contains(r#"window.find("a",false,false,true"#) && !next.contains("removeAllRanges")); + assert!(fallback_script(&request("previous", Some("a")).unwrap()).contains(r#"window.find("a",false,true,true"#)); + // Stop (and a step without a query) only clears the selection. + for request in [request("stop", None).unwrap(), request("next", None).unwrap()] { + let script = fallback_script(&request); + assert!(script.contains("removeAllRanges") && !script.contains("window.find"), "{script}"); + } + // Nothing leaves the page or stays in it: no network, storage, invoke or DOM writes. + for script in [script, next] { + for forbidden in ["fetch", "XMLHttpRequest", "localStorage", "sessionStorage", "invoke", "postMessage", "innerHTML", "document.cookie", "eval("] { + assert!(!script.contains(forbidden), "{forbidden} in {script}"); + } + } + } + + #[test] + fn counts_are_numbers_about_the_tab() { + let state = FindState { id: "t1".into(), count: 17, index: 2 }; + assert_eq!(serde_json::to_string(&state).unwrap(), r#"{"id":"t1","count":17,"index":2}"#); + } +} diff --git a/crates/waybetter-host/src/host.rs b/crates/waybetter-host/src/host.rs index 6e79c5e..3f7eb67 100644 --- a/crates/waybetter-host/src/host.rs +++ b/crates/waybetter-host/src/host.rs @@ -145,6 +145,115 @@ pub fn forget_tab_zoom(app: &AppHandle, id: &str) { } } +/// `tab_find`: searches tab `id`'s page ([`crate::find`]). The engine's own find where this build +/// can drive it (WebView2's `ICoreWebView2Find`, which reports counts through `tab-find` events); +/// otherwise the evaluated `window.find` fallback. The query is kept nowhere. +pub fn tab_find(app: &AppHandle, id: &str, action: &str, query: Option<&str>) -> Result<(), String> { + if !policy::valid_tab_id(id) { + return Err("VALIDATION: invalid tab id".into()); + } + let request = crate::find::request(action, query)?; + let tab = tab_webview(app, id).ok_or("TAB: not found")?; + #[cfg(windows)] + { + let fallback = tab.clone(); + let (app, id) = (app.clone(), id.to_owned()); + tab.with_webview(move |platform| { + // The engine has no find interface (an older WebView2 Runtime): the evaluated fallback. + if !find_windows::run(&app, &platform, &id, &request) { + let _ = fallback.eval(crate::find::fallback_script(&request)); + } + }) + .map_err(|error| format!("TAB: {error}")) + } + #[cfg(not(windows))] + { + tab.eval(crate::find::fallback_script(&request)).map_err(|error| format!("TAB: {error}")) + } +} + +/// WebView2's own find (`ICoreWebView2Find`, WebView2 Runtime with `ICoreWebView2_28`): the find +/// session, its highlights and its counts are the engine's; its own find bar stays hidden. +#[cfg(windows)] +mod find_windows { + use super::{emit_shell, AppHandle, Runtime}; + use crate::find::{FindAction, FindRequest, FindState, EVENT_TAB_FIND}; + use std::collections::HashSet; + use std::sync::{Mutex, OnceLock}; + use webview2_com::Microsoft::Web::WebView2::Win32::{ICoreWebView2Environment15, ICoreWebView2Find, ICoreWebView2_28}; + use webview2_com::{FindActiveMatchIndexChangedEventHandler, FindMatchCountChangedEventHandler, FindStartCompletedHandler}; + use windows::core::{Interface, HSTRING}; + + /// Tab webviews whose find object already reports its counts (one pair of handlers each). + fn watched() -> std::sync::MutexGuard<'static, HashSet> { + static WATCHED: OnceLock>> = OnceLock::new(); + WATCHED.get_or_init(Default::default).lock().unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + /// The tab's webview is gone: a new one under the same id registers its own handlers. + pub(super) fn forget(id: &str) { + watched().remove(id); + } + + fn report(app: &AppHandle, id: &str, find: &ICoreWebView2Find) { + let (mut count, mut index) = (0i32, -1i32); + // SAFETY: COM property reads on the live find object, on the main thread. + unsafe { + let _ = find.MatchCount(&mut count); + let _ = find.ActiveMatchIndex(&mut index); + } + emit_shell(app, EVENT_TAB_FIND, FindState { id: id.to_owned(), count, index }); + } + + /// Runs `request` with the engine's find on the main thread; false when this runtime has none. + pub(super) fn run(app: &AppHandle, platform: &tauri::webview::PlatformWebview, id: &str, request: &FindRequest) -> bool { + // SAFETY: COM calls on this webview's live controller and environment, on the main thread + // (with_webview runs the closure there; the handlers run there too). + unsafe { + let Ok(core) = platform.controller().CoreWebView2() else { return false }; + let (Ok(core), Ok(environment)) = (core.cast::(), platform.environment().cast::()) else { return false }; + let Ok(find) = core.Find() else { return false }; + if watched().insert(id.to_owned()) { + let mut token = 0i64; + let (count_app, count_id) = (app.clone(), id.to_owned()); + let counted = FindMatchCountChangedEventHandler::create(Box::new(move |sender, _| { + if let Some(find) = sender { report(&count_app, &count_id, &find); } + Ok(()) + })); + let _ = find.add_MatchCountChanged(&counted, &mut token); + let (index_app, index_id) = (app.clone(), id.to_owned()); + let moved = FindActiveMatchIndexChangedEventHandler::create(Box::new(move |sender, _| { + if let Some(find) = sender { report(&index_app, &index_id, &find); } + Ok(()) + })); + let _ = find.add_ActiveMatchIndexChanged(&moved, &mut token); + } + match (request.action, request.query.as_deref()) { + (FindAction::Start, Some(query)) => { + let Ok(options) = environment.CreateFindOptions() else { return false }; + let _ = options.SetFindTerm(&HSTRING::from(query)); + let _ = options.SetSuppressDefaultFindDialog(true); + let _ = options.SetShouldHighlightAllMatches(true); + let _ = options.SetIsCaseSensitive(false); + let _ = options.SetShouldMatchWord(false); + // A new query is a new session, from the first match. + let _ = find.Stop(); + let (done_app, done_id, done_find) = (app.clone(), id.to_owned(), find.clone()); + let started = FindStartCompletedHandler::create(Box::new(move |_| { + report(&done_app, &done_id, &done_find); + Ok(()) + })); + let _ = find.Start(&options, &started); + } + (FindAction::Next, _) => { let _ = find.FindNext(); } + (FindAction::Previous, _) => { let _ = find.FindPrevious(); } + (FindAction::Stop, _) | (FindAction::Start, None) => { let _ = find.Stop(); } + } + } + true + } +} + /// A browser shortcut pressed inside tab `id`, forwarded to the shell (`tab-shortcut`). pub fn forward_shortcut(app: &AppHandle, id: String, shortcut: String) -> Result<(), String> { if !tabs::valid_shortcut(&shortcut) { @@ -803,6 +912,11 @@ pub fn forget_tab(app: &AppHandle, label: &str) { } #[cfg(not(windows))] let _ = app; + // Its find session went with the webview: a new one under the same id registers its own handlers. + #[cfg(windows)] + if let Some(id) = policy::tab_id(label) { + find_windows::forget(id); + } placements().forget(label); } diff --git a/crates/waybetter-host/tab-bridge.js b/crates/waybetter-host/tab-bridge.js index 2d19116..355c52a 100644 --- a/crates/waybetter-host/tab-bridge.js +++ b/crates/waybetter-host/tab-bridge.js @@ -85,6 +85,8 @@ if (key === 'w') return 'close-tab'; if (key === 'l') return 'focus-address'; if (key === 'k' && !event.shiftKey) return 'command-palette'; + // Find in page is the shell's bar (`tab_find`): this tab only says the keys were pressed. + if (key === 'f' && !event.shiftKey) return 'find'; if (key === 'tab') return event.shiftKey ? 'prev-tab' : 'next-tab'; if (key === 'r') return event.shiftKey ? 'hard-reload' : 'reload'; // Physical key: layouts like Turkish-Q produce other characters on this key. diff --git a/packages/create-waybetter/src/app.js b/packages/create-waybetter/src/app.js index d1e92e8..8fd0fc2 100644 --- a/packages/create-waybetter/src/app.js +++ b/packages/create-waybetter/src/app.js @@ -151,7 +151,7 @@ const COMMANDS = { */ export const HOST_COMMANDS = { shell: [ - 'tabs_sync', 'tab_navigate', 'tab_action', 'tab_zoom', 'open_external_url', 'shell_focus', 'shell_ready', 'tab_still_ready', 'shell_raise', 'window_system_menu', + 'tabs_sync', 'tab_navigate', 'tab_action', 'tab_zoom', 'tab_find', 'open_external_url', 'shell_focus', 'shell_ready', 'tab_still_ready', 'shell_raise', 'window_system_menu', 'profiles_get', 'profiles_set', 'i18n_get', 'i18n_set', 'plugins_list', 'plugin_set_enabled', 'plugins_open_folder', 'custom_css_get', 'custom_css_set', 'features_get', 'features_set', 'mode_get', 'mode_set', 'settings_get', 'settings_set', ], diff --git a/packages/shell/src/frame/AppMenu.tsx b/packages/shell/src/frame/AppMenu.tsx index a12e184..180884d 100644 --- a/packages/shell/src/frame/AppMenu.tsx +++ b/packages/shell/src/frame/AppMenu.tsx @@ -265,6 +265,7 @@ export function AppMenu() { case 'plugins': return item(id, section(t('wb.panel.section.plugins')), 'plug', { run: () => shell.openPanelSection('plugins') }); case 'store': return item(id, section(t('wb.panel.section.store')), 'bag', { run: () => shell.openPanelSection('store') }); case 'workspaces': return item(id, t('wb.ws.title'), 'layout', { submenu: true, hint: workspaces.store.items.find(entry => entry.id === workspaces.active)?.name }); + case 'find': return item(id, menuText('find'), 'search', { shortcut: 'Ctrl+F', disabled: !active || !isWeb(active), run: () => shell.shortcut('find') }); case 'shortcuts': return item(id, menuText('shortcuts'), 'keyboard', { run: () => (menu.shortcuts ? menu.shortcuts() : shell.shortcut('command-palette')) }); case 'palette': return item(id, menuText('palette'), 'command', { shortcut: 'Ctrl+K', run: () => shell.shortcut('command-palette') }); case 'developer': return item(id, menuText('developer'), 'code', { submenu: true }); @@ -342,7 +343,7 @@ export function AppMenu() { const groups = menu.groups ?? DEFAULT_MENU; const env: MenuEnv = { decks: !!config.deck, languages: !!menu.languages, themes: !!config.themes, modes: modeList.length > 0, - zoom: hasFeature('zoom'), store: hasFeature('store'), workspaces: hasFeature('workspaces'), developer: hasFeature('developer'), updates: hasFeature('updates'), + zoom: hasFeature('zoom'), find: hasFeature('find'), store: hasFeature('store'), workspaces: hasFeature('workspaces'), developer: hasFeature('developer'), updates: hasFeature('updates'), }; const rootRows = () => joinGroups(planMenu(groups, env).map(group => group.flatMap(entry => (typeof entry === 'string' ? [builtin(entry)] : specRows([entry]))))); const labelOf = (id: string, rows: MenuRow[]) => rows.find((row): row is MenuItemRow => row.kind === 'item' && row.id === id)?.label ?? ''; diff --git a/packages/shell/src/frame/FindBar.tsx b/packages/shell/src/frame/FindBar.tsx new file mode 100644 index 0000000..c406896 --- /dev/null +++ b/packages/shell/src/frame/FindBar.tsx @@ -0,0 +1,92 @@ +// Find in page: the shell's find bar for one pane. It takes the address field's place in that +// pane's toolbar while it is open (so the page under it does not move and, in split view, the bar +// is plainly the searched pane's). Native code does the searching (`tab_find`, shell-only): the +// engine's own find where the build can drive it (WebView2: highlights and a match count, which +// arrive as `tab-find` events), else the engine's `window.find` evaluated by native code (next and +// previous work, no count). Only what the page has rendered can be found, as in a browser: a +// virtualized list (X's timeline) holds the posts near the viewport, not the whole feed. +// +// The query lives in this component's state while the bar is open and nowhere else: it is not +// saved, logged or put in a URL, and closing the bar clears the engine's highlights. +// Keys: Enter / F3 next, Shift+Enter / Shift+F3 previous, Esc closes and gives the page the focus. + +import { useEffect, useRef, useState } from 'react'; +import { invoke, listen } from './bridge.ts'; +import { useT } from './hooks.ts'; +import { formatNumber } from './i18n.ts'; +import { Icon } from './icons.tsx'; +import { findLabel, menuText } from './menuModel.ts'; +import { tabAction } from './state.ts'; +import './findBar.css'; + +/** Opens (or focuses) the find bar of web tab `id`. */ +export const openFind = (id: string) => window.dispatchEvent(new CustomEvent('bt-find', { detail: id })); +/** The next (`1`) or previous (`-1`) match in tab `id`, when its find bar is open (F3 anywhere in the shell). */ +export const stepFind = (id: string, direction: 1 | -1) => window.dispatchEvent(new CustomEvent('bt-find-step', { detail: { id, direction } })); + +const find = (id: string, action: 'start' | 'next' | 'previous' | 'stop', query?: string) => + invoke('tab_find', { id, action, ...(query ? { query } : {}) }).catch(() => {}); + +export function FindBar({ tabId, url, onClose }: { tabId: string; url: string; onClose(): void }) { + useT(); + const [query, setQuery] = useState(''); + // What the engine reported for the query on screen (null: nothing yet, or an engine that does not count). + const [counts, setCounts] = useState<{ count: number; index: number } | null>(null); + const input = useRef(null); + const live = useRef(query); + live.current = query; + + const close = () => { + onClose(); + // The page gets the keyboard back. + void tabAction(tabId, 'focus'); + }; + const step = (direction: 1 | -1) => { if (live.current) void find(tabId, direction > 0 ? 'next' : 'previous', live.current); }; + + // The shell takes the keyboard (Ctrl+F was pressed in the page); closing clears the highlights. + useEffect(() => { + invoke('shell_focus').catch(() => {}); + input.current?.focus(); + const again = (event: Event) => { if ((event as CustomEvent).detail === tabId) { input.current?.focus(); input.current?.select(); } }; + const onStep = (event: Event) => { const detail = (event as CustomEvent<{ id: string; direction: 1 | -1 }>).detail; if (detail.id === tabId) step(detail.direction); }; + window.addEventListener('bt-find', again); + window.addEventListener('bt-find-step', onStep); + let disposed = false; + let unlisten: (() => void) | undefined; + listen<{ id: string; count: number; index: number }>('tab-find', ({ payload }) => { + if (payload.id === tabId && live.current) setCounts({ count: payload.count, index: payload.index }); + }).then(dispose => { if (disposed) dispose(); else unlisten = dispose; }).catch(() => {}); + return () => { + disposed = true; + unlisten?.(); + window.removeEventListener('bt-find', again); + window.removeEventListener('bt-find-step', onStep); + void find(tabId, 'stop'); + }; + }, [tabId]); + + // A new query (or a new page under the same query) starts a new search, a beat after the last key. + useEffect(() => { + setCounts(null); + if (!query) { void find(tabId, 'stop'); return; } + const timer = setTimeout(() => void find(tabId, 'start', query), 140); + return () => clearTimeout(timer); + }, [query, url, tabId]); + + const status = query && counts ? findLabel(counts, value => formatNumber(value)) : ''; + return
+ + setQuery(event.target.value.replace(/[\u0000-\u001f\u007f]/g, ''))} + onKeyDown={event => { + if (event.key === 'Enter' || event.key === 'F3') { event.preventDefault(); event.stopPropagation(); step(event.shiftKey ? -1 : 1); } + if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close(); } + }}/> + {status} + + + +
; +} diff --git a/packages/shell/src/frame/Shell.tsx b/packages/shell/src/frame/Shell.tsx index 80dc54a..42e90b8 100644 --- a/packages/shell/src/frame/Shell.tsx +++ b/packages/shell/src/frame/Shell.tsx @@ -20,6 +20,7 @@ import { openAppMenu } from './AppMenu.tsx'; import { invoke, listen } from './bridge.ts'; import { CommandPalette } from './CommandPalette.tsx'; import { DeckTabBadge, DeckView, focusColumn, runDeckCommand } from './DeckView.tsx'; +import { openFind, stepFind } from './FindBar.tsx'; import { columnSourceUrl, createDeck, deckById, decks, findColumnTab, loadDecks, setRuntime } from './deckStore.ts'; import { installDevHost } from './devHost.ts'; import { useProfiles, useT } from './hooks.ts'; @@ -264,6 +265,7 @@ function runPalette(action: PaletteAction) { case 'plugin-command': runPluginCommand(action.tab, action.command); break; case 'workspace': void restoreWorkspace(action.id); break; case 'workspace-save': openWorkspaceSave(); break; + case 'find': runShortcut('find'); break; case 'menu': openAppMenu({ keyboard: true }); break; } } @@ -290,6 +292,9 @@ function runShortcut(shortcut: string, id?: string) { const panel = id === undefined ? api.activePanel : api.getPanel(id); switch (shortcut) { case 'new-tab': addStart(); break; + // Find in page: the find bar of that tab (the one the keys were pressed in, else the one in front). + case 'find': if (panel && isWeb(panel) && hasFeature('find')) { panel.api.setActive(); openFind(panel.id); } break; + case 'find-next': case 'find-previous': if (panel && isWeb(panel)) stepFind(panel.id, shortcut === 'find-next' ? 1 : -1); break; case 'close-tab': if (panel) closeTab(panel); break; case 'reopen-tab': { const tab = shell.closed.pop(); if (tab) addWeb(tab.url, undefined, true, tab.profile); break; } case 'focus-address': if (panel && (isWeb(panel) || (panel.params as TabParams).kind === 'start')) focusAddress(panel.id); break; @@ -340,6 +345,7 @@ function shortcutFor(event: KeyboardEvent): string | null { if (key === 'l') return 'focus-address'; if (key === 'g' && event.shiftKey) return 'media-panel'; if (key === 'k' && !event.shiftKey) return 'command-palette'; + if (key === 'f' && !event.shiftKey && hasFeature('find')) return 'find'; if (key === 'tab') return event.shiftKey ? 'prev-tab' : 'next-tab'; if (key === 'r') return 'reload'; if (event.code === 'Backslash' || event.code === 'IntlBackslash') return event.shiftKey ? 'split-down' : 'split-right'; @@ -349,6 +355,7 @@ function shortcutFor(event: KeyboardEvent): string | null { if (key === '0' || event.code === 'Numpad0') return 'zoom-reset'; } } + if (event.key === 'F3' && !mod && !event.altKey) return event.shiftKey ? 'find-previous' : 'find-next'; // The app menu, like a browser's: F10, and Alt+F where Alt is not a typing key (not on macOS). if (event.key === 'F10' && !mod && !event.altKey && !event.shiftKey) return 'app-menu'; if (event.altKey && !mod && !event.shiftKey && event.code === 'KeyF' && os !== 'macos') return 'app-menu'; diff --git a/packages/shell/src/frame/WebPanel.tsx b/packages/shell/src/frame/WebPanel.tsx index a1411ae..9220759 100644 --- a/packages/shell/src/frame/WebPanel.tsx +++ b/packages/shell/src/frame/WebPanel.tsx @@ -4,6 +4,7 @@ import { tabProfile } from '../profileModel.ts'; import { AccountAvatar, accountName } from './AccountSwitcher.tsx'; import { WB_MARK } from './brand.ts'; import { invoke } from './bridge.ts'; +import { FindBar } from './FindBar.tsx'; import { useProfiles, useSiteText, useT } from './hooks.ts'; import { Icon } from './icons.tsx'; import { openPaneTheme } from './PaneTheme.tsx'; @@ -22,6 +23,13 @@ export function WebPanel(props: IDockviewPanelProps) { const [draft, setDraft] = useState(null); const [caret, setCaret] = useState(0); const [splitMenu, setSplitMenu] = useState(false); + // Find in page: the find field takes the address field's place while it is open (FindBar.tsx). + const [finding, setFinding] = useState(false); + useEffect(() => { + const open = (event: Event) => { if ((event as CustomEvent).detail === api.id) { setDraft(null); setFinding(true); } }; + window.addEventListener('bt-find', open); + return () => window.removeEventListener('bt-find', open); + }, [api.id]); // Windows: the page's last frame, shown while its webview is hidden (host `tab-still`). const still = useTabStill(api.id); useSiteText(); @@ -74,6 +82,7 @@ export function WebPanel(props: IDockviewPanelProps) { useEffect(() => { const focusAddress = (event: Event) => { if ((event as CustomEvent).detail !== api.id) return; + setFinding(false); if (draft === null) enterEdit(); else { input.current?.focus(); input.current?.select(); } }; @@ -121,7 +130,7 @@ export function WebPanel(props: IDockviewPanelProps) { {account && } - {editing + {finding ? setFinding(false)}/> : editing ?
step < factor - near) ?? ZOOM_MIN; } +// --------------------------------------------------------------------------------------------- +// Find in page + +/** + * What the find bar says about a search: "3/17" (the active match of the total), the total alone + * while no match is active, "No matches" for none. `number` writes a number in the active language. + */ +export function findLabel(counts: { count: number; index: number }, number: (value: number) => string = String): string { + if (counts.count <= 0) return menuText('findNone'); + if (counts.index < 0 || counts.index >= counts.count) return menuText('findTotal', { count: counts.count }); + return menuText('findCount', { index: number(counts.index + 1), count: number(counts.count) }); +} + /** Whole percent of a factor (1.1 → 110). */ export const zoomPercent = (factor: number) => Math.round(factor * 100); diff --git a/packages/shell/src/frame/paletteModel.ts b/packages/shell/src/frame/paletteModel.ts index cc12a2f..cf29f37 100644 --- a/packages/shell/src/frame/paletteModel.ts +++ b/packages/shell/src/frame/paletteModel.ts @@ -30,7 +30,9 @@ export type PaletteAction = | { type: 'workspace'; id: string } | { type: 'workspace-save' } /** Opens the app menu (the titlebar's "Settings and more"). */ - | { type: 'menu' }; + | { type: 'menu' } + /** Opens the find bar of the tab in front. */ + | { type: 'find' }; /** The frame's groups; the app's items are grouped under its product name, plugin commands under the plugin's. */ export type PaletteGroup = 'Tabs' | 'Deck' | 'Workspaces' | 'Profiles'; @@ -64,7 +66,7 @@ export type PaletteContext = { }; /** What the palette knows about the app: its site items, its name and which frame features it has. */ -export type PaletteSetup = { site: PaletteSite; product: string; decks: boolean; media: boolean; workspaces?: boolean }; +export type PaletteSetup = { site: PaletteSite; product: string; decks: boolean; media: boolean; workspaces?: boolean; find?: boolean }; /** A plugin command as the palette lists it: the tab's report plus the plugin's display name. */ export type PluginCommandItem = { id: string; title: string; keywords: string; plugin: string }; @@ -146,6 +148,8 @@ export function buildItems(context: PaletteContext, query: string, setup: Palett items.push({ id: `panel:${section.id}`, group: setup.product, label: section.label(), keywords: section.keywords, icon: section.icon, action: { type: 'panel', section: section.id } }); } if (setup.media) items.push({ id: 'media', group: setup.product, label: t('wb.palette.media'), hint: 'Ctrl+Shift+G', keywords: 'photos images screenshots attach paste media', icon: 'image', action: { type: 'media' } }); + // Find in the page of the tab in front (the shell's find bar; nothing is sent anywhere). + if (setup.find !== false) items.push({ id: 'find', group: setup.product, label: menuText('find'), hint: 'Ctrl+F', keywords: 'find search page text match', icon: 'search', action: { type: 'find' } }); // The app menu (the titlebar's "Settings and more"): language, theme, mode, zoom and the rest. items.push({ id: 'app-menu', group: setup.product, label: menuText('label'), hint: 'Alt+F', keywords: 'menu more settings language theme mode zoom options preferences', icon: 'settings', action: { type: 'menu' } }); // Plugin commands, grouped under each plugin's name; they run in the focused site tab. diff --git a/packages/shell/src/frame/site.ts b/packages/shell/src/frame/site.ts index 17b680b..d9e6090 100644 --- a/packages/shell/src/frame/site.ts +++ b/packages/shell/src/frame/site.ts @@ -147,11 +147,11 @@ export type ShellSite = { /** * Native features the app serves (waybetter-host modules it wires up): workspaces (`workspaces_*`), * encrypted folder sync (`sync_*`), developer mode (`dev_*`), plugin palette commands - * (`tab_run_command`) and page zoom (`tab_zoom`, the host's own); and what its panel has that the + * (`tab_run_command`), page zoom and find in page (`tab_zoom`, `tab_find`: the host's own); and what its panel has that the * app menu links to: the Store (`PanelSite.store`) and the updater (`PanelSite.updates`). Each is * on unless set to false; off, the frame shows nothing of it. */ - features?: { workspaces?: boolean; sync?: boolean; developer?: boolean; pluginCommands?: boolean; zoom?: boolean; store?: boolean; updates?: boolean }; + features?: { workspaces?: boolean; sync?: boolean; developer?: boolean; pluginCommands?: boolean; zoom?: boolean; find?: boolean; store?: boolean; updates?: boolean }; /** * The app menu (the titlebar's "Settings and more", Alt+F / F10): its rows in order (built-in * ones by name, the app's own as objects) and what the Language and Mode submenus need. Omit for diff --git a/packages/shell/tests/menu.test.ts b/packages/shell/tests/menu.test.ts index 5a73dff..8933714 100644 --- a/packages/shell/tests/menu.test.ts +++ b/packages/shell/tests/menu.test.ts @@ -8,15 +8,15 @@ import test from 'node:test'; import { fileURLToPath } from 'node:url'; import { setShellI18n, type ShellI18n } from '../src/frame/i18n.ts'; import { - DEFAULT_MENU, MENU_BUILTINS, MENU_MESSAGES, ZOOM_MAX, ZOOM_MIN, ZOOM_STEPS, builtinAvailable, findSpec, joinGroups, languageChoice, languageRows, menuText, menuWith, + DEFAULT_MENU, MENU_BUILTINS, MENU_MESSAGES, ZOOM_MAX, ZOOM_MIN, ZOOM_STEPS, builtinAvailable, findLabel, findSpec, joinGroups, languageChoice, languageRows, menuText, menuWith, menuWithout, moveStop, planMenu, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, zoomPercent, zoomStep, type MenuEnv, type MenuGroups, type MenuItemRow, type MenuItemSpec, type MenuLanguage, type MenuRow, } from '../src/frame/menuModel.ts'; import { buildItems } from '../src/frame/paletteModel.ts'; const here = dirname(fileURLToPath(import.meta.url)); -const ALL: MenuEnv = { decks: true, languages: true, themes: true, modes: true, zoom: true, store: true, workspaces: true, developer: true, updates: true }; -const NONE: MenuEnv = { decks: false, languages: false, themes: false, modes: false, zoom: false, store: false, workspaces: false, developer: false, updates: false }; +const ALL: MenuEnv = { decks: true, languages: true, themes: true, modes: true, zoom: true, find: true, store: true, workspaces: true, developer: true, updates: true }; +const NONE: MenuEnv = { decks: false, languages: false, themes: false, modes: false, zoom: false, find: false, store: false, workspaces: false, developer: false, updates: false }; const ids = (groups: ReturnType) => groups.map(group => group.map(entry => (typeof entry === 'string' ? entry : entry.id))); const items = (rows: MenuRow[]) => rows.filter((row): row is MenuItemRow => row.kind === 'item'); @@ -26,7 +26,7 @@ test('the default menu lists every built-in row once, and an app that serves eve }); test('a row the app cannot serve is left out, and a group left empty takes its rule with it', () => { - // A new app (create-waybetter): no decks, languages, themes, zoom, Store, workspaces, developer mode or updater. + // An app that serves none of the optional parts: no decks, languages, themes, zoom, find, Store, workspaces, developer mode or updater. assert.deepEqual(ids(planMenu(DEFAULT_MENU, NONE)), [ ['new-tab', 'split-right', 'split-down'], ['plugins'], @@ -35,7 +35,7 @@ test('a row the app cannot serve is left out, and a group left empty takes its r ]); // Each gate is its own. const gates: Array<[keyof MenuEnv, string]> = [ - ['decks', 'new-column'], ['languages', 'language'], ['themes', 'theme'], ['modes', 'mode'], ['zoom', 'zoom'], + ['decks', 'new-column'], ['languages', 'language'], ['themes', 'theme'], ['modes', 'mode'], ['zoom', 'zoom'], ['find', 'find'], ['store', 'store'], ['workspaces', 'workspaces'], ['developer', 'developer'], ['updates', 'updates'], ]; for (const [feature, row] of gates) { @@ -63,7 +63,7 @@ test('an app orders, removes and adds rows; its own rows follow their `when`', ( assert.equal(ids(planMenu(groups, ALL)).flat().includes('drafts'), false); drafts = true; assert.deepEqual(ids(planMenu(menuWithout(groups, 'store', 'zoom', 'drafts'), ALL)), [ - ['new-tab', 'split-right', 'split-down', 'new-column'], ['language', 'theme', 'mode'], ['plugins', 'workspaces'], ['shortcuts', 'palette'], ['developer', 'updates', 'about', 'settings'], + ['new-tab', 'split-right', 'split-down', 'new-column'], ['language', 'theme', 'mode'], ['plugins', 'workspaces'], ['find', 'shortcuts', 'palette'], ['developer', 'updates', 'about', 'settings'], ]); // Explicit order; a row listed twice shows once; an unknown name and an own row named like a built-in are ignored. const custom: MenuGroups = [['settings', 'new-tab', 'settings', 'nope' as never], [{ id: 'zoom', label: () => 'Fake zoom' }, own]]; @@ -229,15 +229,28 @@ test("the menu's words: English from menuMessages.en.json until a catalog has th assert.equal(menuText('zoom'), 'Zoom', 'a key the catalog lacks still reads in English'); // The component and the palette name their words through menuText, never as raw keys. const used = new Set(); - for (const file of ['AppMenu.tsx', 'TitlebarExtras.tsx', 'AccountSwitcher.tsx', 'paletteModel.ts']) { + for (const file of ['AppMenu.tsx', 'TitlebarExtras.tsx', 'AccountSwitcher.tsx', 'paletteModel.ts', 'FindBar.tsx', 'menuModel.ts']) { for (const match of readFileSync(join(here, '../src/frame', file), 'utf8').matchAll(/menuText\('([A-Za-z]+)'/g)) used.add(`wb.menu.${match[1]}`); } for (const key of used) assert.ok(key in MENU_MESSAGES, `${key} has English`); for (const key of Object.keys(MENU_MESSAGES)) assert.ok(used.has(key), `${key} is used`); }); +test("the find bar says which match of how many, in the reader's numbers", () => { + assert.equal(findLabel({ count: 17, index: 2 }), '3/17'); + assert.equal(findLabel({ count: 1, index: 0 }), '1/1'); + assert.equal(findLabel({ count: 0, index: -1 }), 'No matches'); + assert.equal(findLabel({ count: 5, index: -1 }), '5 matches', 'a count without an active match'); + assert.equal(findLabel({ count: 1, index: -1 }), '1 match'); + assert.equal(findLabel({ count: 12, index: 3 }, value => `<${value}>`), '<4>/<12>'); +}); + test('the palette opens the menu', () => { const all = buildItems({ tabs: [], profiles: [], activeProfile: 'default' }, '', { site: { placeholder: () => '', sections: [] }, product: 'App', decks: false, media: false }); const entry = all.find(item => item.id === 'app-menu'); assert.deepEqual([entry?.action, entry?.group], [{ type: 'menu' }, 'App']); + // Find in page is there unless the app has no find. + assert.deepEqual(all.find(item => item.id === 'find')?.action, { type: 'find' }); + const without = buildItems({ tabs: [], profiles: [], activeProfile: 'default' }, '', { site: { placeholder: () => '', sections: [] }, product: 'App', decks: false, media: false, find: false }); + assert.equal(without.some(item => item.id === 'find'), false); }); From c7437ac504f7e546db044140d4528c0ae653c8e2 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 30 Sep 2026 22:38:07 +0700 Subject: [PATCH 18/72] String packs, phase 1: data-only packs that replace the wrapped site's own UI strings. Pack and inventory formats, validator (only inventory keys, parameter names, plural and select kinds, no markup), ordered idempotent engine that keeps what a restore needs, coverage and drift report; the per-site catalog hook adapter with a self-check (ok, hook not matched, no catalog seen), a fail-open webpack chunk array hook, a small DOM text net; waybetter strings check Co-Authored-By: Claude Opus 5.5 --- README.md | 7 + docs/STRING-PACKS.md | 147 +++++ packages/runtime/src/stringPackHook.ts | 273 +++++++++ packages/runtime/src/stringPacks.ts | 548 ++++++++++++++++++ packages/runtime/src/textNet.ts | 129 +++++ packages/runtime/tests/stringPacks.test.ts | 545 +++++++++++++++++ packages/waybetter/README.md | 1 + packages/waybetter/bin/waybetter.mjs | 8 +- packages/waybetter/cli/strings.mjs | 121 ++++ packages/waybetter/tests/strings-cli.test.mjs | 80 +++ 10 files changed, 1857 insertions(+), 2 deletions(-) create mode 100644 docs/STRING-PACKS.md create mode 100644 packages/runtime/src/stringPackHook.ts create mode 100644 packages/runtime/src/stringPacks.ts create mode 100644 packages/runtime/src/textNet.ts create mode 100644 packages/runtime/tests/stringPacks.test.ts create mode 100644 packages/waybetter/cli/strings.mjs create mode 100644 packages/waybetter/tests/strings-cli.test.mjs diff --git a/README.md b/README.md index e9c83dc..058c664 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,10 @@ packages/runtime/src/ page runtime core (TypeScript, no dependencies) siteRuntime.ts the runtime's composition: the IPC bridge, flag-controlled parts with a deck column's overrides, the runtime object under its window names, native queues pageStrings.ts the page's language: English built in, native deliveries checked as data + stringPacks.ts string packs (docs/STRING-PACKS.md): pack and inventory formats, validator, + ordered engine, coverage, drift report + stringPackHook.ts the per-site catalog hook adapter, its self-check, a webpack chunk array hook + textNet.ts DOM safety net for labels no catalog hook reaches panelButton.ts the way into the panel from the page (navigation entry or floating button) commandReport.ts the palette command report and developer-mode start errors packages/shell/src/ shell core (TypeScript) and the shell frame (React) @@ -474,6 +478,9 @@ The npm package adds the app-side tooling: machine's account name, and prints hits masked (`m***`). `waybetter release` builds with `build-env` and refuses to release an artifact with a hit or one it could not open. The `.pdb` next to a Windows binary still holds every path: never publish it. +- `waybetter strings check `: a string pack (data that replaces the wrapped site's own UI + strings) against the site's string inventory: only inventory keys, parameter names, plural and + select kinds, no markup; prints the coverage. See docs/STRING-PACKS.md. - `waybetter i18n check|extract`: an app's locale catalogs against the framework's rules (file shape, keys English lacks, ICU syntax, placeholder parity, plural forms, no markup), the framework's catalogs in the same languages, the generated `languages.json` and native diff --git a/docs/STRING-PACKS.md b/docs/STRING-PACKS.md new file mode 100644 index 0000000..5226afd --- /dev/null +++ b/docs/STRING-PACKS.md @@ -0,0 +1,147 @@ +# String packs + +A string pack replaces the wrapped site's own UI strings with data: it adds a language the site +does not offer, fixes its translation, or rewords it. This is phase 1: the formats, the validator, +the application engine, the hook interface and `waybetter strings check`. The Store kind, the +install screen and the settings UI are not built yet. + +## Rules + +1. **Idempotent.** The result is a pure function of (the site's own values, the ordered pack list). + Applying twice equals applying once. Packs apply in the listed order; a later pack wins per key. +2. **The site's own language is the fallback.** A pack patches on top of whatever language the site + shows. A key no pack changes keeps exactly the site's value. +3. **An inventory of the site's known keys.** A pack can change only inventory keys. An unknown key + is reported and never applied. +4. **Packs are data.** Plain text in an ICU MessageFormat subset. Never HTML, never code. + +## The pack + +```json +{ + "format": 1, + "site": "x", + "catalog": "web", + "language": "en-x-pirate", + "name": "Pirate", + "authors": ["Someone"], + "base": "en", + "strings": { + "a0000001": "Home port", + "b0000002": "{count, plural, one {# sighting} other {# sightings}}" + } +} +``` + +- `site` and `catalog` name the inventory the pack is for. One site can have several catalogs + (different builds of the site with different key spaces); each has its own inventory and packs. +- `language` is a BCP 47 tag; a private-use tag is fine. `base` is the language whose plural rules + the pack follows when the runtime does not know `language`; without either, every number takes + the `other` form. +- `strings` maps a key id to text. The ids are the inventory's; a pack never carries the site's own + text. + +A value may use `{name}`, `{name, plural, one {…} other {…}}` (with `#` for the number and `=0`, +`=1` exact forms) and `{name, select, a {…} other {…}}`. A value is refused, and the site's text +stays, when: + +- it names a parameter the original does not take; +- it pluralizes a parameter the original does not pluralize, or selects on one the original does + not select on (the original's plural parameters are the ones known to be numbers); +- a plural or select has no `other`; +- it uses a number or date format, `selectordinal` or a plural offset; +- it contains `<` or `>` (unless the inventory gives the key tag slots; then exactly those tags); +- it contains control or bidi-override characters, is empty or is longer than 2000 characters; +- the key's kind cannot be replaced by data yet (`rich`, `format`). + +A parameter is inserted the way string concatenation would insert it (`String(value)`). + +## The inventory + +```json +{ + "format": 1, "site": "x", "catalog": "web", "base": "en", "build": "…", + "entries": { + "a0000001": { "kind": "text", "hash": "0k3j…" }, + "b0000002": { "kind": "message", "params": ["count"], "plural": ["count"], "hash": "…" }, + "c0000003": { "kind": "rich", "group": "rich", "hash": "…" } + } +} +``` + +| Kind | The site's value | A pack can replace it | +|---|---|---| +| `text` | a string | yes | +| `message` | a function of parameters that returns a string | yes | +| `rich` | text with element slots | not yet | +| `format` | a compiled number, date or currency formatter | no | + +`hash` is a hash of the base-language value (`hashText`), for the drift report; the inventory holds +no text of the site. `group` names the part of the catalog a key arrives with (default `main`). + +`driftReport(inventory, observed, loadedGroups)` compares an inventory with a newer build: `added`, +`reworded` (the hash changed), `reshaped` (kind or parameters changed) and `vanished`. A key is +called vanished only when its group's base catalog was actually read. + +`packInventory(inventory)` is the form a page runtime ships: ids and shapes, no hashes. + +## The engine + +```ts +const engine = createStringEngine(inventory, [compilePack(packA, inventory), compilePack(packB, inventory)]); +engine.resolve(id, siteValue); // packB's value, else packA's, else exactly siteValue +``` + +`resolve` returns a string for a `text` key and a function with the original's call shape for a +`message` key (closures over the parsed message; nothing is evaluated). Feeding a value the engine +produced back in returns the same value. It keeps the site's own value of every key it changed +(`engine.originals()`), which is what a restore needs; `applyPacks` and `restoreCatalog` do both +for a whole catalog object without changing it. A live value whose kind differs from the +inventory's is left alone and listed in `engine.stats().mismatched`; a key the site has and the +inventory lacks is listed in `unlisted`. + +## Hooking a site + +How a site hands its strings to its own code is that site's implementation detail, so the hook is +an adapter the app supplies: + +```ts +const adapter: CatalogHookAdapter = { + catalog: 'web', + install(win, sink) { + // At document start: arrange for the site's catalog to pass through + // sink.seen(group) a catalog file is loading + // sink.matched(language, group) the hook matched + // sink.resolve(id, original) the value to register + return () => { /* remove the hook */ }; + }, +}; +const handle = installStringPacks(window, [{ adapter, inventory, packs }], { onStatus }); +``` + +- The adapter must not change the site's objects: hand the site a shadow + (`Object.create(module)`) instead. +- Everything fails open: an exception in a wrapper leaves the site's behaviour as it was. +- A catalog without a usable pack is not hooked at all. +- The self-check decides after `settleMs`: `ok`, `not-matched` (a catalog file was seen but the + hook did not match: the site changed) or `no-catalog` (no catalog file was seen). + +For a webpack site, `watchChunkArray(win, name, onChunk)` sees every chunk before the site's own +`push` gets it and passes it on unchanged; `mapChunkRequires(chunk, map)` lets one identified +chunk's modules receive a shadow of what they `require`. + +`installTextNet(win, { map })` is a DOM safety net for labels no catalog hook can reach (the server +sends them already worded): exact text in text nodes, `aria-label`, `placeholder` and `title`, the +site's value kept per node, restored on `dispose()`. It is secondary: it cannot see parameters or +plural forms. + +## Checking a pack + +```sh +waybetter strings check pack.strings.json --inventory strings/x.web.inventory.json +``` + +Prints what was refused and why, the unknown keys, and the coverage per group (translated of +translatable, and how many keys are not translatable yet). Exit 1 when anything would not be +applied. Without `--inventory`, the inventories come from `waybetter.strings.json` +(`{ "inventories": ["…"] }`) in the app's root. diff --git a/packages/runtime/src/stringPackHook.ts b/packages/runtime/src/stringPackHook.ts new file mode 100644 index 0000000..38b503f --- /dev/null +++ b/packages/runtime/src/stringPackHook.ts @@ -0,0 +1,273 @@ +// String packs in the page (published as `waybetter/runtime/stringPackHook`): the per-site +// "catalog hook adapter" interface, the installer that connects adapters to the engine of +// stringPacks.ts, a self-check that says when a hook did not match, and the generic half of a +// common hook point (a webpack chunk array). +// +// How a site hands its strings to its own code is that site's implementation detail, so the hook +// is an adapter the app supplies. One site can have several catalogs (different builds of the +// site, different key spaces); each gets its own adapter, inventory and packs. +// +// Everything here fails open: an exception inside a wrapper leaves the site's own behaviour as it +// was, and with no pack installed nothing is hooked at all. +import { + compilePack, createStringEngine, type CompiledPack, type EngineStats, type PackReport, type PageInventory, type StringEngine, + type StringInventory, +} from './stringPacks.ts'; + +// ------------------------------------------------------------------------------------------- +// The adapter interface + +/** What an adapter reports to and asks from the framework. None of these throw. */ +export type CatalogSink = { + /** A catalog file of this adapter was seen loading (whether or not the hook then matches). */ + seen(group?: string): void; + /** The hook matched: the site is about to register values in `language`. */ + matched(language: string, group?: string): void; + /** The value to register for `id`: a pack's, or exactly `original`. */ + resolve(id: string, original: unknown): unknown; +}; + +export type CatalogHookAdapter = { + /** The catalog (key space) this adapter hooks; packs and the inventory name the same one. */ + catalog: string; + /** Installs the hook at document start; returns its removal. Must not change the site's objects. */ + install(win: Window, sink: CatalogSink): () => void; +}; + +export type CatalogSetup = { + adapter: CatalogHookAdapter; + inventory: StringInventory | PageInventory; + /** Pack documents in application order (a later one wins). Untrusted data: validated here. */ + packs: readonly unknown[]; +}; + +/** + * `ok`: the hook matched and keys went through it. + * `not-matched`: a catalog file was seen but the hook did not match it (the site changed). + * `no-catalog`: no catalog file was seen at all (another build of the site, or not loaded yet). + */ +export type HookStatus = 'pending' | 'ok' | 'not-matched' | 'no-catalog'; + +export type CatalogReport = { + catalog: string; + status: HookStatus; + /** Languages the site registered through the hook. */ + languages: string[]; + /** Catalog files seen, per group. */ + seen: Record; + packs: { name: string; language: string; report: PackReport }[]; + /** Pack documents that were refused as a whole. */ + refused: string[]; + engine: EngineStats; +}; + +export type StringPacksHandle = { + status(catalog?: string): HookStatus; + report(): CatalogReport[]; + /** The engines, per catalog (the originals they keep are what a restore needs). */ + engine(catalog: string): StringEngine | undefined; + dispose(): void; +}; + +export type StringPacksOptions = { + /** When the self-check decides (default 15 s after install). */ + settleMs?: number; + /** Called once per catalog when its status is decided (`ok` as soon as it is reached). */ + onStatus?: (report: CatalogReport) => void; +}; + +type TimerWindow = { setTimeout(handler: () => void, ms: number): unknown; clearTimeout(id: never): void }; + +/** + * Installs the adapters that have at least one usable pack. A catalog without packs is not hooked + * (the site runs untouched), so its status stays `pending`. + */ +export function installStringPacks(win: Window, setups: readonly CatalogSetup[], options: StringPacksOptions = {}): StringPacksHandle { + const timers = win as unknown as TimerWindow; + const states = setups.map(setup => { + const packs: CompiledPack[] = []; + const refused: string[] = []; + for (const document of setup.packs) { + try { + packs.push(compilePack(document, setup.inventory)); + } catch (error) { + refused.push(error instanceof Error ? error.message : String(error)); + } + } + const usable = packs.filter(pack => pack.values.size > 0); + return { + catalog: setup.adapter.catalog, adapter: setup.adapter, packs, refused, usable, + engine: usable.length ? createStringEngine(setup.inventory, usable) : null, + seen: {} as Record, languages: new Set(), keys: 0, settled: false, told: false, + remove: null as null | (() => void), + }; + }); + type State = (typeof states)[number]; + + const status = (state: State): HookStatus => { + if (state.languages.size && state.keys > 0) return 'ok'; + if (!state.settled) return 'pending'; + return Object.keys(state.seen).length ? 'not-matched' : 'no-catalog'; + }; + const reportOf = (state: State): CatalogReport => ({ + catalog: state.catalog, + status: status(state), + languages: [...state.languages], + seen: { ...state.seen }, + packs: state.packs.map(pack => ({ name: pack.name, language: pack.language, report: pack.report })), + refused: [...state.refused], + engine: state.engine?.stats() ?? { seen: 0, applied: 0, unlisted: [], mismatched: [] }, + }); + const tell = (state: State) => { + if (state.told || status(state) === 'pending') return; + state.told = true; + try { options.onStatus?.(reportOf(state)); } catch { /* a reporter must not break the page */ } + }; + + for (const state of states) { + const engine = state.engine; + if (!engine) continue; + const sink: CatalogSink = { + seen(group = 'main') { state.seen[group] = (state.seen[group] ?? 0) + 1; }, + matched(language) { state.languages.add(String(language)); }, + resolve(id, original) { + try { + state.keys += 1; + const value = engine.resolve(id, original); + if (state.keys === 1) tell(state); + return value; + } catch { + return original; + } + }, + }; + try { + state.remove = state.adapter.install(win, sink); + } catch { + state.remove = null; + } + } + + const hooked = states.filter(state => state.engine); + const timer = hooked.length + ? timers.setTimeout(() => { for (const state of hooked) { state.settled = true; tell(state); } }, options.settleMs ?? 15000) + : null; + + return { + status: catalog => { + const state = catalog ? states.find(item => item.catalog === catalog) : hooked[0] ?? states[0]; + return state ? status(state) : 'pending'; + }, + report: () => states.map(reportOf), + engine: catalog => states.find(item => item.catalog === catalog)?.engine ?? undefined, + dispose() { + if (timer !== null) timers.clearTimeout(timer as never); + for (const state of states) { + try { state.remove?.(); } catch { /* the hook is gone either way */ } + state.remove = null; + } + }, + }; +} + +// ------------------------------------------------------------------------------------------- +// A webpack chunk array as the hook point +// +// A webpack site loads its code as chunks pushed onto a global array +// (`(globalThis.webpackChunk_x ||= []).push([ids, modules, runtime?])`); webpack's runtime later +// replaces the array's `push` with its own and replays what is already there. Watching the array +// therefore sees every chunk before its modules are installed, whichever loads first. + +type Chunk = [unknown, Record | unknown[], ...unknown[]]; + +/** + * Calls `onChunk(chunk, script)` for every chunk pushed onto `win[name]`, before the site's own + * `push` gets it; `script` is the URL of the script doing the push (`''` when unknown). Install at + * document start. The array and webpack's own `push` replacement keep working unchanged: the + * wrapper calls exactly the `push` that was current when it was read, with the same arguments. An + * exception in `onChunk` is swallowed. Returns the removal. + */ +export function watchChunkArray(win: object, name: string, onChunk: (chunk: Chunk, script: string) => void): () => void { + const holder = win as Record & { document?: { currentScript?: { src?: string } | null } }; + const existing = holder[name]; + const array: unknown[] = Array.isArray(existing) ? existing : []; + if (!Array.isArray(existing)) holder[name] = array; + const done = new WeakSet(); + let current: (...items: unknown[]) => number = array.push; + let active = true; + const look = (items: ArrayLike) => { + if (!active) return; + for (let index = 0; index < items.length; index += 1) { + const chunk = items[index]; + if (typeof chunk !== 'object' || chunk === null || done.has(chunk)) continue; + done.add(chunk); + try { + onChunk(chunk as Chunk, holder.document?.currentScript?.src ?? ''); + } catch { + // Fail open: the chunk goes on to the site exactly as it came. + } + } + }; + try { + Object.defineProperty(array, 'push', { + configurable: true, + enumerable: false, + get() { + const target = current; + return function push(this: unknown, ...items: unknown[]) { + look(items); + return target.apply(this, items); + }; + }, + set(next: (...items: unknown[]) => number) { current = next; }, + }); + } catch { + return () => {}; + } + return () => { + active = false; + try { + if (current === Array.prototype.push) delete (array as { push?: unknown }).push; + else Object.defineProperty(array, 'push', { configurable: true, enumerable: false, writable: true, value: current }); + } catch { + // Left as the pass-through wrapper. + } + }; +} + +/** + * Wraps the module factories of one chunk so that what they `require` passes through `map`: + * `map(exports)` returns a replacement for that one call, or `undefined` to hand out the module's + * own exports. The module itself is never changed (return a shadow, e.g. `Object.create(exports)`). + * Only call this for a chunk you have identified; other chunks must stay untouched. + */ +export function mapChunkRequires(chunk: Chunk, map: (exports: unknown) => unknown): void { + const modules = chunk[1]; + if (typeof modules !== 'object' || modules === null) return; + const table = modules as Record; + for (const id of Object.keys(table)) { + const factory = table[id]; + if (typeof factory !== 'function') continue; + table[id] = function (this: unknown, module: unknown, exports: unknown, require: unknown, ...rest: unknown[]) { + let through = require; + if (typeof require === 'function') { + try { + through = new Proxy(require, { + apply(target, self, args) { + const result = Reflect.apply(target as (...a: unknown[]) => unknown, self, args); + try { + const replaced = map(result); + return replaced === undefined ? result : replaced; + } catch { + return result; + } + }, + }); + } catch { + through = require; + } + } + return (factory as (...a: unknown[]) => unknown).call(this, module, exports, through, ...rest); + }; + } +} diff --git a/packages/runtime/src/stringPacks.ts b/packages/runtime/src/stringPacks.ts new file mode 100644 index 0000000..1c995b2 --- /dev/null +++ b/packages/runtime/src/stringPacks.ts @@ -0,0 +1,548 @@ +// String packs: data-only packs that replace the wrapped site's own UI strings (published as +// `waybetter/runtime/stringPacks`). A pack adds a language the site does not offer, fixes its +// translation or rewords it. This file is the data side: the pack and inventory formats, the +// validator, the ordered application engine, coverage and the drift report. It touches no DOM and +// runs the same in the page, in the shell and in Node (`waybetter strings check`). +// +// The rules (they are the owner's, and every function here keeps them): +// - Idempotent. The result is a pure function of (the site's own values, the ordered pack list): +// applying twice equals applying once, and a later pack wins over an earlier one per key. +// - The site's own language is the fallback. A key no pack changes keeps exactly the site's value +// (the same object, not a copy). +// - An inventory of the site's known keys. A pack may change only inventory keys, and only keys +// whose kind can be replaced by data; unknown keys are reported, never applied. +// - Packs are data: plain text in an ICU MessageFormat subset ({param}, plural, select). Never +// HTML, never code. A message is interpreted by closures here; nothing is evaluated. +// +// One site can have several catalogs (each with its own key space, inventory and hook adapter, +// see stringPackHook.ts); a pack names the one it is for. +import { parseMessage } from './i18n.ts'; + +type Parts = ReturnType; + +// ------------------------------------------------------------------------------------------- +// Formats + +/** + * What the site's value for a key is: + * - `text`: a plain string; + * - `message`: a function of a parameter object that returns a string; + * - `rich`: text with element slots (not replaceable by data yet); + * - `format`: a compiled number/date/currency formatter (not text). + * Only `text` and `message` can be replaced by a pack. + */ +export type StringKind = 'text' | 'message' | 'rich' | 'format'; + +export type InventoryEntry = { + kind: StringKind; + /** Parameter names the site's value takes (`message`). */ + params?: string[]; + /** Parameters the site's value pluralizes: known to be numbers, so a pack may pluralize them. */ + plural?: string[]; + /** Parameters the site's value selects on. */ + select?: string[]; + /** Tag slot names, for catalogs whose values carry `…` slots. */ + tags?: string[]; + /** Hash of the base-language value (`hashText`): drift detection; never the text itself. */ + hash: string; + /** Part of the catalog the key arrives with (default `main`), e.g. a lazily loaded `emoji` group. */ + group?: string; +}; + +/** The known keys of one catalog of one site. It carries ids and shapes, never the site's text. */ +export type StringInventory = { + format: 1; + site: string; + catalog: string; + /** Language the hashes were taken from. */ + base: string; + /** The site build the inventory was read from. */ + build?: string; + entries: Record; +}; + +/** A string pack document: metadata and `key id -> text`. */ +export type StringPack = { + format: 1; + site: string; + catalog: string; + /** BCP 47 tag of the pack's language (private-use tags are fine: `en-x-pirate`). */ + language: string; + name: string; + authors: string[]; + /** A language whose plural rules the pack follows when the runtime does not know `language`. */ + base?: string; + version?: string; + description?: string; + strings: Record; +}; + +export const STRING_PACK_LIMITS = Object.freeze({ strings: 40000, value: 2000, name: 80, authors: 16 }); +export const MAIN_GROUP = 'main'; + +const TAG = /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/; +const IDENT = /^[a-z][a-z0-9-]{0,31}$/; +const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f‪-‮⁦-⁩]/; +const CATEGORIES = new Set(['zero', 'one', 'two', 'few', 'many', 'other']); + +/** Whether a pack can replace a value of this kind. */ +export function translatable(kind: StringKind): boolean { + return kind === 'text' || kind === 'message'; +} + +/** 53-bit hash of a text as 11 base-36 characters. Same result in every runtime. */ +export function hashText(text: string): string { + let h1 = 0xdeadbeef; + let h2 = 0x41c6ce57; + for (let i = 0; i < text.length; i += 1) { + const ch = text.charCodeAt(i); + h1 = Math.imul(h1 ^ ch, 2654435761); + h2 = Math.imul(h2 ^ ch, 1597334677); + } + h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909); + h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909); + return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36).padStart(11, '0'); +} + +// ------------------------------------------------------------------------------------------- +// Inventory lookup (the full inventory, or its compact page form) + +/** The facts the validator and the engine need about one key. */ +export type EntryShape = Pick; +export type InventoryLookup = (id: string) => EntryShape | undefined; + +/** + * The inventory as it ships inside a page runtime: ids and shapes only, no hashes, a fraction of + * the size. `text` and `closed` are space-separated ids; a message is `name name*` (`*` = plural, + * `?` = select). + */ +export type PageInventory = { site: string; catalog: string; text: string; message: Record; closed: string }; + +export function packInventory(inventory: StringInventory): PageInventory { + const text: string[] = []; + const closed: string[] = []; + const message: Record = {}; + for (const [id, entry] of Object.entries(inventory.entries)) { + if (entry.kind === 'text' && !entry.tags?.length) text.push(id); + else if (entry.kind === 'message' && !entry.tags?.length) { + message[id] = (entry.params ?? []).map(name => `${name}${entry.plural?.includes(name) ? '*' : ''}${entry.select?.includes(name) ? '?' : ''}`).join(' '); + } else closed.push(id); + } + return { site: inventory.site, catalog: inventory.catalog, text: text.join(' '), message, closed: closed.join(' ') }; +} + +const TEXT_SHAPE: EntryShape = Object.freeze({ kind: 'text' }); +const CLOSED_SHAPE: EntryShape = Object.freeze({ kind: 'rich' }); + +/** A lookup over either form. The page form is decoded on first use. */ +export function inventoryLookup(inventory: StringInventory | PageInventory): InventoryLookup { + if ('entries' in inventory) { + const entries = inventory.entries; + return id => (Object.prototype.hasOwnProperty.call(entries, id) ? entries[id] : undefined); + } + let table: Map | null = null; + const decode = () => { + const map = new Map(); + if (inventory.text) for (const id of inventory.text.split(' ')) map.set(id, TEXT_SHAPE); + if (inventory.closed) for (const id of inventory.closed.split(' ')) map.set(id, CLOSED_SHAPE); + for (const [id, spec] of Object.entries(inventory.message)) { + const names = spec ? spec.split(' ') : []; + map.set(id, { + kind: 'message', + params: names.map(name => name.replace(/[*?]+$/, '')), + plural: names.filter(name => name.includes('*')).map(name => name.replace(/[*?]+$/, '')), + select: names.filter(name => name.includes('?')).map(name => name.replace(/[*?]+$/, '')), + }); + } + return map; + }; + return id => (table ??= decode()).get(id); +} + +// ------------------------------------------------------------------------------------------- +// Validator + +export type PackIssue = { level: 'error' | 'warning'; key?: string; message: string }; + +const isRecord = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value); + +/** Checks the document envelope. Errors mean the pack is not applied at all. */ +export function checkPackShape(input: unknown): PackIssue[] { + const issues: PackIssue[] = []; + const error = (message: string) => { issues.push({ level: 'error', message }); }; + if (!isRecord(input)) return [{ level: 'error', message: 'a string pack is a JSON object' }]; + if (input.format !== 1) error('"format" must be 1'); + for (const field of ['site', 'catalog'] as const) { + if (typeof input[field] !== 'string' || !IDENT.test(input[field])) error(`"${field}" must be a short lowercase id`); + } + if (typeof input.language !== 'string' || !TAG.test(input.language)) error('"language" must be a language tag (en, pt-BR, en-x-pirate)'); + if (input.base !== undefined && (typeof input.base !== 'string' || !TAG.test(input.base))) error('"base" must be a language tag'); + if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > STRING_PACK_LIMITS.name || CONTROL.test(input.name) || /[<>]/.test(input.name)) { + error(`"name" must be 1 to ${STRING_PACK_LIMITS.name} characters of plain text`); + } + if (!Array.isArray(input.authors) || input.authors.length > STRING_PACK_LIMITS.authors + || input.authors.some(author => typeof author !== 'string' || !author.trim() || author.length > STRING_PACK_LIMITS.name || CONTROL.test(author) || /[<>]/.test(author))) { + error(`"authors" must be a list of at most ${STRING_PACK_LIMITS.authors} plain-text names`); + } + for (const field of ['version', 'description'] as const) { + const value = input[field]; + if (value !== undefined && (typeof value !== 'string' || value.length > 400 || CONTROL.test(value) || /[<>]/.test(value))) error(`"${field}" must be plain text`); + } + if (!isRecord(input.strings)) error('"strings" must be an object of key id -> text'); + else if (Object.keys(input.strings).length > STRING_PACK_LIMITS.strings) error(`"strings" has more than ${STRING_PACK_LIMITS.strings} entries`); + const known = new Set(['$schema', 'format', 'site', 'catalog', 'language', 'base', 'name', 'authors', 'version', 'description', 'strings']); + for (const key of Object.keys(input)) if (!known.has(key)) issues.push({ level: 'warning', message: `unknown field "${key}" is ignored` }); + return issues; +} + +const TAG_TOKEN = /<\/?([A-Za-z][A-Za-z0-9-]*)>/g; + +/** Tag rule: only the original's tag slots, each opened and closed; any other `<` or `>` is refused. */ +function checkTags(value: string, tags: readonly string[]): string | null { + if (!value.includes('<') && !value.includes('>')) { + return tags.length ? `the original's tags are missing: ${tags.map(tag => `<${tag}>`).join(' ')}` : null; + } + if (!tags.length) return 'markup is not allowed: a pack is text, < and > cannot be used'; + const open: string[] = []; + const seen = new Set(); + for (const match of value.matchAll(TAG_TOKEN)) { + const name = match[1]!; + if (!tags.includes(name)) return `<${name}> is not a tag of the original`; + if (match[0].startsWith(' does not close an open tag`; + } else { + open.push(name); + seen.add(name); + } + } + if (open.length) return `<${open[open.length - 1]}> is not closed`; + if (/[<>]/.test(value.replace(TAG_TOKEN, ''))) return '< and > may only be used for the original\'s tags'; + const missing = tags.filter(tag => !seen.has(tag)); + return missing.length ? `the original's tags are missing: ${missing.map(tag => `<${tag}>`).join(' ')}` : null; +} + +/** Walks a parsed message against the key's shape; returns the first problem. */ +function checkParts(parts: Parts, shape: EntryShape): string | null { + const params = shape.params ?? []; + for (const part of parts) { + if (typeof part === 'string' || part.kind === 'pound') continue; + if (!params.includes(part.name)) { + return params.length ? `{${part.name}} is not a parameter of the original (it has: ${params.join(', ')})` : `{${part.name}}: the original takes no parameters`; + } + if (part.kind === 'arg') { + if (part.format) return `{${part.name}, ${part.format}} is not supported: only {name}, plural and select`; + continue; + } + if (part.kind === 'plural') { + if (part.ordinal) return `{${part.name}, selectordinal} is not supported: only {name}, plural and select`; + if (part.offset) return `{${part.name}, plural, offset:…} is not supported`; + if (!shape.plural?.includes(part.name)) return `{${part.name}} is not a plural of the original`; + for (const selector of Object.keys(part.options)) { + if (!CATEGORIES.has(selector) && !/^=\d+$/.test(selector)) return `"${selector}" is not a plural form (zero, one, two, few, many, other, =N)`; + } + } else if (!shape.select?.includes(part.name)) { + return `{${part.name}} is not a select of the original`; + } + for (const option of Object.values(part.options)) { + const nested = checkParts(option, shape); + if (nested) return nested; + } + } + return null; +} + +/** + * Validates one pack value against the key's inventory entry. Returns the parsed message, or the + * reason it is refused (the original then stays). + */ +export function validateString(shape: EntryShape, value: unknown): { parts: Parts } | { reason: string } { + if (!translatable(shape.kind)) return { reason: `not translatable yet (${shape.kind})` }; + if (typeof value !== 'string') return { reason: 'the value must be text' }; + if (!value) return { reason: 'the value is empty' }; + if (value.length > STRING_PACK_LIMITS.value) return { reason: `longer than ${STRING_PACK_LIMITS.value} characters` }; + if (CONTROL.test(value)) return { reason: 'control or bidi-override characters are not allowed' }; + const tags = checkTags(value, shape.tags ?? []); + if (tags) return { reason: tags }; + let parts: Parts; + try { + parts = parseMessage(value); + } catch (error) { + return { reason: `invalid message syntax: ${error instanceof Error ? error.message : String(error)}` }; + } + const problem = checkParts(parts, shape.kind === 'message' ? shape : { kind: 'text' }); + return problem ? { reason: problem } : { parts }; +} + +// ------------------------------------------------------------------------------------------- +// Compiling a pack (validation against an inventory) + +export type CompiledValue = { text: string } | { parts: Parts }; + +export type PackReport = { + /** Entries in the pack. */ + total: number; + /** Entries that are valid for an inventory key. */ + valid: number; + /** Ids the inventory does not have: never applied. */ + unknown: string[]; + /** Values that failed validation: not applied, the original stays. */ + rejected: { id: string; reason: string }[]; +}; + +export type CompiledPack = { + name: string; + language: string; + base?: string; + site: string; + catalog: string; + values: ReadonlyMap; + report: PackReport; +}; + +/** A message without arguments as its literal text (quotes resolved). */ +function literal(parts: Parts): string { + return parts.map(part => (typeof part === 'string' ? part : '')).join(''); +} + +/** + * Validates a pack against an inventory. Throws on a malformed envelope or a pack for another + * site/catalog; every other problem is per key and lands in `report`. + */ +export function compilePack(input: unknown, inventory: StringInventory | PageInventory): CompiledPack { + const shapeErrors = checkPackShape(input).filter(issue => issue.level === 'error'); + if (shapeErrors.length) throw new Error(`invalid string pack: ${shapeErrors.map(issue => issue.message).join('; ')}`); + const pack = input as StringPack; + if (pack.site !== inventory.site || pack.catalog !== inventory.catalog) { + throw new Error(`the pack is for ${pack.site}/${pack.catalog}, the inventory is ${inventory.site}/${inventory.catalog}`); + } + const lookup = inventoryLookup(inventory); + const values = new Map(); + const report: PackReport = { total: 0, valid: 0, unknown: [], rejected: [] }; + for (const [id, value] of Object.entries(pack.strings)) { + report.total += 1; + const shape = lookup(id); + if (!shape) { report.unknown.push(id); continue; } + const result = validateString(shape, value); + if ('reason' in result) { report.rejected.push({ id, reason: result.reason }); continue; } + values.set(id, shape.kind === 'text' ? { text: literal(result.parts) } : { parts: result.parts }); + report.valid += 1; + } + return { name: pack.name, language: pack.language, base: pack.base, site: pack.site, catalog: pack.catalog, values, report }; +} + +// ------------------------------------------------------------------------------------------- +// Interpreting a message (closures over the parsed parts; nothing is evaluated) + +const rulesCache = new Map(); + +/** Plural rules of the first language the runtime knows; `null` = every number is `other`. */ +function rulesFor(languages: readonly (string | undefined)[]): Intl.PluralRules | null { + const key = languages.join('|'); + let rules = rulesCache.get(key); + if (rules !== undefined) return rules; + rules = null; + for (const language of languages) { + if (!language) continue; + const tag = language.split(/-x-/i)[0]!; + try { + if (Intl.PluralRules.supportedLocalesOf([tag]).length) { rules = new Intl.PluralRules(tag); break; } + } catch { + // Not a tag this runtime accepts: try the next. + } + } + rulesCache.set(key, rules); + return rules; +} + +/** + * Renders a validated message. A parameter is inserted the way string concatenation would + * (`String(value)`, nothing for a missing one); `#` is the plural's own value. + */ +export function renderMessage(parts: Parts, params: Readonly>, languages: readonly (string | undefined)[], pound: unknown = undefined): string { + let out = ''; + for (const part of parts) { + if (typeof part === 'string') { out += part; continue; } + // The parser only yields `#` inside a plural, so there is always a value it stands for. + if (part.kind === 'pound') { out += pound === undefined || pound === null ? '' : String(pound); continue; } + const value = params[part.name]; + if (part.kind === 'arg') { out += value === undefined || value === null ? '' : String(value); continue; } + if (part.kind === 'select') { + out += renderMessage(part.options[String(value)] ?? part.options.other!, params, languages, pound); + continue; + } + const n = typeof value === 'number' ? value : Number(value); + const option = Number.isFinite(n) + ? part.options[`=${n}`] ?? part.options[rulesFor(languages)?.select(n) ?? 'other'] ?? part.options.other! + : part.options.other!; + out += renderMessage(option, params, languages, value); + } + return out; +} + +// ------------------------------------------------------------------------------------------- +// The ordered application engine + +export type EngineStats = { + /** Keys the site registered. */ + seen: number; + /** Keys a pack value was used for. */ + applied: number; + /** Keys the site registered that the inventory does not have (new keys: drift). */ + unlisted: string[]; + /** Keys whose live value does not have the inventory's kind: left untouched. */ + mismatched: string[]; +}; + +export type StringEngine = { + /** + * The value to use for `id`, given the site's own value: a pack's, or exactly `original`. + * Feeding a value this engine produced back in returns the same value (idempotent). + */ + resolve(id: string, original: unknown): unknown; + /** The site's own values of the keys a pack changed: what restoring needs. */ + originals(): ReadonlyMap; + stats(): EngineStats; +}; + +const MAX_LISTED = 200; + +/** `packs` in application order: a later pack wins over an earlier one for the same key. */ +export function createStringEngine(inventory: StringInventory | PageInventory | InventoryLookup, packs: readonly CompiledPack[]): StringEngine { + const lookup = typeof inventory === 'function' ? inventory : inventoryLookup(inventory); + const originals = new Map(); + const applied = new Map(); + const produced = new WeakMap(); + const seen = new Set(); + const unlisted = new Set(); + const mismatched = new Set(); + + const winner = (id: string): { pack: CompiledPack; value: CompiledValue } | null => { + for (let index = packs.length - 1; index >= 0; index -= 1) { + const value = packs[index]!.values.get(id); + if (value) return { pack: packs[index]!, value }; + } + return null; + }; + + const resolve = (id: string, incoming: unknown): unknown => { + let original = incoming; + // A value of ours coming back in (a second application): work from the site's own value again. + if (typeof incoming === 'function' && produced.has(incoming)) original = produced.get(incoming); + else if (typeof incoming === 'string' && applied.has(id) && applied.get(id) === incoming) original = originals.get(id); + seen.add(id); + const found = winner(id); + if (!found) { + if (unlisted.size < MAX_LISTED && !lookup(id)) unlisted.add(id); + return original; + } + const shape = lookup(id); + if (!shape || !translatable(shape.kind)) return original; + if (shape.kind === 'text' ? typeof original !== 'string' : typeof original !== 'function') { + if (mismatched.size < MAX_LISTED) mismatched.add(id); + return original; + } + if (originals.has(id) && originals.get(id) === original) return applied.get(id); + let next: unknown; + if ('text' in found.value) { + next = found.value.text; + } else { + const parts = found.value.parts; + const languages = [found.pack.language, found.pack.base]; + const message = (params?: unknown): string => renderMessage(parts, isRecord(params) ? params : {}, languages); + produced.set(message, original); + next = message; + } + originals.set(id, original); + applied.set(id, next); + return next; + }; + + return { + resolve, + originals: () => originals, + stats: () => ({ seen: seen.size, applied: applied.size, unlisted: [...unlisted], mismatched: [...mismatched] }), + }; +} + +/** + * The whole catalog at once: a new object with the packs applied; `catalog` itself is not + * changed. `applyPacks(applyPacks(c, …), …)` with one engine equals `applyPacks(c, …)`. + */ +export function applyPacks(catalog: Readonly>, engine: StringEngine): Record { + const out: Record = {}; + for (const id of Object.keys(catalog)) out[id] = engine.resolve(id, catalog[id]); + return out; +} + +/** The inverse: every value a pack changed is the site's own again; `catalog` is not changed. */ +export function restoreCatalog(catalog: Readonly>, engine: StringEngine): Record { + const originals = engine.originals(); + const out: Record = {}; + for (const id of Object.keys(catalog)) out[id] = originals.has(id) ? originals.get(id) : catalog[id]; + return out; +} + +// ------------------------------------------------------------------------------------------- +// Coverage + +export type Coverage = { + /** Keys a pack can replace (text and messages). */ + translatable: number; + /** Of those, keys the pack has a valid value for. */ + translated: number; + /** Keys that exist but cannot be replaced by data yet (rich text, formatters). */ + closed: number; +}; + +/** Coverage of a compiled pack per group of the inventory, plus `all`. */ +export function coverage(inventory: StringInventory, pack: Pick): Record { + const out: Record = { all: { translatable: 0, translated: 0, closed: 0 } }; + for (const [id, entry] of Object.entries(inventory.entries)) { + const group = (out[entry.group ?? MAIN_GROUP] ??= { translatable: 0, translated: 0, closed: 0 }); + for (const bucket of [group, out.all!]) { + if (!translatable(entry.kind)) { bucket.closed += 1; continue; } + bucket.translatable += 1; + if (pack.values.has(id)) bucket.translated += 1; + } + } + return out; +} + +// ------------------------------------------------------------------------------------------- +// Drift (the site shipped a new build) + +export type DriftReport = { + /** Keys the site has that the inventory lacks. */ + added: string[]; + /** Keys whose base-language value changed (same shape). */ + reworded: string[]; + /** Keys whose kind or parameters changed: pack values for them have to be checked again. */ + reshaped: string[]; + /** Inventory keys the site no longer has. Only for groups whose base catalog was loaded. */ + vanished: string[]; +}; + +const sameList = (a: readonly string[] = [], b: readonly string[] = []) => a.length === b.length && [...a].sort().join('\n') === [...b].sort().join('\n'); + +/** + * Compares an inventory with what was observed now. `loaded` names the groups whose base catalog + * was actually read: a key can only be called vanished when its group was (a lazily loaded group + * that never arrived says nothing about its keys). + */ +export function driftReport(inventory: StringInventory, observed: Readonly>, loaded: readonly string[]): DriftReport { + const report: DriftReport = { added: [], reworded: [], reshaped: [], vanished: [] }; + for (const [id, now] of Object.entries(observed)) { + const before = Object.prototype.hasOwnProperty.call(inventory.entries, id) ? inventory.entries[id] : undefined; + if (!before) { report.added.push(id); continue; } + if (before.kind !== now.kind || !sameList(before.params, now.params) || !sameList(before.plural, now.plural) || !sameList(before.select, now.select) || !sameList(before.tags, now.tags)) { + report.reshaped.push(id); + } else if (before.hash !== now.hash) { + report.reworded.push(id); + } + } + const groups = new Set(loaded); + for (const [id, entry] of Object.entries(inventory.entries)) { + if (!Object.prototype.hasOwnProperty.call(observed, id) && groups.has(entry.group ?? MAIN_GROUP)) report.vanished.push(id); + } + return report; +} diff --git a/packages/runtime/src/textNet.ts b/packages/runtime/src/textNet.ts new file mode 100644 index 0000000..f27ca1c --- /dev/null +++ b/packages/runtime/src/textNet.ts @@ -0,0 +1,129 @@ +// A DOM safety net for strings a catalog hook cannot reach (published as +// `waybetter/runtime/textNet`): labels the server sends already worded, or text that is painted +// before the hook can act. It replaces exact texts in text nodes and in `aria-label`, +// `placeholder` and `title`, keeps the site's own value per node, and puts everything back when it +// is disposed. It is secondary to a catalog hook: it cannot see parameters or plural forms, and a +// rendered text only maps back to one key in a language without homonyms. +// +// Text is written through `nodeValue` / `setAttribute` (never `textContent` or HTML), so the site's +// framework keeps owning its nodes; when the site rewrites a node, the net looks at it again. + +export type TextNetOptions = { + /** Exact original text -> replacement. A text that is not a key is left alone. */ + map: ReadonlyMap; + /** Attributes to cover (default `aria-label`, `placeholder`, `title`). */ + attributes?: readonly string[]; + /** Elements whose content is never touched (default: scripts, styles, editable text). */ + skip?: string; +}; + +export type TextNetHandle = { + /** Text nodes and attributes currently replaced. */ + count(): number; + /** Restores every node and attribute to the site's own value and stops observing. */ + dispose(): void; +}; + +const DEFAULT_ATTRIBUTES = ['aria-label', 'placeholder', 'title']; +const DEFAULT_SKIP = 'script, style, noscript, textarea, [contenteditable=""], [contenteditable="true"]'; +const TEXT_NODE = 3; +const ELEMENT_NODE = 1; +const SHOW_TEXT = 4; + +export function installTextNet(win: Window, options: TextNetOptions): TextNetHandle { + const doc = win.document; + const attributes = options.attributes ?? DEFAULT_ATTRIBUTES; + const skip = options.skip ?? DEFAULT_SKIP; + const map = options.map; + /** The site's own value and ours, per text node. */ + const texts = new WeakMap(); + /** The same per element and attribute. */ + const attrs = new WeakMap>(); + let count = 0; + let active = true; + + const skipped = (element: Element | null) => !!element && !!skip && !!element.closest(skip); + + const text = (node: Node) => { + const value = node.nodeValue ?? ''; + const kept = texts.get(node); + if (kept) { + if (value === kept.applied) return; + // The site wrote the node again: what it wrote is the new original. + texts.delete(node); + count -= 1; + } + const next = map.get(value); + if (next === undefined || next === value || skipped(node.parentElement)) return; + texts.set(node, { original: value, applied: next }); + count += 1; + node.nodeValue = next; + }; + + const attribute = (element: Element, name: string) => { + const value = element.getAttribute(name); + const kept = attrs.get(element)?.get(name); + if (kept) { + if (value === kept.applied) return; + attrs.get(element)!.delete(name); + count -= 1; + } + if (value === null) return; + const next = map.get(value); + if (next === undefined || next === value || skipped(element)) return; + let own = attrs.get(element); + if (!own) attrs.set(element, own = new Map()); + own.set(name, { original: value, applied: next }); + count += 1; + element.setAttribute(name, next); + }; + + const sweep = (root: Node) => { + if (root.nodeType === TEXT_NODE) { text(root); return; } + if (root.nodeType !== ELEMENT_NODE) return; + const element = root as Element; + const walker = doc.createTreeWalker(element, SHOW_TEXT); + while (walker.nextNode()) text(walker.currentNode); + for (const name of attributes) { + if (element.hasAttribute(name)) attribute(element, name); + for (const child of element.querySelectorAll(`[${name}]`)) attribute(child, name); + } + }; + + const observer = new (win as unknown as { MutationObserver: typeof MutationObserver }).MutationObserver(records => { + if (!active) return; + for (const record of records) { + if (record.type === 'characterData') text(record.target); + else if (record.type === 'attributes') { if (record.attributeName) attribute(record.target as Element, record.attributeName); } + else for (const node of record.addedNodes) sweep(node); + } + }); + if (map.size) { + if (doc.documentElement) sweep(doc.documentElement); + observer.observe(doc, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: [...attributes] }); + } + + return { + count: () => count, + dispose() { + if (!active) return; + active = false; + observer.disconnect(); + if (!doc.documentElement) return; + const walker = doc.createTreeWalker(doc.documentElement, SHOW_TEXT); + while (walker.nextNode()) { + const node = walker.currentNode; + const kept = texts.get(node); + if (kept && node.nodeValue === kept.applied) node.nodeValue = kept.original; + texts.delete(node); + } + for (const name of attributes) { + for (const element of doc.querySelectorAll(`[${name}]`)) { + const kept = attrs.get(element)?.get(name); + if (kept && element.getAttribute(name) === kept.applied) element.setAttribute(name, kept.original); + } + } + count = 0; + }, + }; +} diff --git a/packages/runtime/tests/stringPacks.test.ts b/packages/runtime/tests/stringPacks.test.ts new file mode 100644 index 0000000..3853374 --- /dev/null +++ b/packages/runtime/tests/stringPacks.test.ts @@ -0,0 +1,545 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { + applyPacks, checkPackShape, compilePack, coverage, createStringEngine, driftReport, hashText, inventoryLookup, packInventory, + renderMessage, restoreCatalog, validateString, type InventoryEntry, type StringInventory, type StringPack, +} from '../src/stringPacks.ts'; +import { parseMessage } from '../src/i18n.ts'; +import { installStringPacks, mapChunkRequires, watchChunkArray, type CatalogHookAdapter, type CatalogSink } from '../src/stringPackHook.ts'; +import { installTextNet } from '../src/textNet.ts'; + +// A small site: two texts, two messages (one plural), one rich entry, one formatter, one lazy group. +const INVENTORY: StringInventory = { + format: 1, site: 'demo', catalog: 'web', base: 'en', build: 'b1', + entries: { + a0000001: { kind: 'text', hash: hashText('Home') }, + a0000002: { kind: 'text', hash: hashText('Following') }, + b0000001: { kind: 'message', params: ['name'], hash: hashText('Hello {name}') }, + b0000002: { kind: 'message', params: ['count', 'name'], plural: ['count'], hash: hashText('{count} posts by {name}') }, + c0000001: { kind: 'rich', hash: hashText('rich') }, + d0000001: { kind: 'format', hash: hashText('fmt') }, + e0000001: { kind: 'text', group: 'emoji', hash: hashText('Grinning face') }, + }, +}; +/** The site's own values, as its catalog registers them. */ +const site = () => ({ + a0000001: 'Home', + a0000002: 'Following', + b0000001: (e: { name: string }) => `Hello ${e.name}`, + b0000002: (e: { count: number; name: string }) => `${e.count} ${e.count === 1 ? 'post' : 'posts'} by ${e.name}`, + c0000001: () => ({ element: true }), + d0000001: (n: number) => String(n), + e0000001: 'Grinning face', +}); +const pack = (strings: Record, extra: Partial = {}): StringPack => ({ + format: 1, site: 'demo', catalog: 'web', language: 'en-x-test', name: 'Test', authors: ['A tester'], base: 'en', strings, ...extra, +}); + +test('hashText: stable, 11 characters, different for different text', () => { + assert.equal(hashText('Home'), hashText('Home')); + assert.match(hashText('Home'), /^[0-9a-z]{11}$/); + assert.notEqual(hashText('Home'), hashText('home')); + assert.equal(hashText(''), hashText('')); +}); + +test('pack envelope: what is refused as a whole', () => { + assert.deepEqual(checkPackShape(pack({ a0000001: 'Hoom' })), []); + const errors = (input: unknown) => checkPackShape(input).filter(issue => issue.level === 'error').map(issue => issue.message).join(' | '); + assert.match(errors([]), /JSON object/); + assert.match(errors({ ...pack({}), format: 2 }), /format/); + assert.match(errors({ ...pack({}), language: 'not a tag' }), /language/); + assert.match(errors({ ...pack({}), name: 'x' }), /name/); + assert.match(errors({ ...pack({}), authors: 'me' }), /authors/); + assert.match(errors({ ...pack({}), strings: [] }), /strings/); + assert.match(errors({ ...pack({}), site: 'Demo Site' }), /site/); + assert.deepEqual(checkPackShape({ ...pack({}), extra: 1 }).map(issue => issue.level), ['warning']); + assert.throws(() => compilePack({ ...pack({}), format: 2 }, INVENTORY), /invalid string pack/); + assert.throws(() => compilePack(pack({}, { catalog: 'other' }), INVENTORY), /the pack is for demo\/other/); +}); + +test('validator: parameters, plural kind, other, markup', () => { + const entry = (id: string) => INVENTORY.entries[id]!; + const reason = (id: string, value: unknown) => { const result = validateString(entry(id), value); return 'reason' in result ? result.reason : ''; }; + // Accepted. + assert.equal(reason('a0000001', 'Hoom'), ''); + assert.equal(reason('b0000001', 'Ahoy {name}'), ''); + assert.equal(reason('b0000001', 'Ahoy'), '', 'a subset of the parameters is fine'); + assert.equal(reason('b0000002', '{count, plural, one {# postle} other {# postles}} by {name}'), ''); + assert.equal(reason('b0000002', '{count, plural, =0 {nothing} other {#}}'), ''); + assert.equal(reason('b0000002', '{count} by {name}'), '', 'a language without plural forms needs none'); + assert.equal(reason('a0000001', "It's '{'fine'}'"), '', 'quoted braces are text'); + // Refused. + assert.match(reason('a0000001', 'Hi {name}'), /takes no parameters/); + assert.match(reason('b0000001', 'Ahoy {user}'), /not a parameter of the original \(it has: name\)/); + assert.match(reason('b0000001', '{name, plural, one {a} other {b}}'), /not a plural of the original/); + assert.match(reason('b0000002', '{name, select, a {x} other {y}}'), /not a select of the original/); + assert.match(reason('b0000002', '{count, plural, one {a}}'), /"other"/); + assert.match(reason('b0000002', '{count, plural, lots {a} other {b}}'), /not a plural form/); + assert.match(reason('b0000002', '{count, selectordinal, one {a} other {b}}'), /selectordinal/); + assert.match(reason('b0000002', '{count, number}'), /not supported/); + assert.match(reason('b0000002', '{count, plural, offset:1 other {b}}'), /offset/); + assert.match(reason('a0000001', 'Home'), /markup is not allowed/); + assert.match(reason('a0000001', 'a > b'), /markup is not allowed/); + assert.match(reason('a0000001', 'Home {'), /invalid message syntax/); + assert.match(reason('a0000001', ''), /empty/); + assert.match(reason('a0000001', 42), /must be text/); + assert.match(reason('a0000001', 'x'.repeat(2001)), /longer than/); + assert.match(reason('a0000001', 'a‮b'), /control or bidi/); + assert.match(reason('c0000001', 'text'), /not translatable yet \(rich\)/); + assert.match(reason('d0000001', 'text'), /not translatable yet \(format\)/); +}); + +test('validator: tag slots must be the original\'s', () => { + const shape: InventoryEntry = { kind: 'text', tags: ['link'], hash: 'x' }; + const reason = (value: string) => { const result = validateString(shape, value); return 'reason' in result ? result.reason : ''; }; + assert.equal(reason('Read the rules'), ''); + assert.match(reason('Read the rules'), /tags are missing: /); + assert.match(reason('Read the rules'), / is not a tag of the original/); + assert.match(reason('Read the rules'), /not closed/); + assert.match(reason('Read the rules'), /does not close/); + assert.match(reason('1 < 2 x'), /may only be used for the original's tags/); +}); + +test('compilePack: unknown keys are reported and never applied; bad values are rejected one by one', () => { + const compiled = compilePack(pack({ + a0000001: 'Hoom', b0000001: 'Ahoy {name}', zzzzzzzz: 'Nope', a0000002: 'x', c0000001: 'rich text', b0000002: '{count, plural, one {# postle} other {# postles}}', + }), INVENTORY); + assert.deepEqual([...compiled.values.keys()].sort(), ['a0000001', 'b0000001', 'b0000002']); + assert.deepEqual(compiled.report.unknown, ['zzzzzzzz']); + assert.deepEqual(compiled.report.rejected.map(item => item.id).sort(), ['a0000002', 'c0000001']); + assert.equal(compiled.report.total, 6); + assert.equal(compiled.report.valid, 3); + // An unknown key reaches the engine as nothing at all. + const engine = createStringEngine(INVENTORY, [compiled]); + assert.equal(engine.resolve('zzzzzzzz', 'Site text'), 'Site text'); + assert.equal(engine.resolve('a0000002', 'Following'), 'Following', 'a rejected value leaves the original'); +}); + +test('renderMessage: concatenation semantics, plural by the pack language, exact forms, select', () => { + const render = (source: string, params: Record, languages: (string | undefined)[] = ['en']) => renderMessage(parseMessage(source), params, languages); + assert.equal(render('Ahoy {name}!', { name: 'Ada' }), 'Ahoy Ada!'); + assert.equal(render('Ahoy {name}!', {}), 'Ahoy !'); + assert.equal(render('{count} of them', { count: '1,234' }), '1,234 of them', 'a parameter is inserted as it comes'); + const plural = '{count, plural, =0 {none} one {# postle} other {# postles}}'; + assert.equal(render(plural, { count: 0 }), 'none'); + assert.equal(render(plural, { count: 1 }), '1 postle'); + assert.equal(render(plural, { count: 5 }), '5 postles'); + assert.equal(render(plural, { count: '7' }), '7 postles'); + assert.equal(render(plural, { count: 'many' }), 'many postles', 'not a number: other'); + // A language the runtime does not know falls back to the pack's base, then to `other`. + assert.equal(render(plural, { count: 1 }, ['qqq-x-made-up', 'en']), '1 postle'); + assert.equal(render(plural, { count: 1 }, ['zz-x-test', undefined]), '1 postles'); + assert.equal(render(plural, { count: 1 }, ['en-x-test']), '1 postle', 'a private-use tag uses its language'); + assert.equal(render('{count, plural, one {# gönderi} other {# gönderi}}', { count: 2 }, ['tr']), '2 gönderi'); + assert.equal(render('{kind, select, a {first} other {rest}}', { kind: 'a' }), 'first'); + assert.equal(render('{kind, select, a {first} other {rest}}', { kind: 'b' }), 'rest'); +}); + +test('engine: a pack value when the key has one, otherwise exactly the site\'s value', () => { + const values = site(); + const engine = createStringEngine(INVENTORY, [compilePack(pack({ + a0000001: 'Hoom', b0000002: '{count, plural, one {# postle} other {# postles}} by {name}', + }), INVENTORY)]); + const out = applyPacks(values, engine); + assert.equal(out.a0000001, 'Hoom'); + assert.equal((out.b0000002 as (e: unknown) => string)({ count: 1, name: 'Ada' }), '1 postle by Ada'); + assert.equal((out.b0000002 as (e: unknown) => string)({ count: 3, name: 'Ada' }), '3 postles by Ada'); + assert.equal((out.b0000002 as () => string)(), ' postles by ', 'called without parameters: still a string'); + // Untouched keys are the very same values (same function objects). + for (const id of ['a0000002', 'b0000001', 'c0000001', 'd0000001', 'e0000001'] as const) assert.equal(out[id], values[id], id); + // The site's catalog object was not changed. + assert.deepEqual(Object.keys(values), Object.keys(site())); + assert.equal(values.a0000001, 'Home'); + assert.deepEqual(engine.stats(), { seen: 7, applied: 2, unlisted: [], mismatched: [] }); +}); + +test('engine: applying twice equals applying once', () => { + const values = site(); + const engine = createStringEngine(INVENTORY, [compilePack(pack({ a0000001: 'Hoom', b0000001: 'Ahoy {name}' }), INVENTORY)]); + const once = applyPacks(values, engine); + const twice = applyPacks(once, engine); + const again = applyPacks(values, engine); + for (const id of Object.keys(values)) { + assert.equal(twice[id], once[id], `${id}: second application changes nothing`); + assert.equal(again[id], once[id], `${id}: the same input gives the same value`); + } + assert.equal(engine.stats().applied, 2); + // A fresh engine (a reload) gives the same result for the same input. + const reloaded = applyPacks(values, createStringEngine(INVENTORY, [compilePack(pack({ a0000001: 'Hoom', b0000001: 'Ahoy {name}' }), INVENTORY)])); + assert.equal(reloaded.a0000001, once.a0000001); + assert.equal((reloaded.b0000001 as (e: unknown) => string)({ name: 'Ada' }), (once.b0000001 as (e: unknown) => string)({ name: 'Ada' })); +}); + +test('engine: packs apply in the listed order, the later one wins per key', () => { + const language = compilePack(pack({ a0000001: 'Hoom', a0000002: 'Trailing' }, { name: 'Language' }), INVENTORY); + const rewording = compilePack(pack({ a0000001: 'Den' }, { name: 'Rewording' }), INVENTORY); + const first = applyPacks(site(), createStringEngine(INVENTORY, [language, rewording])); + assert.equal(first.a0000001, 'Den'); + assert.equal(first.a0000002, 'Trailing', 'a key only the earlier pack has keeps its value'); + const second = applyPacks(site(), createStringEngine(INVENTORY, [rewording, language])); + assert.equal(second.a0000001, 'Hoom'); + // No packs: everything is the site's. + const none = applyPacks(site(), createStringEngine(INVENTORY, [])); + assert.equal(none.a0000001, 'Home'); +}); + +test('engine: restore gives back exactly the site\'s values', () => { + const values = site(); + const engine = createStringEngine(INVENTORY, [compilePack(pack({ a0000001: 'Hoom', b0000001: 'Ahoy {name}' }), INVENTORY)]); + const applied = applyPacks(values, engine); + assert.deepEqual([...engine.originals().keys()].sort(), ['a0000001', 'b0000001'], 'only what a pack changed is kept'); + const restored = restoreCatalog(applied, engine); + for (const id of Object.keys(values) as (keyof typeof values)[]) assert.equal(restored[id], values[id], id); + assert.equal(applied.a0000001, 'Hoom', 'restoring does not change the applied object'); +}); + +test('engine: a live value of another kind than the inventory says is left alone', () => { + const engine = createStringEngine(INVENTORY, [compilePack(pack({ a0000001: 'Hoom', b0000001: 'Ahoy {name}' }), INVENTORY)]); + const fn = () => 'now a function'; + assert.equal(engine.resolve('a0000001', fn), fn); + assert.equal(engine.resolve('b0000001', 'now a string'), 'now a string'); + assert.deepEqual(engine.stats().mismatched.sort(), ['a0000001', 'b0000001']); + assert.equal(engine.stats().applied, 0); + // A key the site has and the inventory lacks is counted as drift. + assert.equal(engine.resolve('f0000009', 'New text'), 'New text'); + assert.deepEqual(engine.stats().unlisted, ['f0000009']); +}); + +test('page inventory: the compact form answers like the full one', () => { + const page = packInventory(INVENTORY); + assert.equal(JSON.stringify(page).includes('hash'), false); + const full = inventoryLookup(INVENTORY); + const compact = inventoryLookup(page); + assert.equal(compact('a0000001')?.kind, 'text'); + assert.equal(compact('e0000001')?.kind, 'text'); + assert.deepEqual(compact('b0000002'), { kind: 'message', params: ['count', 'name'], plural: ['count'], select: [] }); + assert.equal(compact('nope'), undefined); + assert.equal(full('nope'), undefined); + assert.equal(full('constructor'), undefined, 'inherited names are not keys'); + for (const id of ['c0000001', 'd0000001']) assert.notEqual(compact(id)?.kind, 'text'); + // The same pack compiles the same against both. + const strings = { a0000001: 'Hoom', b0000002: '{count, plural, one {#} other {#}}', c0000001: 'x', zzzzzzzz: 'y' }; + const a = compilePack(pack(strings), INVENTORY); + const b = compilePack(pack(strings), page); + assert.deepEqual([...a.values.keys()], [...b.values.keys()]); + assert.deepEqual(a.report.unknown, b.report.unknown); + assert.deepEqual(a.report.rejected.map(item => item.id), b.report.rejected.map(item => item.id)); +}); + +test('coverage: per group, with what cannot be translated yet counted apart', () => { + const compiled = compilePack(pack({ a0000001: 'Hoom', b0000001: 'Ahoy {name}', e0000001: 'Grin' }), INVENTORY); + assert.deepEqual(coverage(INVENTORY, compiled), { + all: { translatable: 5, translated: 3, closed: 2 }, + main: { translatable: 4, translated: 2, closed: 2 }, + emoji: { translatable: 1, translated: 1, closed: 0 }, + }); +}); + +test('drift report: new, reworded, reshaped; vanished only for a group whose base catalog was loaded', () => { + const observed: Record = { + a0000001: { kind: 'text', hash: hashText('Home') }, + a0000002: { kind: 'text', hash: hashText('Following now') }, + b0000001: { kind: 'message', params: ['name', 'title'], hash: hashText('Hello {name}') }, + c0000001: { kind: 'rich', hash: hashText('rich') }, + d0000001: { kind: 'format', hash: hashText('fmt') }, + f0000001: { kind: 'text', hash: hashText('Brand new') }, + }; + assert.deepEqual(driftReport(INVENTORY, observed, ['main']), { + added: ['f0000001'], reworded: ['a0000002'], reshaped: ['b0000001'], vanished: ['b0000002'], + }); + // The emoji group was never loaded: its key is not called vanished. With it loaded, it is. + assert.deepEqual(driftReport(INVENTORY, observed, ['main', 'emoji']).vanished, ['b0000002', 'e0000001']); + // Nothing loaded: nothing can be called vanished. + assert.deepEqual(driftReport(INVENTORY, observed, []).vanished, []); + assert.deepEqual(driftReport(INVENTORY, INVENTORY.entries, ['main', 'emoji']), { added: [], reworded: [], reshaped: [], vanished: [] }); +}); + +// ------------------------------------------------------------------------------------------- +// The chunk array hook + +/** A stand-in for webpack's runtime: takes over `push`, replays what is there, installs modules. */ +function webpackRuntime(array: unknown[]) { + const installed: Record = {}; + const parentPush = array.push.bind(array); + const callback = (parent: ((chunk: unknown) => number) | 0, chunk: unknown) => { + const [, modules] = chunk as [unknown, Record]; + Object.assign(installed, modules); + if (parent) parent(chunk); + return 0; + }; + array.forEach(chunk => callback(0, chunk)); + array.push = ((chunk: unknown) => callback(parentPush, chunk)) as typeof array.push; + return installed; +} + +test('chunk array hook: every chunk is seen once, before the site gets it, whichever loads first', () => { + const win: Record & { document: { currentScript: { src: string } | null } } = { document: { currentScript: { src: 'https://cdn.test/a.js' } } }; + const seen: string[] = []; + watchChunkArray(win, 'chunks', (chunk, script) => { seen.push(`${String((chunk[0] as unknown[])[0])}@${script}`); }); + const array = win.chunks as unknown[]; + const early = [[1], { m1: () => 1 }]; + array.push(early); + assert.equal(array.length, 1, 'before the runtime loads, push is still the array\'s own'); + const installed = webpackRuntime(array); + win.document.currentScript = { src: 'https://cdn.test/b.js' }; + const late = [[2], { m2: () => 2 }]; + array.push(late); + win.document.currentScript = null; + array.push([[3], {}]); + assert.deepEqual(seen, ['1@https://cdn.test/a.js', '2@https://cdn.test/b.js', '3@']); + assert.deepEqual(Object.keys(installed), ['m1', 'm2']); + assert.deepEqual(array, [early, late, [[3], {}]], 'the array holds the same chunks in the same order'); +}); + +test('chunk array hook: a chunk nobody maps passes through byte-identical', () => { + const win: Record = {}; + watchChunkArray(win, 'chunks', () => { /* looks, touches nothing */ }); + const array = win.chunks as unknown[]; + const installed = webpackRuntime(array); + const factory = function (module: { exports: unknown }) { module.exports = 42; }; + const runtime = () => {}; + const chunk = [[7, 8], { m7: factory }, runtime]; + const snapshot = { ids: chunk[0], modules: chunk[1], source: factory.toString(), keys: Object.keys(chunk[1] as object) }; + array.push(chunk); + assert.equal(array[0], chunk, 'the same chunk object reaches the array'); + assert.equal(chunk.length, 3); + assert.equal(chunk[0], snapshot.ids); + assert.equal(chunk[1], snapshot.modules); + assert.equal(chunk[2], runtime); + assert.equal((chunk[1] as Record).m7, factory, 'the same factory function'); + assert.equal(installed.m7, factory); + assert.equal(factory.toString(), snapshot.source); + assert.deepEqual(Object.keys(chunk[1] as object), snapshot.keys); +}); + +test('chunk array hook: fails open, and removal puts the site\'s push back', () => { + const win: Record = {}; + const remove = watchChunkArray(win, 'chunks', () => { throw new Error('boom'); }); + const array = win.chunks as unknown[]; + const installed = webpackRuntime(array); + const sitePush = Object.getOwnPropertyDescriptor(array, 'push'); + assert.ok(sitePush?.get, 'the accessor is ours while installed'); + assert.doesNotThrow(() => array.push([[1], { m1: 1 }])); + assert.deepEqual(Object.keys(installed), ['m1']); + remove(); + assert.equal(typeof Object.getOwnPropertyDescriptor(array, 'push')?.value, 'function', 'a plain property again'); + array.push([[2], { m2: 2 }]); + assert.deepEqual(Object.keys(installed), ['m1', 'm2']); + assert.equal(array.length, 2); + // Removed before any runtime took over: the array has no own push left. + const other: Record = {}; + watchChunkArray(other, 'chunks', () => {})(); + assert.equal(Object.prototype.hasOwnProperty.call(other.chunks, 'push'), false); + // An existing array is kept (the site's `||= []` finds it). + const existing: unknown[] = []; + const third: Record = { chunks: existing }; + watchChunkArray(third, 'chunks', () => {}); + assert.equal(third.chunks, existing); +}); + +test('mapChunkRequires: a module sees a shadow of what it requires; the required module is unchanged', () => { + const registry = { register: (language: string) => `site:${language}`, other: 1 }; + const require = Object.assign((id: string): any => (id === 'registry' ? registry : { id }), { e: 'kept' }); + const results: unknown[] = []; + const factory = function (this: unknown, module: { exports: unknown }, _exports: unknown, req: typeof require) { + results.push(req('registry').register('en'), req('plain'), req.e, this); + module.exports = 'done'; + }; + const chunk: [unknown, Record] = [[1], { m: factory }]; + mapChunkRequires(chunk, exports => { + if (exports !== registry) return undefined; + const shadow = Object.create(registry) as typeof registry; + Object.defineProperty(shadow, 'register', { value: (language: string) => `ours:${language}` }); + return shadow; + }); + assert.notEqual(chunk[1].m, factory); + const module = { exports: {} as unknown }; + (chunk[1].m as (...args: unknown[]) => void).call('self', module, module.exports, require); + assert.deepEqual(results, ['ours:en', { id: 'plain' }, 'kept', 'self']); + assert.equal(module.exports, 'done'); + assert.equal(registry.register('en'), 'site:en', 'the site\'s module is untouched'); + assert.deepEqual(Object.keys(registry), ['register', 'other']); + // A throwing map hands out the module's own exports. + const failing: [unknown, Record] = [[2], { m: factory }]; + mapChunkRequires(failing, () => { throw new Error('boom'); }); + results.length = 0; + (failing[1].m as (...args: unknown[]) => void).call('self', module, module.exports, require); + assert.equal(results[0], 'site:en'); +}); + +// ------------------------------------------------------------------------------------------- +// Adapters and the self-check + +function fakeWindow() { + const timers: (() => void)[] = []; + const win = { setTimeout: (fn: () => void) => { timers.push(fn); return timers.length; }, clearTimeout: () => {} } as unknown as Window; + return { win, settle: () => { for (const fn of timers.splice(0)) fn(); } }; +} +/** An adapter driven by the test: `drive` plays the site. */ +function adapter(catalog = 'web') { + const state: { sink: CatalogSink | null; removed: number } = { sink: null, removed: 0 }; + const hook: CatalogHookAdapter = { catalog, install: (_win, sink) => { state.sink = sink; return () => { state.removed += 1; }; } }; + return { hook, state }; +} + +test('self-check: ok, "hook not matched" and "no catalog seen" are distinct', () => { + const packs = [pack({ a0000001: 'Hoom' })]; + // ok: a catalog file was seen, the hook matched, keys went through. + { + const { win, settle } = fakeWindow(); + const { hook, state } = adapter(); + const told: string[] = []; + const handle = installStringPacks(win, [{ adapter: hook, inventory: INVENTORY, packs }], { onStatus: report => told.push(report.status) }); + assert.equal(handle.status(), 'pending'); + state.sink!.seen(); + state.sink!.matched('en-GB'); + assert.equal(state.sink!.resolve('a0000001', 'Home'), 'Hoom'); + assert.equal(state.sink!.resolve('a0000002', 'Following'), 'Following'); + assert.equal(handle.status(), 'ok'); + settle(); + assert.deepEqual(told, ['ok'], 'told once'); + const [report] = handle.report(); + assert.deepEqual({ status: report!.status, languages: report!.languages, seen: report!.seen, applied: report!.engine.applied }, { status: 'ok', languages: ['en-GB'], seen: { main: 1 }, applied: 1 }); + handle.dispose(); + assert.equal(state.removed, 1); + } + // A catalog file was seen but nothing went through the hook. + { + const { win, settle } = fakeWindow(); + const { hook, state } = adapter(); + const told: string[] = []; + const handle = installStringPacks(win, [{ adapter: hook, inventory: INVENTORY, packs }], { onStatus: report => told.push(report.status) }); + state.sink!.seen('main'); + assert.equal(handle.status(), 'pending'); + settle(); + assert.equal(handle.status(), 'not-matched'); + assert.deepEqual(told, ['not-matched']); + } + // No catalog file at all. + { + const { win, settle } = fakeWindow(); + const { hook } = adapter(); + const told: string[] = []; + const handle = installStringPacks(win, [{ adapter: hook, inventory: INVENTORY, packs }], { onStatus: report => told.push(report.status) }); + settle(); + assert.equal(handle.status(), 'no-catalog'); + assert.deepEqual(told, ['no-catalog']); + } +}); + +test('install: no usable pack means no hook; several catalogs keep their own packs', () => { + const { win } = fakeWindow(); + const web = adapter('web'); + const guest = adapter('guest'); + const guestInventory: StringInventory = { format: 1, site: 'demo', catalog: 'guest', base: 'en', entries: { 'Sign in': { kind: 'text', hash: hashText('Sign in') } } }; + const handle = installStringPacks(win, [ + { adapter: web.hook, inventory: INVENTORY, packs: [] }, + { adapter: guest.hook, inventory: guestInventory, packs: [pack({ 'Sign in': 'Sign inne' }, { catalog: 'guest' }), pack({ a0000001: 'Hoom' }), 'not a pack'] }, + ]); + assert.equal(web.state.sink, null, 'a catalog without packs is not hooked'); + assert.ok(guest.state.sink); + assert.equal(guest.state.sink!.resolve('Sign in', 'Sign in'), 'Sign inne'); + const report = handle.report(); + assert.equal(report[1]!.packs.length, 1); + assert.equal(report[1]!.refused.length, 2, 'a pack for another catalog and a malformed one are refused as a whole'); + assert.equal(handle.engine('web'), undefined); + assert.ok(handle.engine('guest')); + // Only unknown keys: nothing usable, nothing hooked. + const third = adapter(); + installStringPacks(win, [{ adapter: third.hook, inventory: INVENTORY, packs: [pack({ zzzzzzzz: 'x' })] }]); + assert.equal(third.state.sink, null); +}); + +test('install: an adapter or engine that throws leaves the site\'s value', () => { + const { win } = fakeWindow(); + const broken: CatalogHookAdapter = { catalog: 'web', install: () => { throw new Error('boom'); } }; + assert.doesNotThrow(() => installStringPacks(win, [{ adapter: broken, inventory: INVENTORY, packs: [pack({ a0000001: 'Hoom' })] }]).dispose()); +}); + +// ------------------------------------------------------------------------------------------- +// The DOM safety net (a minimal document: text nodes, elements, attributes) + +type FakeNode = { nodeType: number; nodeValue: string | null; parentElement: FakeElement | null }; +class FakeElement { + nodeType = 1; + nodeValue = null; + parentElement: FakeElement | null = null; + children: (FakeElement | FakeNode)[] = []; + attrs = new Map(); + tag: string; + constructor(tag: string, attrs: Record = {}) { this.tag = tag; for (const [k, v] of Object.entries(attrs)) this.attrs.set(k, v); } + add(child: T): T { child.parentElement = this; this.children.push(child); return child; } + text(value: string): FakeNode { return this.add({ nodeType: 3, nodeValue: value, parentElement: null }); } + getAttribute(name: string) { return this.attrs.get(name) ?? null; } + setAttribute(name: string, value: string) { this.attrs.set(name, value); } + hasAttribute(name: string) { return this.attrs.has(name); } + closest(selector: string): FakeElement | null { + const tags = selector.split(',').map(part => part.trim()); + for (let el: FakeElement | null = this; el; el = el.parentElement) if (tags.includes(el.tag)) return el; + return null; + } + all(): FakeElement[] { return this.children.flatMap(child => (child instanceof FakeElement ? [child, ...child.all()] : [])); } + querySelectorAll(selector: string) { const name = selector.slice(1, -1); return this.all().filter(el => el.attrs.has(name)); } + textNodes(): FakeNode[] { return this.children.flatMap(child => (child instanceof FakeElement ? child.textNodes() : [child])); } +} +function fakeDocument() { + const root = new FakeElement('html'); + let callback: (records: unknown[]) => void = () => {}; + let observing = false; + const win = { + document: { + documentElement: root, + createTreeWalker(element: FakeElement) { + const nodes = element.textNodes(); + let index = -1; + return { get currentNode() { return nodes[index]; }, nextNode() { index += 1; return index < nodes.length; } }; + }, + querySelectorAll: (selector: string) => [...(root.attrs.has(selector.slice(1, -1)) ? [root] : []), ...root.querySelectorAll(selector)], + }, + MutationObserver: class { constructor(fn: (records: unknown[]) => void) { callback = fn; } observe() { observing = true; } disconnect() { observing = false; } }, + }; + return { root, win: win as unknown as Window, mutate: (records: unknown[]) => { if (observing) callback(records); } }; +} + +test('text net: exact texts and attributes are replaced once, rewritten nodes are looked at again, dispose restores', () => { + const { root, win, mutate } = fakeDocument(); + const nav = root.add(new FakeElement('nav', { 'aria-label': 'Trending' })); + const label = nav.text('Trending'); + const other = nav.text('Trending topics today'); + const script = root.add(new FakeElement('script')); + const code = script.text('Trending'); + const net = installTextNet(win, { map: new Map([['Trending', 'Trendish'], ['News', 'Newsish']]), skip: 'script' }); + assert.equal(label.nodeValue, 'Trendish'); + assert.equal(nav.getAttribute('aria-label'), 'Trendish'); + assert.equal(other.nodeValue, 'Trending topics today', 'only an exact text is a match'); + assert.equal(code.nodeValue, 'Trending', 'skipped elements are not touched'); + assert.equal(net.count(), 2); + // Our own writes come back as mutations: nothing changes further. + mutate([{ type: 'characterData', target: label }, { type: 'attributes', target: nav, attributeName: 'aria-label' }]); + assert.equal(label.nodeValue, 'Trendish'); + assert.equal(net.count(), 2); + // A node added later, and the site rewriting a node. + const added = new FakeElement('div', { title: 'News' }); + const news = added.text('News'); + root.add(added); + mutate([{ type: 'childList', addedNodes: [added] }]); + assert.equal(news.nodeValue, 'Newsish'); + assert.equal(added.getAttribute('title'), 'Newsish'); + label.nodeValue = 'News'; + mutate([{ type: 'characterData', target: label }]); + assert.equal(label.nodeValue, 'Newsish'); + label.nodeValue = 'Something of the site'; + mutate([{ type: 'characterData', target: label }]); + assert.equal(label.nodeValue, 'Something of the site'); + assert.equal(net.count(), 3); + net.dispose(); + assert.equal(news.nodeValue, 'News'); + assert.equal(added.getAttribute('title'), 'News'); + assert.equal(nav.getAttribute('aria-label'), 'Trending'); + assert.equal(label.nodeValue, 'Something of the site'); + assert.equal(net.count(), 0); + // Disposed: later mutations do nothing. + label.nodeValue = 'Trending'; + mutate([{ type: 'characterData', target: label }]); + assert.equal(label.nodeValue, 'Trending'); +}); diff --git a/packages/waybetter/README.md b/packages/waybetter/README.md index 06f0337..5d8c9c0 100644 --- a/packages/waybetter/README.md +++ b/packages/waybetter/README.md @@ -112,6 +112,7 @@ const Shell = createShell({ ...site, panel: { id: 'app', title: 'wayBetter', com - `waybetter store build --config store.config.mjs`: builds an app's part of the shared store folder (its items only, validated with the apps' own rules). - `waybetter store sign [--init] --key ` / `waybetter store verify --pub `: Ed25519 signature over the exact catalog bytes; any listed public key verifies (rotation). The private key is never printed or copied. +- `waybetter strings check [--inventory ] [--verbose]`: validates a string pack (data that replaces the wrapped site's own UI strings: `waybetter/runtime/stringPacks`, `waybetter/runtime/stringPackHook`, `waybetter/runtime/textNet`) against the site's string inventory and prints its coverage; the inventories otherwise come from `waybetter.strings.json` in the app's root. - `waybetter i18n check [--write] [--verbose] [locale…]`: checks an app's catalogs (and the framework's in the same languages) with the `waybetter/i18n/check` rules, bundled plugins' inline English and the generated files; `--write` regenerates `languages.json` and the native localization files (macOS, Linux). `waybetter i18n extract [--missing]`: keys the code looks up that English lacks, and English keys without a literal lookup. Both read `waybetter.i18n.json` in the app's root (`locales`, `sources`, `nativeSources`, `bundledPlugins`, `runtimeKeys`, `supported`, `native`; schema: `i18n-config.schema.json`). `supported` lists the languages in the supported tier; every other catalog gets `tier: "community"` in the generated `languages.json` (`languages.schema.json`), and an app resolves its automatic language choices only to supported ones (`createLanguage({ supported })`). - `waybetter release windows|macos`: signed native releases and the update manifest (`waybetter.release.json`). The Windows build runs path-free (below) and every artifact must pass the privacy scan before anything is copied or signed. - `waybetter build-env -- `: runs a build (`tauri build`, `cargo build`) so the binary holds none of the machine's paths: the home folder, the workspace, `CARGO_HOME`, `RUSTUP_HOME` and `CARGO_TARGET_DIR` become `/home`, `/src`, `/cargo`, `/rustup` and `/target` (`--remap-path-prefix` appended to the flags already in `RUSTFLAGS`/`CARGO_ENCODED_RUSTFLAGS`, `/PDBALTPATH` on MSVC; for C and C++ a build script compiles, `-ffile-prefix-map` on gcc and clang and, on MSVC, `/d1trimfile:` in `CL` and `/PDBALTPATH` in `LINK`, which reach the cc crate, CMake and MSBuild alike). Without a command it prints that environment (`--json`). diff --git a/packages/waybetter/bin/waybetter.mjs b/packages/waybetter/bin/waybetter.mjs index ee848fb..6d42ef9 100644 --- a/packages/waybetter/bin/waybetter.mjs +++ b/packages/waybetter/bin/waybetter.mjs @@ -2,13 +2,15 @@ // The `waybetter` command: `waybetter store build|sign|verify` (cli/store.mjs), // `waybetter release windows|macos` (cli/release.mjs), `waybetter i18n check|extract` // (cli/i18n.mjs), `waybetter privacy-scan` (cli/privacy.mjs) and `waybetter build-env` -// (cli/buildenv.mjs), `waybetter dev` (cli/dev.mjs: watchers + tauri dev). +// (cli/buildenv.mjs), `waybetter dev` (cli/dev.mjs: watchers + tauri dev), `waybetter strings check` +// (cli/strings.mjs). import { readFileSync } from 'node:fs'; import { BUILD_ENV_USAGE, buildEnvCommand } from '../cli/buildenv.mjs'; import { DEV_USAGE, devCommand } from '../cli/dev.mjs'; import { I18N_USAGE, i18nCommand } from '../cli/i18n.mjs'; import { PRIVACY_USAGE, privacyCommand } from '../cli/privacy.mjs'; import { STORE_USAGE, storeCommand } from '../cli/store.mjs'; +import { STRINGS_USAGE, stringsCommand } from '../cli/strings.mjs'; import { RELEASE_USAGE, releaseCommand } from '../cli/release.mjs'; const [area, ...rest] = process.argv.slice(2); @@ -19,6 +21,8 @@ try { await releaseCommand(rest); } else if (area === 'i18n') { process.exitCode = await i18nCommand(rest); + } else if (area === 'strings') { + process.exitCode = await stringsCommand(rest); } else if (area === 'privacy-scan') { process.exitCode = privacyCommand(rest); } else if (area === 'build-env') { @@ -28,7 +32,7 @@ try { } else if (area === '--version' || area === '-v') { console.log(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version); } else { - console.log(`${STORE_USAGE}\n\n${RELEASE_USAGE}\n\n${I18N_USAGE}\n\n${PRIVACY_USAGE}\n\n${BUILD_ENV_USAGE} + console.log(`${STORE_USAGE}\n\n${RELEASE_USAGE}\n\n${I18N_USAGE}\n\n${STRINGS_USAGE}\n\n${PRIVACY_USAGE}\n\n${BUILD_ENV_USAGE} ${DEV_USAGE}`); if (area && area !== '--help' && area !== '-h') process.exitCode = 1; diff --git a/packages/waybetter/cli/strings.mjs b/packages/waybetter/cli/strings.mjs new file mode 100644 index 0000000..9b6ce38 --- /dev/null +++ b/packages/waybetter/cli/strings.mjs @@ -0,0 +1,121 @@ +// `waybetter strings check`: a string pack against a site's string inventory, with the +// framework's rules (waybetter/runtime/stringPacks: the envelope, only inventory keys, parameter +// names, plural and select kinds, no markup) and its coverage. +// +// waybetter strings check pack.strings.json --inventory strings/x.web.inventory.json +// waybetter strings check pack.strings.json the inventory comes from the config +// waybetter strings check pack.strings.json --verbose list every key that was refused or unknown +// +// Config: waybetter.strings.json in the app's root (or --config ); paths are relative to it. +// +// { "inventories": ["strings/x.web.inventory.json"] } +// +// The pack names its site and catalog; the inventory with the same two is used. Exit 1 when the +// envelope is invalid, a value is refused or a key is unknown (none of those is ever applied). +import { existsSync, readFileSync } from 'node:fs'; +import { dirname, isAbsolute, relative, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +export const STRINGS_CONFIG_FILE = 'waybetter.strings.json'; + +export const STRINGS_USAGE = `Usage: + waybetter strings check [--inventory ] [--verbose] [--config ] + Validates a string pack against the site's string inventory and prints its coverage. + +Config: ${STRINGS_CONFIG_FILE} in the app's root (inventories).`; + +class StringsError extends Error {} + +const LISTED = 12; + +/** The pack rules: the framework's sources inside its repository, else the built package. */ +async function loadRules() { + const source = fileURLToPath(new URL('../../runtime/src/stringPacks.ts', import.meta.url)); + const built = fileURLToPath(new URL('../dist/runtime/stringPacks.js', import.meta.url)); + const file = existsSync(source) ? source : built; + if (!existsSync(file)) throw new StringsError('the string pack rules are not built (run the package build)'); + return import(pathToFileURL(file).href); +} + +function readJson(file, what) { + if (!existsSync(file)) throw new StringsError(`${what} not found: ${file}`); + try { + return JSON.parse(readFileSync(file, 'utf8')); + } catch (error) { + throw new StringsError(`${what} is not JSON: ${file} (${error instanceof Error ? error.message : error})`); + } +} + +/** The inventories a config lists, as absolute paths. */ +export function loadStringsConfig(cwd, file) { + const path = resolve(cwd, file ?? STRINGS_CONFIG_FILE); + if (!existsSync(path)) throw new StringsError(`${relative(cwd, path) || path} not found: pass --inventory (see \`waybetter strings --help\`)`); + const config = readJson(path, 'the config'); + if (!Array.isArray(config.inventories) || config.inventories.some(item => typeof item !== 'string')) throw new StringsError(`${relative(cwd, path)}: "inventories" must be a list of files`); + return { inventories: config.inventories.map(item => resolve(dirname(path), item)) }; +} + +const percent = (part, whole) => (whole ? `${(part / whole * 100).toFixed(part && part < whole / 1000 ? 2 : 1)}%` : 'n/a'); + +/** + * Checks one pack. `inventories` are inventory files; the one for the pack's site and catalog is + * used. Returns the lines to print, the number of errors and the compiled report. + */ +export async function checkPack(packFile, inventories, { verbose = false } = {}) { + const rules = await loadRules(); + const pack = readJson(packFile, 'the pack'); + const lines = []; + const issues = rules.checkPackShape(pack); + for (const issue of issues) lines.push(`${issue.level}: ${issue.message}`); + if (issues.some(issue => issue.level === 'error')) return { lines, errors: issues.filter(issue => issue.level === 'error').length, report: null, coverage: null }; + const loaded = inventories.map(file => ({ file, inventory: readJson(file, 'the inventory') })); + const match = loaded.find(item => item.inventory.site === pack.site && item.inventory.catalog === pack.catalog); + if (!match) throw new StringsError(`no inventory for ${pack.site}/${pack.catalog} (have: ${loaded.map(item => `${item.inventory.site}/${item.inventory.catalog}`).join(', ') || 'none'})`); + if (match.inventory.format !== 1 || typeof match.inventory.entries !== 'object') throw new StringsError(`${match.file} is not a string inventory`); + const compiled = rules.compilePack(pack, match.inventory); + const { report } = compiled; + const coverage = rules.coverage(match.inventory, compiled); + lines.push(`${pack.name} (${pack.language}) for ${pack.site}/${pack.catalog}, inventory build ${match.inventory.build ?? 'unknown'}`); + lines.push(`${report.total} strings: ${report.valid} valid, ${report.rejected.length} refused, ${report.unknown.length} unknown`); + const list = (items, render) => { + for (const item of verbose ? items : items.slice(0, LISTED)) lines.push(` ${render(item)}`); + if (!verbose && items.length > LISTED) lines.push(` … ${items.length - LISTED} more (--verbose lists all)`); + }; + if (report.rejected.length) { + lines.push('Refused (not applied, the site\'s text stays):'); + list(report.rejected, item => `${item.id}: ${item.reason}`); + } + if (report.unknown.length) { + lines.push('Unknown keys (not in the inventory, never applied):'); + list(report.unknown, id => id); + } + lines.push('Coverage:'); + for (const [group, numbers] of Object.entries(coverage)) { + lines.push(` ${group.padEnd(8)} ${numbers.translated} of ${numbers.translatable} translatable strings (${percent(numbers.translated, numbers.translatable)})${numbers.closed ? `; ${numbers.closed} not translatable yet (rich text, formatters)` : ''}`); + } + return { lines, errors: report.rejected.length + report.unknown.length, report, coverage }; +} + +export async function stringsCommand(args, { cwd = process.cwd(), log = console.log } = {}) { + const [action, ...rest] = args; + const value = flag => { + const at = rest.indexOf(flag); + if (at < 0) return undefined; + if (!rest[at + 1] || rest[at + 1].startsWith('--')) throw new StringsError(`${flag} needs a file`); + return rest[at + 1]; + }; + if (action === 'check') { + const inventory = value('--inventory'); + const config = value('--config'); + const taken = new Set([inventory, config].filter(Boolean)); + const [pack, ...extra] = rest.filter(arg => !arg.startsWith('--') && !taken.has(arg)); + if (!pack || extra.length) throw new StringsError('check needs one pack file'); + const at = file => (isAbsolute(file) ? file : resolve(cwd, file)); + const inventories = inventory ? [at(inventory)] : loadStringsConfig(cwd, config).inventories; + const result = await checkPack(at(pack), inventories, { verbose: rest.includes('--verbose') }); + for (const line of result.lines) log(line); + return result.errors ? 1 : 0; + } + log(STRINGS_USAGE); + return action && action !== '--help' && action !== '-h' ? 1 : 0; +} diff --git a/packages/waybetter/tests/strings-cli.test.mjs b/packages/waybetter/tests/strings-cli.test.mjs new file mode 100644 index 0000000..762e633 --- /dev/null +++ b/packages/waybetter/tests/strings-cli.test.mjs @@ -0,0 +1,80 @@ +// `waybetter strings check` on a small site inventory. +import assert from 'node:assert/strict'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { checkPack, loadStringsConfig, stringsCommand } from '../cli/strings.mjs'; + +const BIN = fileURLToPath(new URL('../bin/waybetter.mjs', import.meta.url)); +const json = (file, value) => writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`); + +/** An app folder: an inventory (2 texts, 1 plural message, 1 rich entry, 1 emoji name), a config, a pack. */ +function app(strings, extra = {}) { + const dir = mkdtempSync(join(tmpdir(), 'wb-strings-')); + json(join(dir, 'demo.web.inventory.json'), { format: 1, site: 'demo', catalog: 'web', base: 'en', build: 'b7', entries: { + a0000001: { kind: 'text', hash: '00000000001' }, + a0000002: { kind: 'text', hash: '00000000002' }, + b0000001: { kind: 'message', params: ['count'], plural: ['count'], hash: '00000000003' }, + c0000001: { kind: 'rich', hash: '00000000004' }, + e0000001: { kind: 'text', group: 'emoji', hash: '00000000005' }, + } }); + json(join(dir, 'waybetter.strings.json'), { inventories: ['demo.web.inventory.json'] }); + json(join(dir, 'pack.json'), { format: 1, site: 'demo', catalog: 'web', language: 'en-x-test', name: 'Testish', authors: ['A tester'], strings, ...extra }); + return dir; +} + +test('check: a valid pack passes and prints its coverage per group', async () => { + const dir = app({ a0000001: 'Hoom', b0000001: '{count, plural, one {# postle} other {# postles}}' }); + const result = await checkPack(join(dir, 'pack.json'), [join(dir, 'demo.web.inventory.json')]); + assert.equal(result.errors, 0); + const text = result.lines.join('\n'); + assert.match(text, /Testish \(en-x-test\) for demo\/web, inventory build b7/); + assert.match(text, /2 strings: 2 valid, 0 refused, 0 unknown/); + assert.match(text, /all\s+2 of 4 translatable strings \(50\.0%\); 1 not translatable yet/); + assert.match(text, /main\s+2 of 3 translatable strings/); + assert.match(text, /emoji\s+0 of 1 translatable strings \(0\.0%\)/); + assert.deepEqual(result.coverage.all, { translatable: 4, translated: 2, closed: 1 }); +}); + +test('check: unknown keys and refused values are errors, listed with the reason', async () => { + const dir = app({ a0000001: 'Hoom', b0000001: '{total} postles', c0000001: 'Rich', zzzzzzzz: 'Nope', a0000002: 'Fine' }); + const lines = []; + const code = await stringsCommand(['check', 'pack.json'], { cwd: dir, log: line => lines.push(line) }); + assert.equal(code, 1); + const text = lines.join('\n'); + assert.match(text, /5 strings: 1 valid, 3 refused, 1 unknown/); + assert.match(text, /a0000001: markup is not allowed/); + assert.match(text, /b0000001: \{total\} is not a parameter of the original \(it has: count\)/); + assert.match(text, /c0000001: not translatable yet \(rich\)/); + assert.match(text, /Unknown keys[^\n]*\n\s+zzzzzzzz/); +}); + +test('check: an invalid envelope stops before the inventory; a pack for another catalog has no inventory', async () => { + const dir = app({}, { language: 'not a tag', format: 3 }); + const result = await checkPack(join(dir, 'pack.json'), [join(dir, 'demo.web.inventory.json')]); + assert.equal(result.errors, 2); + assert.equal(result.report, null); + const other = app({ a0000001: 'x' }, { catalog: 'guest' }); + await assert.rejects(stringsCommand(['check', 'pack.json'], { cwd: other, log() {} }), /no inventory for demo\/guest \(have: demo\/web\)/); +}); + +test('command: the config, --inventory, usage and the binary', async () => { + const dir = app({ a0000001: 'Hoom' }); + assert.deepEqual(loadStringsConfig(dir).inventories, [join(dir, 'demo.web.inventory.json')]); + assert.throws(() => loadStringsConfig(tmpdir(), 'nope.json'), /pass --inventory/); + const lines = []; + assert.equal(await stringsCommand(['check', 'pack.json', '--inventory', 'demo.web.inventory.json'], { cwd: dir, log: line => lines.push(line) }), 0); + assert.equal(await stringsCommand([], { log: line => lines.push(line) }), 0); + assert.equal(await stringsCommand(['nope'], { log() {} }), 1); + await assert.rejects(stringsCommand(['check'], { cwd: dir, log() {} }), /one pack file/); + await assert.rejects(stringsCommand(['check', 'pack.json', '--inventory'], { cwd: dir, log() {} }), /--inventory needs a file/); + const out = execFileSync(process.execPath, [BIN, 'strings', 'check', 'pack.json'], { cwd: dir, encoding: 'utf8' }); + assert.match(out, /1 strings: 1 valid/); + const bad = app({ zzzzzzzz: 'x' }); + const run = spawnSync(process.execPath, [BIN, 'strings', 'check', 'pack.json'], { cwd: bad, encoding: 'utf8' }); + assert.equal(run.status, 1); + assert.match(execFileSync(process.execPath, [BIN, '--help'], { encoding: 'utf8' }), /waybetter strings check/); +}); From 2f126659f9d67c6c366e09c9775c1a767971ac6a Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 30 Sep 2026 22:54:51 +0700 Subject: [PATCH 19/72] App menu: "Check for updates" is a real check, once, now, and says what came of it calmly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Host: `updater::check_now` runs the same check the timer runs (the same updater endpoint, nothing else) for the app's shell-only `update_check`. It never queues or retries: while a check is in flight (the timer's or an earlier request's), or within 10 seconds of the last request, it only answers with the current status (`update::may_check_now`, tested). The timer's loop uses the same single-flight guard. Frame: the menu's Updates row is that check (`updateRow`, tested): "Checking…", "Up to date · ", "Downloading …", "Restart to update" when an update is ready (the row then installs it), and "Could not check" with a plain sentence as its tooltip when the server does not answer. The updater's error text is never shown there, and a failure is only mentioned when the owner asked for the check in this menu; the timer's own failures stay quiet. Co-Authored-By: Claude Opus 5.5 --- crates/waybetter-host/src/update.rs | 20 +++++++++ crates/waybetter-host/src/updater.rs | 45 +++++++++++++++++-- packages/shell/src/frame/AppMenu.tsx | 39 ++++++++++++++-- packages/shell/src/frame/menuMessages.en.json | 11 ++++- packages/shell/src/frame/menuModel.ts | 37 +++++++++++++++ packages/shell/tests/menu.test.ts | 19 +++++++- 6 files changed, 162 insertions(+), 9 deletions(-) diff --git a/crates/waybetter-host/src/update.rs b/crates/waybetter-host/src/update.rs index 86123f0..504f206 100644 --- a/crates/waybetter-host/src/update.rs +++ b/crates/waybetter-host/src/update.rs @@ -14,6 +14,16 @@ pub const READY_DEADLINE: Duration = Duration::from_secs(30); /// Launches of an updated version without `app_ready` before automatic apply is disabled. pub const MAX_FAILED_BOOTS: u32 = 2; pub const PENDING_FILE: &str = "update-pending.json"; +/// Least time between two checks the owner asks for ("Check for updates"): a row clicked again +/// and again asks the server once. +pub const MANUAL_CHECK_GAP: Duration = Duration::from_secs(10); + +/// Whether a check the owner asked for may start: never while one is in flight (the timer's or +/// an earlier request's), and not within [`MANUAL_CHECK_GAP`] of the last request. A refused +/// request answers with the current status; nothing is queued and nothing retries. +pub fn may_check_now(in_flight: bool, since_last_request: Option) -> bool { + !in_flight && since_last_request.is_none_or(|elapsed| elapsed >= MANUAL_CHECK_GAP) +} /// Wait before the next check: 30 min +/- 5 min, from any 64-bit entropy value. pub fn next_check_delay(entropy: u64) -> Duration { @@ -76,6 +86,16 @@ pub fn on_boot(pending: Option, current_version: &str) -> BootDec mod tests { use super::*; + #[test] + fn a_requested_check_runs_once_and_never_piles_up() { + assert!(may_check_now(false, None), "the first request checks"); + assert!(!may_check_now(true, None), "not while the timer's check is in flight"); + assert!(!may_check_now(true, Some(Duration::from_secs(3600)))); + assert!(!may_check_now(false, Some(Duration::from_secs(2))), "a row clicked again asks the server once"); + assert!(may_check_now(false, Some(MANUAL_CHECK_GAP))); + assert!(may_check_now(false, Some(Duration::from_secs(60)))); + } + #[test] fn delay_stays_within_jitter() { for entropy in [0, 1, 300, 600, 601, u64::MAX] { diff --git a/crates/waybetter-host/src/updater.rs b/crates/waybetter-host/src/updater.rs index d80ac1b..dc6f0e8 100644 --- a/crates/waybetter-host/src/updater.rs +++ b/crates/waybetter-host/src/updater.rs @@ -4,8 +4,8 @@ //! its verification are [`crate::hotfix`]. //! //! The app registers the updater plugin, calls [`init`] from `setup` with its [`UpdaterConfig`], -//! and wraps [`status`], [`apply`] and [`ready`] in its own shell-only commands; its shell gets an -//! `update-status` event. Site tabs get no updater IPC at all, only verified hotfix data +//! and wraps [`status`], [`apply`], [`ready`] and [`check_now`] in its own shell-only commands; its +//! shell gets an `update-status` event. Site tabs get no updater IPC at all, only verified hotfix data //! ([`hotfix_script`]). use crate::hotfix::{self, Hotfix, Outcome}; @@ -49,6 +49,10 @@ struct Inner { hotfix: Option, /// Automatic apply is off after repeated failed starts of an update. problem: bool, + /// A check is running (the timer's or one the owner asked for): a second one never starts beside it. + checking: bool, + /// When the owner last asked for a check ([`check_now`]). + asked: Option, } struct UpdateState { @@ -111,13 +115,48 @@ pub fn init(app: &AppHandle, config: &'static UpdaterConfig) { tauri::async_runtime::spawn(async move { tokio::time::sleep(update::FIRST_CHECK).await; loop { - check_native(&app).await; + check_once(&app).await; check_hotfix(&app).await; tokio::time::sleep(update::next_check_delay(entropy())).await; } }); } +/// One native check, unless one is already running. +async fn check_once(app: &AppHandle) { + { + let state = app.state::(); + let Ok(mut inner) = state.inner.lock() else { return }; + if inner.checking { + return; + } + inner.checking = true; + } + check_native(app).await; + if let Ok(mut inner) = app.state::().inner.lock() { + inner.checking = false; + } +} + +/// A check the owner asked for (the app's shell-only `update_check`, the app menu's "Check for +/// updates"): the same check the timer runs, once, now, against the same updater endpoint (no +/// other network destination). It never queues or retries: while a check is in flight, or within +/// [`update::MANUAL_CHECK_GAP`] of the last request, it only answers with the current status. +/// Returns the status once the check has finished (the shell also hears each step as events). +pub async fn check_now(app: &AppHandle) -> Result { + { + let state = app.try_state::().ok_or("UPDATE: state unavailable")?; + let mut inner = state.inner.lock().map_err(|_| "UPDATE: state unavailable")?; + let now = std::time::Instant::now(); + if !update::may_check_now(inner.checking, inner.asked.map(|asked| now.duration_since(asked))) { + return Ok(status_of(state.config, &inner)); + } + inner.asked = Some(now); + } + check_once(app).await; + status(app) +} + async fn check_native(app: &AppHandle) { { let state = app.state::(); diff --git a/packages/shell/src/frame/AppMenu.tsx b/packages/shell/src/frame/AppMenu.tsx index 180884d..634146b 100644 --- a/packages/shell/src/frame/AppMenu.tsx +++ b/packages/shell/src/frame/AppMenu.tsx @@ -13,14 +13,15 @@ import { useEffect, useLayoutEffect, useReducer, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react'; import { createPortal } from 'react-dom'; -import { invoke } from './bridge.ts'; +import { parseUpdateStatus, type UpdateStatus } from '../updateModel.ts'; +import { invoke, listen } from './bridge.ts'; import { decks } from './deckStore.ts'; import { refreshDev } from './devHost.ts'; import { useDev, usePaneTick, useT } from './hooks.ts'; import { formatNumber } from './i18n.ts'; import { Icon, type IconName } from './icons.tsx'; import { - DEFAULT_MENU, ZOOM_MAX, ZOOM_MIN, findSpec, joinGroups, languageChoice, languageRows, menuText, moveStop, planMenu, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, + DEFAULT_MENU, ZOOM_MAX, ZOOM_MIN, findSpec, joinGroups, languageChoice, languageRows, menuText, moveStop, planMenu, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, updateRow, type BuiltinMenuItem, type MenuEnv, type MenuItemRow, type MenuRow, } from './menuModel.ts'; import { hasFeature, site } from './site.ts'; @@ -77,6 +78,8 @@ export function AppMenu() { const [mode, setMode] = useState(null); const [asking, setAsking] = useState<{ to: string; changes: number } | null>(null); const [version, setVersion] = useState(''); + const [update, setUpdate] = useState({ state: 'idle' }); + const [askedUpdate, setAskedUpdate] = useState(false); const [error, setError] = useState(''); const [, tick] = useReducer((n: number) => n + 1, 0); const button = useRef(null); @@ -121,6 +124,8 @@ export function AppMenu() { void config.themes?.loadThemes(); menu.modes?.current().then(setMode, () => {}); if (!version) menu.version?.().then(setVersion, () => {}); + setAskedUpdate(false); + if (hasFeature('updates')) invoke('update_status').then(value => setUpdate(parseUpdateStatus(value)), () => {}); } /** `escape`: back to what had focus before. `action` and `away`: nothing focused, so typing returns to the active pane. */ @@ -133,6 +138,17 @@ export function AppMenu() { before.current = null; } + // The updater's steps (checking, downloading, ready) as they happen. + useEffect(() => { + if (!hasFeature('updates')) return; + let disposed = false; + let unlisten: (() => void) | undefined; + listen('update-status', event => setUpdate(parseUpdateStatus(event.payload))) + .then(dispose => { if (disposed) dispose(); else unlisten = dispose; }) + .catch(() => {}); + return () => { disposed = true; unlisten?.(); }; + }, []); + useEffect(() => { const onRequest = (event: Event) => { const request = (event as CustomEvent).detail ?? {}; @@ -269,7 +285,22 @@ export function AppMenu() { case 'shortcuts': return item(id, menuText('shortcuts'), 'keyboard', { run: () => (menu.shortcuts ? menu.shortcuts() : shell.shortcut('command-palette')) }); case 'palette': return item(id, menuText('palette'), 'command', { shortcut: 'Ctrl+K', run: () => shell.shortcut('command-palette') }); case 'developer': return item(id, menuText('developer'), 'code', { submenu: true }); - case 'updates': return item(id, section(t('wb.panel.section.updates')), 'reload', { hint: version || undefined, run: () => shell.openPanelSection('updates') }); + case 'updates': { + // A real check: the row asks the updater now and says what came of it (the titlebar chip stays the loud part). + const row = updateRow(update, askedUpdate, version); + return item(id, row.label, 'reload', { + hint: row.hint, title: row.title, keepOpen: row.action === 'check' || row.action === 'wait', + run: async () => { + if (row.action === 'open') { shell.openPanelSection('updates'); return; } + if (row.action === 'restart') { await invoke('apply_update'); return; } + if (row.action !== 'check') return; + setAskedUpdate(true); + setUpdate({ state: 'checking' }); + // One request, no retry: whatever the updater answers is what the row says. + try { setUpdate(parseUpdateStatus(await invoke('update_check'))); } catch { setUpdate({ state: 'error', message: '' }); } + }, + }); + } case 'about': return item(id, menuText('about', { product: config.product }), 'info', { run: () => shell.openPanelSection('home') }); case 'settings': return item(id, section(t('wb.panel.section.settings')), 'settings', { run: () => shell.openPanelSection('settings') }); } @@ -442,7 +473,7 @@ export function AppMenu() { ; } const expanded = row.submenu ? path[level] === row.id : undefined; - return ; +} + /** The page zoom of the pane in front, only while it is not 100% (Ctrl with + and - say nothing else); a click resets it. */ function ZoomChip() { useT(); diff --git a/packages/shell/src/frame/appMenu.css b/packages/shell/src/frame/appMenu.css index 62b57df..7922f9f 100644 --- a/packages/shell/src/frame/appMenu.css +++ b/packages/shell/src/frame/appMenu.css @@ -90,3 +90,12 @@ /* The titlebar's zoom chip: only while the pane in front is not at 100% (TitlebarExtras.tsx). */ .bt-zoom-chip { font-family: var(--bt-mono); font-size: 11.5px; font-variant-numeric: tabular-nums; } .bt-zoom-chip .bt-glyph { color: var(--bt-muted); } + +/* Safe mode, said in the titlebar for as long as it is on (TitlebarExtras.tsx): amber, and one click leaves it. */ +.bt-safe-chip { border-color: rgba(245, 158, 11, .38); background: rgba(245, 158, 11, .1); color: var(--bt-text); font-weight: 600; } +.bt-safe-chip:hover { border-color: rgba(245, 158, 11, .6); background: rgba(245, 158, 11, .16); } +.bt-safe-chip .bt-glyph { color: #f59e0b; } +.bt-safe-leave { margin-inline-start: 2px; padding-inline-start: 9px; border-inline-start: 1px solid rgba(245, 158, 11, .35); color: var(--bt-text-2); font-weight: 500; } +.bt-safe-chip:hover .bt-safe-leave { color: var(--bt-text); } +.bt-safe-chip:disabled { opacity: .6; cursor: default; } +.bt-app-sub .bt-app-note { max-width: 300px; } diff --git a/packages/shell/src/frame/icons.tsx b/packages/shell/src/frame/icons.tsx index fe3a659..37ba9a9 100644 --- a/packages/shell/src/frame/icons.tsx +++ b/packages/shell/src/frame/icons.tsx @@ -51,6 +51,7 @@ export const ICONS = { code: 'M9 8l-4 4 4 4M15 8l4 4-4 4', folder: 'M4 7h6l2 2h8v10H4z', info: 'M12 21a9 9 0 1 1 0-18 9 9 0 0 1 0 18zM12 11v5M12 8h.01', + shield: 'M12 3l7 3v5.5c0 4.2-2.9 7.9-7 9.5-4.1-1.6-7-5.3-7-9.5V6z', } as const; export type IconName = keyof typeof ICONS; diff --git a/packages/shell/src/frame/menuMessages.en.json b/packages/shell/src/frame/menuMessages.en.json index 204ae39..62d4eed 100644 --- a/packages/shell/src/frame/menuMessages.en.json +++ b/packages/shell/src/frame/menuMessages.en.json @@ -36,5 +36,13 @@ "wb.menu.updateInstalling": "Installing {version}…", "wb.menu.updateRestart": "Restart to update", "wb.menu.updateFailed": "Could not check", - "wb.menu.updateFailedHint": "The update server did not answer. Nothing is wrong with the app; it checks again later on its own." + "wb.menu.updateFailedHint": "The update server did not answer. Nothing is wrong with the app; it checks again later on its own.", + "wb.menu.safe": "Safe mode", + "wb.menu.safeRestart": "Restart in safe mode…", + "wb.menu.safeQuestion": "Restart the tabs in safe mode?", + "wb.menu.safeExplain": "Every tab loads again with plugins, themes, custom CSS and page features off, for this run only. Your setup is back the next time you start the app.", + "wb.menu.safeConfirm": "Restart tabs in safe mode", + "wb.menu.safeLeave": "Leave safe mode", + "wb.menu.safeLeaveShort": "Leave", + "wb.menu.safeChip": "Safe mode is on: plugins, themes, custom CSS and page features are off for this run. Click to leave; the tabs load again with your setup." } diff --git a/packages/shell/src/frame/menuModel.ts b/packages/shell/src/frame/menuModel.ts index e07ff5f..f3f8ee8 100644 --- a/packages/shell/src/frame/menuModel.ts +++ b/packages/shell/src/frame/menuModel.ts @@ -36,7 +36,7 @@ export const MENU_BUILTINS = [ 'zoom', 'plugins', 'store', 'workspaces', 'find', 'shortcuts', 'palette', - 'developer', 'updates', 'about', 'settings', + 'developer', 'updates', 'safe-mode', 'about', 'settings', ] as const; export type BuiltinMenuItem = typeof MENU_BUILTINS[number]; @@ -110,7 +110,7 @@ export const DEFAULT_MENU: MenuGroups = [ ['zoom'], ['plugins', 'store', 'workspaces'], ['find', 'shortcuts', 'palette'], - ['developer', 'updates', 'about', 'settings'], + ['developer', 'updates', 'safe-mode', 'about', 'settings'], ]; const entryId = (entry: MenuEntry) => (typeof entry === 'string' ? entry : entry.id); @@ -146,6 +146,8 @@ export type MenuEnv = { /** `features`: native page zoom (`tab_zoom`), find in page (`tab_find`), the Store, workspaces, developer mode, the updater. */ zoom: boolean; find: boolean; + /** `features.safeMode`: safe mode for one run (`safe_mode_get/set`, the host's own). */ + safeMode: boolean; store: boolean; workspaces: boolean; developer: boolean; @@ -161,6 +163,7 @@ export function builtinAvailable(id: BuiltinMenuItem, env: MenuEnv): boolean { case 'mode': return env.modes; case 'zoom': return env.zoom; case 'find': return env.find; + case 'safe-mode': return env.safeMode; case 'store': return env.store; case 'workspaces': return env.workspaces; case 'developer': return env.developer; diff --git a/packages/shell/src/frame/safeStore.ts b/packages/shell/src/frame/safeStore.ts new file mode 100644 index 0000000..f282dbf --- /dev/null +++ b/packages/shell/src/frame/safeStore.ts @@ -0,0 +1,36 @@ +// Safe mode, as the shell knows it. Native code owns the flag (waybetter-host `safe.rs`: memory +// only, for this run; site tabs get the tab bridge and nothing of the app's page layers). The +// shell reads it at start (`safe_mode_get`), switches it from the app menu and the titlebar chip +// (`safe_mode_set`, which rebuilds every tab), hears a switch as the `safe-mode` event, shows it in +// the titlebar for as long as it is on and drops its own chrome theme meanwhile (themeStore.ts). + +import { invoke, listen } from './bridge.ts'; + +export const safe = { active: false }; + +function note(active: unknown) { + const next = active === true; + if (typeof document !== 'undefined') { + if (next) document.documentElement.dataset.safe = 'on'; else delete document.documentElement.dataset.safe; + } + if (safe.active === next) return; + safe.active = next; + window.dispatchEvent(new CustomEvent('bt-safe')); +} + +/** Switches safe mode for this run; every tab is rebuilt with or without the app's page layers. */ +export async function setSafeMode(on: boolean): Promise { + const state = await invoke<{ active?: boolean }>('safe_mode_set', { on }); + note(state?.active); +} + +/** Reads the flag and follows its changes (Shell.tsx, once). Returns a cleanup. */ +export function installSafeMode(): () => void { + let disposed = false; + let unlisten: (() => void) | undefined; + invoke<{ active?: boolean }>('safe_mode_get').then(state => { if (!disposed) note(state?.active); }).catch(() => {}); + listen<{ active?: boolean }>('safe-mode', ({ payload }) => note(payload?.active)) + .then(dispose => { if (disposed) dispose(); else unlisten = dispose; }) + .catch(() => {}); + return () => { disposed = true; unlisten?.(); }; +} diff --git a/packages/shell/src/frame/site.ts b/packages/shell/src/frame/site.ts index d9e6090..12e9684 100644 --- a/packages/shell/src/frame/site.ts +++ b/packages/shell/src/frame/site.ts @@ -147,11 +147,11 @@ export type ShellSite = { /** * Native features the app serves (waybetter-host modules it wires up): workspaces (`workspaces_*`), * encrypted folder sync (`sync_*`), developer mode (`dev_*`), plugin palette commands - * (`tab_run_command`), page zoom and find in page (`tab_zoom`, `tab_find`: the host's own); and what its panel has that the + * (`tab_run_command`), page zoom, find in page and safe mode (`tab_zoom`, `tab_find`, `safe_mode_*`: the host's own); and what its panel has that the * app menu links to: the Store (`PanelSite.store`) and the updater (`PanelSite.updates`). Each is * on unless set to false; off, the frame shows nothing of it. */ - features?: { workspaces?: boolean; sync?: boolean; developer?: boolean; pluginCommands?: boolean; zoom?: boolean; find?: boolean; store?: boolean; updates?: boolean }; + features?: { workspaces?: boolean; sync?: boolean; developer?: boolean; pluginCommands?: boolean; zoom?: boolean; find?: boolean; safeMode?: boolean; store?: boolean; updates?: boolean }; /** * The app menu (the titlebar's "Settings and more", Alt+F / F10): its rows in order (built-in * ones by name, the app's own as objects) and what the Language and Mode submenus need. Omit for diff --git a/packages/shell/src/frame/state.ts b/packages/shell/src/frame/state.ts index 7663026..a1f04b4 100644 --- a/packages/shell/src/frame/state.ts +++ b/packages/shell/src/frame/state.ts @@ -102,6 +102,12 @@ export function scheduleSync() { frame = requestAnimationFrame(() => { frame = 0; void syncTabs(); }); } +/** Sends the layout again even though nothing moved: native code asked to build every tab webview anew (`tabs-rebuild`). */ +export function resync() { + lastPayload = ''; + scheduleSync(); +} + /** Sends the tab rectangles now (e.g. so native code knows closed tabs are gone before a profile removal). */ export function flushSync(): Promise { if (frame) { cancelAnimationFrame(frame); frame = 0; } diff --git a/packages/shell/src/frame/themeStore.ts b/packages/shell/src/frame/themeStore.ts index bb4ec98..cfbf279 100644 --- a/packages/shell/src/frame/themeStore.ts +++ b/packages/shell/src/frame/themeStore.ts @@ -10,6 +10,7 @@ import { BOOT_CACHE_KEY } from './boot.ts'; import { invoke } from './bridge.ts'; import { CHROME_VAR_NAMES, chromeVars, type ChromeTheme } from './chromeTheme.ts'; import { SCOPES_DEFAULT, normalizeScopes, prunePanes, themeIdFor, type ScopeSource, type ThemeScopes } from './themeScopes.ts'; +import { safe } from './safeStore.ts'; import { shell, type TabParams } from './state.ts'; export type Weights = { kind: 'range'; min: number; max: number } | { kind: 'list'; values: number[] }; @@ -193,7 +194,11 @@ export function createThemeStore(adapter: ThemeAd /** The chrome follows the global theme (or the editor's draft); panes with their own theme follow theirs. */ function applyChrome() { - if (typeof document === 'undefined' || !state.ready) return; + if (typeof document === 'undefined') return; + // Safe mode: the frame's own look, whatever the theme (a theme may be what broke the chrome). The + // first-frame cache is left alone, so the next normal start paints the owner's theme again. + if (safe.active) { setVars(document.documentElement, {}); syncGroups(); return; } + if (!state.ready) return; const own = state.scopes.chrome === 'own'; const global = state.preview ?? adapter.resolve(state.choice); chromeFontsFor(global); @@ -213,7 +218,7 @@ export function createThemeStore(adapter: ThemeAd for (const group of api.groups) { const params = group.activePanel?.params as TabParams | undefined; const tab = params && (params.kind === 'web' || params.kind === 'start') ? { id: params.kind === 'web' ? group.activePanel!.id : undefined, profile: params.profile ?? 'default' } : null; - const scoped = !own && !state.preview && tab ? tabTheme(tab) : null; + const scoped = !own && !safe.active && !state.preview && tab ? tabTheme(tab) : null; const element = group.element; if (scoped && scoped.source !== 'global') { chromeFontsFor(scoped.theme); @@ -228,6 +233,9 @@ export function createThemeStore(adapter: ThemeAd } } + // Safe mode switched: the chrome drops (or takes back) the theme at once. + if (typeof window !== 'undefined') window.addEventListener('bt-safe', applyChrome); + /** Shell.tsx hands over the dock once it exists: pane chrome follows focus and layout changes. */ function attachDock(api: DockviewApi) { dock = api; diff --git a/packages/shell/tests/menu.test.ts b/packages/shell/tests/menu.test.ts index 261cc03..8dc6532 100644 --- a/packages/shell/tests/menu.test.ts +++ b/packages/shell/tests/menu.test.ts @@ -15,8 +15,8 @@ import { import { buildItems } from '../src/frame/paletteModel.ts'; const here = dirname(fileURLToPath(import.meta.url)); -const ALL: MenuEnv = { decks: true, languages: true, themes: true, modes: true, zoom: true, find: true, store: true, workspaces: true, developer: true, updates: true }; -const NONE: MenuEnv = { decks: false, languages: false, themes: false, modes: false, zoom: false, find: false, store: false, workspaces: false, developer: false, updates: false }; +const ALL: MenuEnv = { decks: true, languages: true, themes: true, modes: true, zoom: true, find: true, safeMode: true, store: true, workspaces: true, developer: true, updates: true }; +const NONE: MenuEnv = { decks: false, languages: false, themes: false, modes: false, zoom: false, find: false, safeMode: false, store: false, workspaces: false, developer: false, updates: false }; const ids = (groups: ReturnType) => groups.map(group => group.map(entry => (typeof entry === 'string' ? entry : entry.id))); const items = (rows: MenuRow[]) => rows.filter((row): row is MenuItemRow => row.kind === 'item'); @@ -35,7 +35,7 @@ test('a row the app cannot serve is left out, and a group left empty takes its r ]); // Each gate is its own. const gates: Array<[keyof MenuEnv, string]> = [ - ['decks', 'new-column'], ['languages', 'language'], ['themes', 'theme'], ['modes', 'mode'], ['zoom', 'zoom'], ['find', 'find'], + ['decks', 'new-column'], ['languages', 'language'], ['themes', 'theme'], ['modes', 'mode'], ['zoom', 'zoom'], ['find', 'find'], ['safeMode', 'safe-mode'], ['store', 'store'], ['workspaces', 'workspaces'], ['developer', 'developer'], ['updates', 'updates'], ]; for (const [feature, row] of gates) { @@ -63,7 +63,7 @@ test('an app orders, removes and adds rows; its own rows follow their `when`', ( assert.equal(ids(planMenu(groups, ALL)).flat().includes('drafts'), false); drafts = true; assert.deepEqual(ids(planMenu(menuWithout(groups, 'store', 'zoom', 'drafts'), ALL)), [ - ['new-tab', 'split-right', 'split-down', 'new-column'], ['language', 'theme', 'mode'], ['plugins', 'workspaces'], ['find', 'shortcuts', 'palette'], ['developer', 'updates', 'about', 'settings'], + ['new-tab', 'split-right', 'split-down', 'new-column'], ['language', 'theme', 'mode'], ['plugins', 'workspaces'], ['find', 'shortcuts', 'palette'], ['developer', 'updates', 'safe-mode', 'about', 'settings'], ]); // Explicit order; a row listed twice shows once; an unknown name and an own row named like a built-in are ignored. const custom: MenuGroups = [['settings', 'new-tab', 'settings', 'nope' as never], [{ id: 'zoom', label: () => 'Fake zoom' }, own]]; From 593ce46bd7f4df3735d756cec9be0c925b16f8a8 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 30 Sep 2026 23:20:58 +0700 Subject: [PATCH 23/72] READMEs for strangers: overview, three layers, a real minimal adapter, security model; the long reference moves to docs/ARCHITECTURE.md Co-Authored-By: Claude Opus 5.5 --- README.md | 652 ++++++---------------------- docs/ARCHITECTURE.md | 557 ++++++++++++++++++++++++ packages/create-waybetter/README.md | 12 +- packages/shell/README.md | 4 +- packages/waybetter/README.md | 10 +- 5 files changed, 717 insertions(+), 518 deletions(-) create mode 100644 docs/ARCHITECTURE.md diff --git a/README.md b/README.md index 058c664..7d0708e 100644 --- a/README.md +++ b/README.md @@ -1,294 +1,56 @@ # waybetter -The framework behind the wayBetter apps: apps that extend the apps you already use in place, the -way BetterDiscord extends Discord. The first app is **wayBetter for X**; more are being built on -the same core. - -```sh -npm install waybetter -``` - -[npm](https://www.npmjs.com/package/waybetter) · [waybetter.fyi](https://waybetter.fyi) - -A wayBetter app is one native window (Tauri 2, multiwebview) with: - -- a trusted local **shell** webview: tab strip, split panes (dockview), address bar, titlebar and - window controls, command palette, account switcher, the app's own settings; -- one native child webview per browser **tab**, positioned over the pane rectangles the shell - reports (`tabs_sync`), each in an account **profile** with its own WebView data directory; -- a **page runtime** injected into tabs that are on the app's site: shared DOM/request hubs, - plugins, themes, split-view rail hiding, link routing and account reporting. - -This repository holds the parts that do not depend on which site the app extends. An app is mostly -a **site adapter** plus its own features. - -## One system for every app - -Every wayBetter app is the same system: the Tauri window above (shell + page runtime) plus one -small adapter. That holds for websites like x.com and just as much for services that ship their -own Electron desktop client, such as WhatsApp or Discord: wayBetter runs their web app in its own -light Tauri window instead of the heavy client, and gives it the same tabs, split panes, real -accounts side by side, themes, plugins and signed updates. There is no second kind of host. +A framework for desktop apps that run one website (or a web app you would otherwise use through a +heavy Electron client) in a small native window and extend it in place, the way BetterDiscord +extends Discord. You get tabs, split panes, several signed-in accounts side by side, themes, +plugins, a signed store for them, backups and updates. You write a small adapter that says what +the site is. +The first app built on it is [wayBetter for X](https://git.crt.fyi/CRT/waybetter-for-x). License: GPL-3.0-or-later. -## Projects using wayBetter - -| Project | Target | What it is | -| --- | --- | --- | -| [wayBetter for X](https://waybetter.fyi/x/) | x.com (website) | Desktop app around the live X: tabs, split panes, real accounts side by side, themes, plugins, drafts and fixes for X's own bugs. The first wayBetter app. | - -Built something on wayBetter? Add it to this list with a pull request: name and link, what it extends, one line on what it does. - -## Build your own - ```sh -npm create waybetter plugin # a *.plugin.js (or --ts: a TypeScript project) on the real plugin API -npm create waybetter theme # a theme JSON with "$schema", a derived palette and font roles -npm create waybetter app -- --site kick.com # a whole app: Tauri 2 + waybetter-host + runtime + shell +npm install waybetter # page runtime, shell, CLI tools +npm create waybetter # scaffold a plugin, a theme or a whole app ``` -`create-waybetter` (in `packages/create-waybetter`) asks for what it needs in a terminal, and -takes every answer as a flag (`--help`). The app skeleton is this README in code: the native -`SiteSpec`, the page `SiteAdapter`, the app on `waybetter_host::app` (its config, site hooks and -its own commands), the three capability files and a `tests/security.rs` on `waybetter_host::testkit`, -the shell (the framework's shell frame through `createShell`, with the site's pages and a plugins -panel), the plugin store, one site-only command, the -runtime bundled with `waybetter/build` and a `waybetter.release.json` for `waybetter release`, with presets for -youtube.com, kick.com and twitch.tv and every site selector marked as a placeholder. Its tests -generate each kind into a temp folder and check it against the real contracts: plugin headers with -`plugins::parse_meta`, plugin code against `createCorePluginApi`'s members, themes against -`theme.schema.json`, the app's TypeScript with `tsc` against the built package and its Rust with -`cargo check`/`cargo test` against this crate. +Links: [source](https://git.crt.fyi/CRT/waybetter) · [npm](https://www.npmjs.com/package/waybetter) · [waybetter.fyi](https://waybetter.fyi) -## Layout +## The three layers -``` -crates/waybetter-host/ Rust: security policy, profiles, plugin store, hotfix, updates, tab payloads, - and the generic native features every app gets (below) - tab-bridge.js the tab bridge every tab gets (served by src/bridge.rs) - src/site.rs SiteSpec + AccountRules (the native half of the adapter) - src/policy.rs webview labels, origin checks, tab rect clamp - src/profiles.rs profiles, per-profile data dirs, native-owned accounts - src/plugins.rs *.plugin.js store, custom CSS, bundled-plugin upgrades - src/plugins/commands.rs palette commands site tabs report, and the script that runs one - src/settings.rs the shell's settings (home page, where links open, session restore) and the - page's feature flags, as validated data and the scripts that deliver them - src/hotfix.rs signed data-only hotfix channel (minisign) - src/update.rs silent-update scheduling and crash handshake - src/tabs.rs TabLayout/TabState/OpenRequest, link modes, shortcut and drag validation, - deck ColumnConfig bounds and unread caps - src/bridge.rs the tab bridge script (reports; shortcut/link-drag forwarding opt-in) - src/backup.rs settings backup envelope, secret scrubbing, plugin/account sections - src/sync.rs encrypted folder sync (Argon2id + XChaCha20-Poly1305 snapshots) - src/workspaces.rs saved tab/pane/deck layouts, bounded and well-formed - src/devmode.rs developer mode: debounced file watcher, reload order, error positions - src/alerts.rs keyword alerts: keywords, snippets, rate limits; native notifications - src/media.rs gallery folders (path containment), clipboard history, PNG encoding - src/media/clipboard.rs (feature "tauri") opt-in clipboard polling, private copies skipped - src/gfonts.rs self-hosted Google Fonts: CSS parsing, URL/woff2 checks, cache format - src/fonts.rs (feature "net") font downloads and the font cache - src/updater.rs (features "tauri" + "net") signed native updates and the hotfix channel - src/store/ install links, download allow-list, signed multi-app store catalog, staging - and installs; downloads with feature "net" (docs/STORE.md) - src/host.rs (feature "tauri") webview helpers, shell events, system menu - src/app.rs (feature "app") the whole app around a site: run_app / App, AppConfig, - SiteHooks, the window, shell and tab webviews, the generic commands - (tabs, profiles, language, plugins and custom CSS, feature flags, settings) - src/commands.rs the commands the host serves and who may call them; manifest() for build.rs - src/testkit.rs capability/caller-check assertions for an app's tests/security.rs -packages/runtime/src/ page runtime core (TypeScript, no dependencies) - site.ts SiteAdapter (the page half of the adapter) + configureRuntime - domHub.ts netHub.ts one MutationObserver/frame, one fetch/XHR hook per page - pluginApi.ts core of window..api for plugins (incl. ui and theme) - ui.ts plugin UI kit: toasts, alert/confirm/prompt, dialogs (shadow DOM, themed) - themeApi.ts the active theme as values + --wb-* CSS variables (api.theme) - themeTokens.ts OKLab color model: maps the site's palette onto a theme's axis - paneNav.ts split view: park the site's navigation rail in redundant panes - column.ts deck columns: hide site chrome, fill the width, filters, unread count - linkRouting.ts divert in-page clicks to a pane/tab/browser per setting - accountReport.ts report the signed-in account of this tab's profile - siteRuntime.ts the runtime's composition: the IPC bridge, flag-controlled parts with a deck - column's overrides, the runtime object under its window names, native queues - pageStrings.ts the page's language: English built in, native deliveries checked as data - stringPacks.ts string packs (docs/STRING-PACKS.md): pack and inventory formats, validator, - ordered engine, coverage, drift report - stringPackHook.ts the per-site catalog hook adapter, its self-check, a webpack chunk array hook - textNet.ts DOM safety net for labels no catalog hook reaches - panelButton.ts the way into the panel from the page (navigation entry or floating button) - commandReport.ts the palette command report and developer-mode start errors -packages/shell/src/ shell core (TypeScript) and the shell frame (React) - addressModel.ts address bar chips (site pages named by the adapter) - paneModel.ts beside-pane reuse, redundant rails, navRedundant for tabs_sync - deckModel.ts decks of site columns: bounded storage model, paging layout, focus - linkDrop.ts dropping links into the dock - profileModel.ts profiles and account labels - palette.ts command palette scoring/ranking - updateModel.ts titlebar update chip - windowControls.ts caption buttons, resize grips, system menu (Tauri API injected) - chrome.ts titlebar/toolbar/resize-border sizes (match policy.rs) - storeModel.ts storeMessages.ts Store wire types, item states, permission words; wb.store/install/permission.* - installController.ts the install screen's state machine (links, drops, store items, confirm) - InstallDialog.tsx StoreView.tsx store.css the install screen and the Store view (React peer, --wb-* tokens) - frame/ the shell frame: createShell(site) (see "The shell frame" below) - panel/ the panel: createPanel(site), the app's own tab (see "The panel" below) - installerMessages.ts the Windows installer's words (wb.installer.*) -packages/waybetter/ the published npm package (runtime + shell as ESM + .d.ts, theme.schema.json, - store-catalog.schema.json, the `waybetter store build|sign|verify`, - `waybetter release windows|macos`, `waybetter i18n check|extract`, - `waybetter privacy-scan` and `waybetter build-env` commands, `waybetter/build`, locales/ (51 catalogs and translator notes), - windows/ (the installer template and its language files)) -dev-tools/ development harnesses for a running or built app (perf probes, close and - stress checks); not published (dev-tools/README.md) -docs/STORE.md the Store: shared catalog format, signing and keys, tooling, trust model, how to add it -packages/create-waybetter/ `npm create waybetter`: plugin, theme and app scaffolds (no dependencies) -``` +A wayBetter app is one Tauri 2 window with several webviews. The framework has one piece for each +layer and does not need to know which site you wrap. -Both TypeScript packages are plain source (`.ts`, ESM, `type: module`) with no runtime -dependencies, so an app can bundle them with esbuild/Vite and run their tests with Node's type -stripping. Anything that needs the Tauri API (window controls, the shell frame) takes it as a -parameter. The React parts (the Store screens, the shell frame) have React, and the frame dockview, -as optional peers: the app's copies are used. +| Layer | Where | What it does | +| --- | --- | --- | +| Native host | `crates/waybetter-host` (Rust) | Builds the window, the trusted `shell` webview and one child webview per tab, keeps profiles (each with its own WebView data folder), the plugin store, settings, backups, encrypted sync, updates, fonts, the store install rules, and decides which webview may call which command. | +| Page runtime | `packages/runtime` (TypeScript, no dependencies) | Injected into tabs that are on the site's exact origin: one DOM hub and one fetch/XHR hub, the plugin API and its themed UI kit, the theme engine, split-view navigation, link routing, account reporting, deck columns, string packs. | +| Shell | `packages/shell` (TypeScript and React) | The local UI around the tabs: `createShell(site)` gives tabs in the titlebar, split panes, address bar, command palette, account switcher, decks and workspaces; `createPanel(site)` gives the app's own settings tab (appearance, theme builder, plugins, store, backup, developer mode). | -## The shell frame +Both TypeScript packages ship as the npm package `waybetter` (plain ESM with `.d.ts`). The Rust +crate is used from source, as a git submodule or a path dependency. Details of every module are in +[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md). -`packages/shell/src/frame` (`waybetter/shell/frame`) is the whole shell of a wayBetter app. An app -describes its site and gets tabs in the titlebar row, split panes and link drags into the dock, the -smart address bar, the new-tab page, the command palette, the account switcher, decks of site -columns, workspaces, the developer-mode and sync chips, the gallery/clipboard panel, pane themes, -its own panel tab, keyboard shortcuts, overlays that raise the shell above the tab webviews, the -one-layout-in-flight `tabs_sync` and session restore: +## A minimal adapter -```tsx -import { invoke } from '@tauri-apps/api/core'; // or window.__TAURI__ (withGlobalTauri) -import { listen } from '@tauri-apps/api/event'; -import { getCurrentWindow } from '@tauri-apps/api/window'; -import { createShell, type ShellSite } from 'waybetter/shell/frame'; +An adapter is three small things. This is what `npm create waybetter app` writes for `kick.com` +(selectors are placeholders you replace after looking at the real site). -const site: ShellSite = { name: 'Kick', product: 'wayBetter for Kick', homeUrl, loginUrl, logoutUrl, - isSiteUrl, accounts, searchUrl, address, panel: { id, title, component }, newTab, palette, - deck, media, themes, overlays, features, start }; -const Shell = createShell(site, { native: { invoke, listen, currentWindow: getCurrentWindow }, i18n }); -createRoot(root).render(); -``` - -What the site supplies (`frame/site.ts`, every field documented there): - -- names and pages: `name` (in messages as `{site}`), `product`, `logo`, `homeUrl`, `loginUrl`, - `logoutUrl`, `isSiteUrl`, the account rules, `searchUrl` for typed text; -- the address bar: `address(url)` (chips, usually `parseAddress` with an `AddressSite`) and an - optional `addressCompleter` (inline completions, e.g. search operators); -- slots: `panel` (the app's own tab and its sections), `newTab` (search label, quick links), - `palette` (placeholder, the literal search, completions, the panel's sections, the site's pages), - `deck` (column kinds with labels and icons, the page each loads, titles, value parsing and - completions, column flags and presets, an optional compose dock), `media` (which pages have a - composer), `themes` (a `createThemeStore(adapter)`: the app's theme documents, chrome colors via - `chromeVars`, pane themes), `overlays` (the app's own dialogs), `start()` (read site settings, - call `siteChanged()` when site text changes); -- `features`: the native features the app wires up (workspaces, sync, developer mode, plugin - palette commands); an app without them shows nothing of them. - -The frame's words are `wb.*` messages in the framework catalogs (51 languages; English source in -`frame/frameMessages.ts`): the app passes its i18n instance with the framework catalogs merged in. -Styles come with the components (dockview's, then `shell.css`, `deck.css`, `workspaces.css`, -`accountSwitcher.css`, `paneTheme.css`); colors are `--wb-c-*` tokens with Night Ink fallbacks, -set by the theme store (the chrome and each pane group) and cached for the first frame: -`bootScript()` (`frame/boot.ts`) is the `boot.js` an app serves before its modules (a Vite plugin or -a build step writes it). `installPreviewMocks(handlers)` answers native commands from memory, so -the real shell renders in a plain browser for development previews and screenshots. - -Native commands the frame calls: the host's (`tabs_sync`, `tab_navigate`, `tab_action`, -`shell_focus`, `shell_raise`, `open_external_url`, `window_system_menu`, `profiles_*`), and for the -features an app turns on `settings_get`, `column_configure`, `workspaces_*`, `sync_*`, `dev_*`, -`plugins_list`, `tab_run_command`, `media_get`/`gallery_*`/`clip_*`/`tab_attach_image`/ -`tab_insert_text`, `theme_scopes_*` and `gfonts_*`, `app_ready`/`update_status`/`apply_update`. It -listens to `tab-state`, `tab-open`, `tab-shortcut`, `link-drag`, `open-panel`, `profiles-changed`, -`tab-commands`, `dev-event`, `update-status`, `tab-still` and `clipboard-changed`. - -## The panel - -`packages/shell/src/panel` (`waybetter/shell/panel`) is an app's own tab in the shell: a home page, -Appearance (the theme gallery, customization, account and pane themes, downloaded fonts, theme -import/export) and the Theme Builder (undo/redo, a palette from three colors, a contrast report, a -font per role with the Google Fonts browser), plugins and custom CSS, the Store, Make (example -plugins, the plugin UI kit, the theme API, bundled docs), accounts, Power User (deck settings), -settings (language, links and session, keyword alerts, the media panel), backup and sync, developer -mode, updates, and a search across every setting. It lives in the shell package, next to the frame -it renders in: it uses the frame's stores (profiles, decks, themes, sync, developer mode), its -native bridge and its language, so `createShell` comes first. - -```tsx -import { createPanel, type PanelSite } from 'waybetter/shell/panel'; - -const panel: PanelSite = { brand: { name: 'wayBetter', logo }, home, themes, sections, order, make, - store, languages, settings, power, backup: true, updates: true }; -const Panel = createPanel(panel); -const Shell = createShell({ ...site, panel: { id: 'app', title: 'wayBetter', component: Panel } }, options); -``` - -What the app supplies (`panel/site.ts`, every field documented there): - -- `brand` and `home`: the header and the home page's words (kicker, title, lede, chips, actions, - highlight cards, the About block), `version()` for its chip; -- `sections` and `order`: its own sections (a label, an icon path, a component that gets `notify` - and `openSection`; `searchable` ones also show in the settings search), placed among the built-in - ones. X adds Tweaks and Drafts; -- `themes`: its theme store and catalog (`createThemeStore`, `createThemeCatalog`), accent swatches, - the **preview** component (a miniature of the site drawn from a theme document, used by the gallery - and the builder), the site font's name, the palette a draft starts from, and for Make's theme view - `resolved(choice, mode)` with the site's own display modes; -- `make`: example plugins, an example theme file and bundled Markdown docs; -- `store`: the install controller (the Store section, and removing a plugin from the list); -- `languages`: the language list and state (`createLanguage`, `frame/language.ts`); -- `settings`, `power`, `cssExamples`: keyword alerts, extra settings rows, which column flags and - which memory measure Power User lists, placeholder CSS with the site's selectors. - -A built-in section shows only when the app serves what it needs: Appearance, the Theme Builder and -the Store with `themes` (and `store`), Make with `make`, Power User with `site.deck`, backup with -`backup` (its sync half with the frame's `sync` feature), Developer with the frame's `developer` -feature, Updates with `updates`. An app with nothing but plugins gets Home, Plugins, Accounts and -Settings (this is what `npm create waybetter app` generates). - -Building blocks for the app's own sections: the panel's controls (`Section`, `Row`, `Toggle`, -`Segmented`, `Select`, `Slider`, `ColorField`, `Button`, `Badge`, ...; `panel/controls`), the -feature toggles (`useFeatures` + `FeatureGroups` over `features_get/set`: the app names its flags -and groups, its catalog has `features..label` and `.description`), and `compareLines`. - -The panel's words are `wb.*` messages too (English source in `panel/panelMessages.ts`, translator -notes in `locales/en.meta.json`). Three families of keys stay the app's, by convention, because -they name its own things: `plugin..name|description` (its bundled plugins), -`theme..description` (its built-in themes) and `features.*` (its tweaks). - -Native commands the panel calls: the host's `plugins_list`, `plugin_set_enabled`, -`plugins_open_folder`, `custom_css_get/set`, `features_get/set`, `settings_get/set`, -`profiles_*` and `open_external_url`, and for what the app turns on `alerts_get/set`, -`media_get/set`/`gallery_add_folder`/`clip_remove`, `backup_*`, `sync_*`, `dev_*`, the theme -store's commands and `gfonts_*`, `install_records`/`install_forget`/`plugin_remove`/`store_catalog`, -`app_ready`/`update_status`/`apply_update`. - -The Google Fonts list the font browser shows is an offline snapshot -(`panel/fonts/googleFontsCatalog.json`; `packages/shell/scripts/google-fonts-catalog.mjs` -regenerates it). The app never fetches the list, only the font files the owner picks (natively). - -## The site adapter - -A site adapter is three small, explicit things. - -### 1. Native: `SiteSpec` (Rust) +**1. Native: which webviews are site tabs, and what an account looks like** (`src-tauri/src/site.rs`) ```rust use waybetter_host::site::{AccountRules, SiteSpec}; -fn kick_handle(value: &str) -> bool { - (3..=25).contains(&value.len()) && value.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') +pub fn valid_handle(handle: &str) -> bool { + (3..=25).contains(&handle.len()) && handle.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') } pub static SITE: SiteSpec = SiteSpec { product: "wayBetter for Kick", - hosts: &["kick.com"], // exact https origin(s) of site tabs - runtime_global: "WayBetterKick", // window. of the page runtime + hosts: &["kick.com"], // exact https origin(s): the only definition of a site tab + runtime_global: "WayBetterForKick", // window. of the page runtime accounts: AccountRules { - valid_handle: kick_handle, + valid_handle, avatar_prefixes: &["https://files.kick.com/"], max_name_chars: 50, max_avatar_len: 512, @@ -296,269 +58,137 @@ pub static SITE: SiteSpec = SiteSpec { }; ``` -`SiteSpec::is_origin` is the only definition of "a site tab". Site-only commands check -`policy::require_site_tab(&SITE, label, url)` (or `host::site_tab_only`), which also requires a -`tab-*` label. - -### 2. Page: `SiteAdapter` (TypeScript) +**2. Page: what the runtime needs to know about the markup** (`src/site.ts`, shortened) ```ts -import { configureRuntime, type SiteAdapter } from 'waybetter/packages/runtime/src/site.ts'; +import type { SiteAdapter } from 'waybetter/runtime/site'; -export const KICK: SiteAdapter = { +export const SITE: SiteAdapter = { product: 'wayBetter for Kick', hosts: ['kick.com'], - runtimeGlobal: 'WayBetterKick', - heavyPath: null, // pages where offOnHeavy DOM features pause - apiMarks: ['/api/'], // request URLs the net hub stages may see + runtimeGlobal: 'WayBetterForKick', + heavyPath: null, + apiMarks: ['/api/'], // request URLs the net hub may inspect xhrMarks: [], - plugins: { name: 'WayBetterKick', product: 'wayBetter for Kick', storagePrefix: 'wbk-plugin:', - styleDataKey: 'wbkPlugin', toastId: 'wbk-toast', toastBackground: '#53fc18', + plugins: { name: 'WayBetterForKick', product: 'wayBetter for Kick', storagePrefix: 'wb-kick-plugin:', + styleDataKey: 'wbKickPlugin', toastId: 'wb-kick-ui', toastBackground: '#53fc18', itemSelector: '[data-chat-entry]', chordKeys: [] }, - rail: { prefix: 'wbk', rail: '#sidebar-wrapper', anchor: 'a[href="/"]', main: 'main', - modalOpen: '[role="dialog"]', menuOpen: '[role="menu"]', - paint: { width: 64, background: '#0b0e0f', line: 'rgba(255,255,255,.12)', accent: '#53fc18', rtl: false } }, - account: { read: readKickAccount, signedOut: root => !!root.querySelector('[data-test="login"]') }, - links: { configKey: 'site', clickedUrl: kickClickedUrl }, - themeSources: { dark: KICK_DARK_AXIS }, + account: { read: readAccount, signedOut: root => !!root.querySelector('button[data-testid="login"]') }, + links: { configKey: 'site', clickedUrl }, }; -configureRuntime(KICK); ``` -Each runtime module takes only its piece (`installPaneNav(window, KICK.rail!)`, -`installLinkRouting(window, KICK.links!)`, `installAccountReport(window, KICK.account!, invoke)`, -`createCorePluginApi(window, KICK.plugins)`), so a site without a rail simply does not install it. - -What every runtime entry does the same way is composed by `runtime/siteRuntime`: -`pageInvoke(window, product)` (the IPC bridge, read at call time), `createFeatureFlags({ defaults, -installers, apply })` (parts that install on enable and dispose on disable; a deck column's flag -overrides sit on top of the owner's) and `installSiteRuntime({ win, site, version, plugins, strings, -features, theme, fonts, pane, links, column, extra, queues })`, which builds the runtime object -(`features.apply`, `i18n.set`, `links.configure`, `pane.set`, `fonts.provide`, `column.set`, -`open()`, `api`, `withPlugin`, `devError`), publishes it as `window.wayBetter` and the app's own -names, takes over what native code queued before it existed and starts the palette command report. -`createPageStrings` (`runtime/pageStrings`) is the page's language and `installPanelButton` -(`runtime/panelButton`) keeps the way into the panel on the page: the adapter's `mountNav` puts -an entry into the site's own navigation, and where the page has none a floating button stands in. - -### 3. Capabilities (Tauri JSON, keyed by webview label) - -The security model is the same for every app and must stay keyed by webview label: - -| webview | may call | -| --- | --- | -| `shell` (local assets only) | the app's own commands and the host's `commands::SHELL` (`tabs_sync`, `tab_navigate`, `tab_action`, `shell_raise`, `profiles_*`, `i18n_*`, `plugins_*`, `custom_css_*`, `features_*`, `settings_*`, ...) | -| `tab-*` (any site) | only tab chrome about itself: `tab_report`, `tab_shortcut`, `tab_link_drag` | -| `tab-*` on the exact site origin | the app's short, reviewed list of site-only commands, and the host's `commands::SITE` (`open_panel`) | -| other local webviews (`popover-*`, ...) | their own narrow capability | - -```json -{ "identifier": "tab-chrome", "webviews": ["tab-*"], "local": false, - "remote": { "urls": ["https://*/*", "http://*/*"] }, - "permissions": ["allow-tab-report", "allow-tab-shortcut", "allow-tab-link-drag"] } -``` +**3. Capabilities: who may call what** (`src-tauri/capabilities/*.json`, keyed by webview label). +The scaffold writes `shell`, `tab-chrome` and `site-tab`; the last one is granted only on the +site's own URLs: ```json { "identifier": "site-tab", "webviews": ["tab-*"], "local": false, "remote": { "urls": ["https://kick.com/*"] }, - "permissions": ["allow-open-panel"] } + "permissions": ["allow-site-ready", "allow-open-panel"] } ``` -Native code re-checks every one of these (the capability file alone is not the boundary): the -caller's label, the webview's own URL (never the page's claim), payload bounds. A tab can speak only -about itself; the account it reports is recorded only for its own profile, only while it is on the -site, and a shell save can never change it (`ProfileSettings::keep_accounts_from`). +The app itself is `waybetter_host::app` configured with an `AppConfig` and a `SiteHooks` +implementation (what only your site knows: page scripts, legacy domains, link routing). Anything +else the app needs is an ordinary `#[tauri::command]` in your crate. -`waybetter_host::testkit` checks this in an app's own tests: `Capabilities::from_dir` reads every -capability file, `assert_host_commands` keeps the host's commands shell-only / tab-only, -`assert_shell_only` / `assert_tab_only` do the same for the app's, `assert_site_only(command, &SITE)` -checks that a site command is granted only on the site's own URLs, `assert_no_plugin_apis` refuses -Tauri plugin JS APIs, and `assert_guarded` / `assert_host_guards` check that each command's first -statement checks its caller. - -## What the host gives an app - -- `app` (feature `app`): the whole app. `App::new(AppConfig, hooks).setup(..).run(context, - handler)` (or `run_app`) registers single-instance, deep-link (opt-in), window-state, opener, - updater (opt-in), process, notification and dialog; makes the app-data folder (0700 on Unix), - loads the profiles and the language, runs the app's setup, then builds the window (frameless - with the shell's titlebar, or the OS frame), restores its geometry (lost geometry reset), - routes helper-window closes (Windows), follows window resizes natively and adds the shell - webview (transparent: it can rise above the tabs; macOS needs the `macos-private-api` feature). - It serves `commands::SHELL` (`tabs_sync`, `tab_navigate`, `tab_action`, `open_external_url`, - `shell_focus`, `shell_ready`, `tab_still_ready`, `shell_raise`, `window_system_menu`, `profiles_get`/`profiles_set`, - `i18n_get`/`i18n_set`, `plugins_list`, `plugin_set_enabled`, `plugins_open_folder`, - `custom_css_get`/`custom_css_set`, `features_get`/`features_set`, `settings_get`/`settings_set`), - `commands::TAB` (`tab_shortcut`, `tab_link_drag`) and `commands::SITE` (`open_panel`), each - checking its caller first, and dispatches every other command to the app's handler. It keeps - the page state those commands read and save (`PageState`: the plugin store in app data - `plugins`, made from the `PluginHost` in `AppConfig::new(site, title, plugins)`; the feature flags - in `features.json`; `ShellSettings` in `settings.json`): the app reads it with `page(app)`, gets a - loaded document's scripts from `page_scripts(app)` (flags, links, custom CSS, plugins) and writes - it with `set_features`, `set_settings` and `set_custom_css` (a backup import). Tab webviews get their - profile's data folder, the app's document-start scripts, navigation/pop-up/load/title/download - handling, stills and memory targets; `SiteHooks` is where the app says what only it knows (page - scripts, legacy domains, link routing, per-tab state, what a finished site page gets). Helpers: - `profiles`, `tab_profile`, `account_seen`, `tr`/`trf`, `i18n_page_script`, `notify`, - `open_external`. - To show the first window only after restored panes are placed, opt in on both sides: - `AppConfig::defer_window_show = true` and `ShellSite.deferWindowShow = true`, and grant the - shell `allow-shell-ready`. The default still shows the window immediately. An opted-in app - shows it after initial `tabs_sync`, with a three-second fallback if shell startup fails. -- `commands`: the host's command lists (`SHELL`, `TAB`, `SITE`) and `manifest(&[..])` for the app's `build.rs`. -- `settings`: `ShellSettings` (home page, where links to other sites and to the site's own pages - open, session restore; missing fields take the defaults), `links_script`, and the feature flags' - validation (a small map of booleans) and `features_script`. -- `testkit`: see the capabilities section. -- `policy`: `SHELL_LABEL`, `tab_id`, `require_local`, `require_site_tab`, `clamp_tab_rect` (tabs never - cover the titlebar or, while restored, the resize band). -- `profiles`: `ProfileSettings` (validated, default profile required, profiles with open tabs cannot be - removed), `data_dir` (ids cannot escape `profiles/`), `orphan_dirs`, `store_identifier` (macOS). -- `plugins`: `PluginStore` with a `PluginHost` (runtime global, origin, product, bundled plugins). - Bundled plugins are written disabled and upgraded only while untouched. -- `hotfix`: minisign-verified, schema-checked, monotonic, expiring data; delivered frozen as data. -- `update`: check schedule with jitter, crash handshake (automatic apply off after two failed boots). -- `tabs`: shell payloads and validation; `deliver_script` hands JSON to a runtime member or parks it. -- `bridge`: the tab bridge (`SOURCE`, or `script(BridgeOptions)` to leave shortcut and link-drag - forwarding off when the shell does not handle them). -- `backup` + `sync`: the `.waybetter` settings backup (the app registers its sections and files; - secret-looking keys are scrubbed both ways) and encrypted snapshots in a folder the owner syncs. -- `workspaces`: validation of saved layouts (slug ids, known tab kinds, http(s) URLs, size caps). -- `devmode`: the live-reload watcher (plugins, `custom.css`, one theme file; the app turns the theme - document into its own state through a callback). -- `alerts`: keyword settings, snippets, `Throttle`, `AlertGate` over any `KeywordMatch`; - `alerts::notify` (feature `tauri`) shows a native notification. -- `media`: gallery folders and the opt-in clipboard history; `media::clipboard::watch` (feature - `tauri`) polls the OS clipboard and never reads a copy a password manager marked private. -- `gfonts` + `fonts` (feature `net`): Google Fonts downloaded natively from the two Google hosts - only, cached with a sha256 manifest and handed to site pages as bytes (`page_script(&SITE, ..)`). -- `updater` (features `tauri` + `net`): the update loop, the signed hotfix channel and - `status`/`apply`/`ready` for the app's commands, configured by an `UpdaterConfig`. -- `plugins::commands`: palette commands a site tab reports, and `run_script(&SITE, id)`. -- `store`: the wayBetter Store for any app from a `StoreConfig` (app id, link scheme, store URL, - public keys with rotation, download hosts): `waybetter://install` link parsing, the allow-list, - size caps, catalog verification (Ed25519, strict schema, each app sees only its items), `Store` - (pending links, staged installs, commit of exactly the staged bytes, records, offline catalog), - and with feature `net` no-redirect/no-cookie downloads. The shell half is `waybetter/shell`'s - `InstallHost`, `StoreView` and install controller; the tooling is `waybetter store` - (docs/STORE.md). -- `host` (feature `tauri`): `shell_only`, `tab_only`, `site_tab_only`, `emit_shell`, `tab_webview`, - `eval_in_site_tabs`, `navigate_tab`, `tab_action`, `forward_shortcut`, `forward_link_drag`, - `read_json`/`write_json`, `remove_profile_dirs`, `prune_profile_dirs`, `migrate_identifier`, - `system_menu`. - -The app keeps its own `#[tauri::command]` wrappers for everything else, and its capability files; -its `build.rs` lists its commands through `commands::manifest`, which adds the host's. - -The npm package adds the app-side tooling: - -- `waybetter/build`: `buildRuntime({ entry, outfile, catalog, prefixes, ... })` bundles a page - runtime into one IIFE with the app's esbuild (`?inline` CSS as text, other CSS dropped, only the - runtime's own catalog prefixes compiled in). -- `waybetter release windows|macos`: signed native releases and the update manifest from the - app's `waybetter.release.json` (product and file names, key folder, CDN and API URLs, an optional - manifest validator). Windows: the signed NSIS build, the installer and `.sig` in - `/upload`, `latest.json` (other platforms of the version kept); macOS: signs a universal - build's updater bundle and adds both darwin platforms. It never uploads: it prints the steps. - The key is read only into the build's environment or handed to the Tauri signer by path. -- `waybetter build-env -- ` and `waybetter privacy-scan`: nothing an app publishes may - name the person who built it. A Rust binary embeds the absolute paths of its sources (the Cargo - registry, the rustup toolchain, the workspace: about 1,400 strings holding the account name in - one app), so `build-env` runs a build with those roots remapped to `/home`, `/src`, `/cargo`, - `/rustup` and `/target` (`--remap-path-prefix` appended to the flags already set, - `/PDBALTPATH:%_PDB%` on MSVC, `-ffile-prefix-map` for C sources on gcc and clang). MSVC has no - prefix map, so there the C and C++ a build script compiles (a CMake library, the cc crate) lose - the same roots through `/d1trimfile:` in the `CL` variable, and any PDB they link through - `/PDBALTPATH` in `LINK`; cl.exe and link.exe read both themselves, whatever runs them: - `waybetter build-env -- tauri build`, on every platform. `privacy-scan` is the proof: it searches - files, binaries (UTF-8, UTF-16), archives (npm tarballs, zip, tar, .deb, DMG; NSIS installers and - AppImages through 7-Zip), git-tracked files and, with `--history`, every blob, path, commit - message and identity of a repository for the terms in a file kept outside every repository - (`"forbiddenTerms"` in `waybetter.release.json`, or `WAYBETTER_FORBIDDEN_TERMS`) plus the - machine's account name, and prints hits masked (`m***`). `waybetter release` builds with - `build-env` and refuses to release an artifact with a hit or one it could not open. The `.pdb` - next to a Windows binary still holds every path: never publish it. -- `waybetter strings check `: a string pack (data that replaces the wrapped site's own UI - strings) against the site's string inventory: only inventory keys, parameter names, plural and - select kinds, no markup; prints the coverage. See docs/STRING-PACKS.md. -- `waybetter i18n check|extract`: an app's locale catalogs against the framework's rules (file - shape, keys English lacks, ICU syntax, placeholder parity, plural forms, no markup), the - framework's catalogs in the same languages, the generated `languages.json` and native - localization files (macOS `Info.plist` and `InfoPlist.strings`, the Linux `.desktop` template), - bundled plugins' inline English, and the keys the code looks up; configured by the app's - `waybetter.i18n.json`. -- `waybetter/windows/languages/.nsh`: the installer's messages for the 17 languages - Tauri does not ship itself, generated from the framework catalogs (`wb.installer.*`; - `node packages/waybetter/scripts/installer-languages.mjs --write`). An app lists them under - `bundle.windows.nsis.customLanguageFiles`. -- `waybetter/windows/installer.nsi`: the Windows installer, a template for Tauri's NSIS bundler - (`bundle.windows.nsis.template`). No wizard and no UAC: it installs for the current user, makes - the Desktop and Start menu shortcuts and opens the app. Run again by hand, it only installs when - it is newer than what is installed (an upgrade in place, app data untouched); otherwise it opens - the installed app and exits 0, so an old setup left in Downloads never replaces or downgrades an - install the updater has moved on. `/FORCE` reinstalls the same version (repair), `/NORUN` does - not open the app, `/UPDATE` is the updater's path and always installs. An app renamed after its - first release keeps its registry keys by defining `WAYBETTER_LEGACY_NAME` in its installer hooks - (`bundle.windows.nsis.installerHooks`). - -## Consuming it - -wayBetter for X adds this repository as a git submodule at `waybetter/` and consumes it from source: - -- Rust: a path dependency, `waybetter-host = { path = "../../../waybetter/crates/waybetter-host" }`, - with `features = ["app", "net", "macos-private-api"]` enabled by the app's desktop feature (and - as a build-dependency for `commands::manifest`). -- TypeScript: relative imports of `waybetter/packages/*/src/*.ts`: the X site for the shell frame - (`src/shell/site.tsx`), the page runtime's adapter and a few X modules. Its Vite config dedupes - React, dockview and the Tauri API (the frame's imports use the app's copies) and serves - `bootScript()` as `/boot.js`. The - packages are not Bun workspace members of the app on purpose: the app's server CI clones without - submodules and runs `bun i`, which fails when a declared workspace package is missing; and Node's - type stripping refuses `.ts` files under `node_modules`, while sources outside it work with Bun's - isolated linker on Windows. - -## Dev loop - -`waybetter dev [--stable] --watch ""...` starts the app's watchers, waits for their -first build and runs `tauri dev` (`--stable` adds `--no-watch`: a Rust file saved by someone else -does not restart the app; restart it yourself after Rust changes). Debug builds only: - -- The app names its page scripts with `waybetter_host::page_script!(include_str!("../x.js"), "x.js")` - in `SiteHooks::init_scripts`. A debug build reads the file from disk (path relative to the app - crate, falling back to the embedded copy) each time a tab's init scripts are built and watches it - (`devloop`, using `devmode`'s debounced signature watcher). When it changes, every tab webview is - rebuilt on its current URL through `tabs_sync`, because a webview's document-start scripts are - fixed at creation. Route is kept, scroll is not. About 1 s from save to visible. -- `buildRuntime({ watch: watchRequested(), ... })` (`waybetter/build`) keeps esbuild rebuilding the - file; a failed build leaves the last good one. -- The shell reloads through the frontend dev server (`beforeDevCommand`), instantly. -- Restart needed: Rust, `tauri.conf.json`, capabilities, bundled plugin sources (`include_str!` in the - plugin table; installed plugin files reload with developer mode as before). -- Release builds contain none of it: `devloop` is `cfg(debug_assertions)`, the macro's release arm is - `$embedded.to_owned()` and the path literal is never expanded. `release_guard` (lib.rs) checks that - every mention is gated; `cargo test --release` also runs `release_page_script_is_the_embedded_copy`. -- `.taurignore` the watched output files (`observer.js`, `x-runtime.js`), or plain `tauri dev` restarts - on every rebuild. `create-waybetter` apps get `npm run dev` and `npm run dev:stable`. - -## Scripts (no CI) +## Start a project ```sh -bun install # typescript + @types/node for the checks -bun run typecheck # tsc over both packages and their tests, and create-waybetter (checkJs) -bun run test # node --test (runtime + shell), cargo test (headless host), create-waybetter -bun run test:ts -bun run test:rust -bun run test:create # scaffolds into temp dirs; its cargo check of an app is ~1 min cold - # (WAYBETTER_SKIP_CARGO_CHECK=1 skips it; needs the local crate cache) -bun run check # typecheck + build:packages + test -bun run check:tauri # cargo check with the app feature (slow: builds Tauri and its plugins) -bun run build # typecheck + cargo build -bun run pack:check # npm pack --dry-run of waybetter and create-waybetter -node packages/waybetter/scripts/installer-languages.mjs [--write] # windows/languages/*.nsh from the catalogs -node packages/shell/scripts/google-fonts-catalog.mjs # the font browser's offline list +npm create waybetter plugin -- --name "Hide Trends" +npm create waybetter theme -- --name "Midnight Mint" --accent "#3ddc97" +npm create waybetter app kickapp -- --site kick.com --name "wayBetter for Kick" --yes ``` -`dev-tools/` has the harnesses for a running or built app (perf probes, the graceful-close check, -tab and webview stress); see its README. +The app scaffold adds the framework as a git submodule at `waybetter/` by default (`--host-source +path` and `--host-source git` are the alternatives). Its next steps, as the tool prints them: +`git init && git submodule add https://git.crt.fyi/CRT/waybetter.git waybetter`, then +`npm install`, `npm run build`, `npm run tauri dev`, then replace the placeholder selectors in +`src/site.ts` and `src-tauri/src/site.rs`. Flags: `npm create waybetter -- --help`. +See [packages/create-waybetter](packages/create-waybetter/README.md). -Requires Bun 1.4.2+, Node 24+ and Rust 1.88+. +## The dev loop + +In a scaffolded app, `npm run dev` runs `waybetter dev --watch "node scripts/build.mjs --watch"`: +it starts your watchers, waits for their first build and runs `tauri dev`. In debug builds the page +runtime file is read from disk and watched; when it changes, every tab webview is rebuilt on its +current URL (about a second from save to visible, the route is kept, the scroll position is not). +The shell reloads through the frontend dev server. Rust, `tauri.conf.json`, capabilities and +bundled plugin sources need a restart. `npm run dev:stable` adds `--no-watch` so a Rust file saved +elsewhere does not restart the app. Release builds contain none of this. There is also a developer +mode in the panel (Settings, Developer) that reloads installed plugins, custom CSS and one theme +file in every tab as you save. + +## Security model + +The site's page is not trusted, and neither is a plugin. The rules: + +- Capabilities are keyed by webview label and each command re-checks its caller in Rust: the + capability file is not the boundary. A `tab-*` webview may only report about itself + (`tab_report`, `tab_shortcut`, `tab_link_drag`); on the site's exact origin it also gets the + app's short, reviewed list of site commands and `open_panel`. Everything else (tab layout, + settings, plugins, backup, install) is callable from the local `shell` webview only. +- `SiteSpec::is_origin` is the single definition of "a site tab": exact https origin, no + credentials in the URL. +- The account a tab reports is recorded only for that tab's own profile, only while it is on the + site, validated by your `AccountRules`, and a settings save can never change it. +- Installs (themes, plugins) come from a dropped file, a `waybetter://install` link or the signed + store, and are written only after the owner confirms in the shell. The store catalog is verified + with Ed25519; downloads use an allow-list, no redirects, no cookies and size caps. Plugins may + declare `@permissions`; the runtime gives each an API view that throws on undeclared members. + That is a guard rail, not a sandbox. A plugin without the line is labelled legacy and gets the + full API. +- Backups and sync snapshots never contain cookies, WebView profile folders, tokens or signing + keys. Sync is encrypted with the owner's passphrase (Argon2id and XChaCha20-Poly1305). +- `waybetter_host::testkit` lets your `tests/security.rs` read every capability file and assert + that host commands stay shell-only or tab-only, that site commands are granted only on the + site's URLs, and that each command's first statement checks its caller. The scaffold includes + such a test. +- `waybetter privacy-scan` and `waybetter build-env` keep a build free of the builder's paths and + names; `waybetter release` refuses to release an artifact with a hit. + +## What is in the host and what is still yours + +The host owns the logic for settings backup, encrypted folder sync, saved workspaces, the +developer-mode watcher, keyword alerts, the gallery and clipboard history, Google Fonts download +and cache, the store install rules and the update loop. In today's apps some of the Tauri command +wrappers around those modules are still written by the app (wayBetter for X has them). If you +build an app on the scaffold, expect to add the wrapper commands for the features you turn on. +Moving those wrappers into the host is planned. + +## Repository layout + +``` +crates/waybetter-host/ Rust host crate (features: tauri, net, app) +packages/runtime/ page runtime (published inside `waybetter`) +packages/shell/ shell models, shell frame, panel, store screens (published inside `waybetter`) +packages/waybetter/ the npm package: built runtime and shell, JSON Schemas, locales, + and the `waybetter` command (store, release, i18n, strings, privacy-scan, + build-env, dev) +packages/create-waybetter/ `npm create waybetter` +docs/ ARCHITECTURE.md, STORE.md, STRING-PACKS.md +dev-tools/ harnesses for a running or built app (not published) +``` + +## Tests + +```sh +bun install +bun run typecheck # tsc over both packages, their tests and create-waybetter +bun run test:ts # node --test: runtime and shell +bun run test:rust # cargo test of the host crate (headless, feature net) +bun run test:create # scaffolds each kind into temp folders and checks them against the real contracts +``` + +`test:create` also runs `cargo check` on a generated app (about a minute cold); +`WAYBETTER_SKIP_CARGO_CHECK=1` skips that step. Requires Bun 1.4.2+, Node 24+ and Rust 1.88+. + +## Contributing + +Issues and pull requests go to [git.crt.fyi/CRT/waybetter](https://git.crt.fyi/CRT/waybetter). +Keep the split: generic mechanisms belong here, site-specific ones in the app. If you built +something on wayBetter, add it to the list below with a pull request. + +| Project | Target | What it is | +| --- | --- | --- | +| [wayBetter for X](https://git.crt.fyi/CRT/waybetter-for-x) | x.com | Tabs, split panes, real accounts side by side, themes, plugins, drafts and fixes for X's own bugs. | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..ad384d4 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,557 @@ +# Architecture reference + +Every module of the host, the runtime and the shell, and what an app supplies. The overview is in +the [README](../README.md); this is the long form. + +A wayBetter app is one native window (Tauri 2, multiwebview) with: + +- a trusted local **shell** webview: tab strip, split panes (dockview), address bar, titlebar and + window controls, command palette, account switcher, the app's own settings; +- one native child webview per browser **tab**, positioned over the pane rectangles the shell + reports (`tabs_sync`), each in an account **profile** with its own WebView data directory; +- a **page runtime** injected into tabs that are on the app's site: shared DOM/request hubs, + plugins, themes, split-view rail hiding, link routing and account reporting. + +This repository holds the parts that do not depend on which site the app extends. An app is mostly +a **site adapter** plus its own features. + +## One system for every app + +Every wayBetter app is the same system: the Tauri window above (shell + page runtime) plus one +small adapter. That holds for websites like x.com and just as much for services that ship their +own Electron desktop client, such as WhatsApp or Discord: wayBetter runs their web app in its own +light Tauri window instead of the heavy client, and gives it the same tabs, split panes, real +accounts side by side, themes, plugins and signed updates. There is no second kind of host. + +License: GPL-3.0-or-later. + +## Projects using wayBetter + +| Project | Target | What it is | +| --- | --- | --- | +| [wayBetter for X](https://waybetter.fyi/x/) | x.com (website) | Desktop app around the live X: tabs, split panes, real accounts side by side, themes, plugins, drafts and fixes for X's own bugs. The first wayBetter app. | + +Built something on wayBetter? Add it to this list with a pull request: name and link, what it extends, one line on what it does. + +## Build your own + +```sh +npm create waybetter plugin # a *.plugin.js (or --ts: a TypeScript project) on the real plugin API +npm create waybetter theme # a theme JSON with "$schema", a derived palette and font roles +npm create waybetter app -- --site kick.com # a whole app: Tauri 2 + waybetter-host + runtime + shell +``` + +`create-waybetter` (in `packages/create-waybetter`) asks for what it needs in a terminal, and +takes every answer as a flag (`--help`). The app skeleton is this README in code: the native +`SiteSpec`, the page `SiteAdapter`, the app on `waybetter_host::app` (its config, site hooks and +its own commands), the three capability files and a `tests/security.rs` on `waybetter_host::testkit`, +the shell (the framework's shell frame through `createShell`, with the site's pages and a plugins +panel), the plugin store, one site-only command, the +runtime bundled with `waybetter/build` and a `waybetter.release.json` for `waybetter release`, with presets for +youtube.com, kick.com and twitch.tv and every site selector marked as a placeholder. Its tests +generate each kind into a temp folder and check it against the real contracts: plugin headers with +`plugins::parse_meta`, plugin code against `createCorePluginApi`'s members, themes against +`theme.schema.json`, the app's TypeScript with `tsc` against the built package and its Rust with +`cargo check`/`cargo test` against this crate. + +## Layout + +``` +crates/waybetter-host/ Rust: security policy, profiles, plugin store, hotfix, updates, tab payloads, + and the generic native features every app gets (below) + tab-bridge.js the tab bridge every tab gets (served by src/bridge.rs) + src/site.rs SiteSpec + AccountRules (the native half of the adapter) + src/policy.rs webview labels, origin checks, tab rect clamp + src/profiles.rs profiles, per-profile data dirs, native-owned accounts + src/plugins.rs *.plugin.js store, custom CSS, bundled-plugin upgrades + src/plugins/commands.rs palette commands site tabs report, and the script that runs one + src/settings.rs the shell's settings (home page, where links open, session restore) and the + page's feature flags, as validated data and the scripts that deliver them + src/hotfix.rs signed data-only hotfix channel (minisign) + src/update.rs silent-update scheduling and crash handshake + src/tabs.rs TabLayout/TabState/OpenRequest, link modes, shortcut and drag validation, + deck ColumnConfig bounds and unread caps + src/bridge.rs the tab bridge script (reports; shortcut/link-drag forwarding opt-in) + src/backup.rs settings backup envelope, secret scrubbing, plugin/account sections + src/sync.rs encrypted folder sync (Argon2id + XChaCha20-Poly1305 snapshots) + src/workspaces.rs saved tab/pane/deck layouts, bounded and well-formed + src/devmode.rs developer mode: debounced file watcher, reload order, error positions + src/alerts.rs keyword alerts: keywords, snippets, rate limits; native notifications + src/media.rs gallery folders (path containment), clipboard history, PNG encoding + src/media/clipboard.rs (feature "tauri") opt-in clipboard polling, private copies skipped + src/gfonts.rs self-hosted Google Fonts: CSS parsing, URL/woff2 checks, cache format + src/fonts.rs (feature "net") font downloads and the font cache + src/updater.rs (features "tauri" + "net") signed native updates and the hotfix channel + src/store/ install links, download allow-list, signed multi-app store catalog, staging + and installs; downloads with feature "net" (docs/STORE.md) + src/host.rs (feature "tauri") webview helpers, shell events, system menu + src/app.rs (feature "app") the whole app around a site: run_app / App, AppConfig, + SiteHooks, the window, shell and tab webviews, the generic commands + (tabs, profiles, language, plugins and custom CSS, feature flags, settings) + src/commands.rs the commands the host serves and who may call them; manifest() for build.rs + src/testkit.rs capability/caller-check assertions for an app's tests/security.rs +packages/runtime/src/ page runtime core (TypeScript, no dependencies) + site.ts SiteAdapter (the page half of the adapter) + configureRuntime + domHub.ts netHub.ts one MutationObserver/frame, one fetch/XHR hook per page + pluginApi.ts core of window..api for plugins (incl. ui and theme) + ui.ts plugin UI kit: toasts, alert/confirm/prompt, dialogs (shadow DOM, themed) + themeApi.ts the active theme as values + --wb-* CSS variables (api.theme) + themeTokens.ts OKLab color model: maps the site's palette onto a theme's axis + paneNav.ts split view: park the site's navigation rail in redundant panes + column.ts deck columns: hide site chrome, fill the width, filters, unread count + linkRouting.ts divert in-page clicks to a pane/tab/browser per setting + accountReport.ts report the signed-in account of this tab's profile + siteRuntime.ts the runtime's composition: the IPC bridge, flag-controlled parts with a deck + column's overrides, the runtime object under its window names, native queues + pageStrings.ts the page's language: English built in, native deliveries checked as data + stringPacks.ts string packs (docs/STRING-PACKS.md): pack and inventory formats, validator, + ordered engine, coverage, drift report + stringPackHook.ts the per-site catalog hook adapter, its self-check, a webpack chunk array hook + textNet.ts DOM safety net for labels no catalog hook reaches + panelButton.ts the way into the panel from the page (navigation entry or floating button) + commandReport.ts the palette command report and developer-mode start errors +packages/shell/src/ shell core (TypeScript) and the shell frame (React) + addressModel.ts address bar chips (site pages named by the adapter) + paneModel.ts beside-pane reuse, redundant rails, navRedundant for tabs_sync + deckModel.ts decks of site columns: bounded storage model, paging layout, focus + linkDrop.ts dropping links into the dock + profileModel.ts profiles and account labels + palette.ts command palette scoring/ranking + updateModel.ts titlebar update chip + windowControls.ts caption buttons, resize grips, system menu (Tauri API injected) + chrome.ts titlebar/toolbar/resize-border sizes (match policy.rs) + storeModel.ts storeMessages.ts Store wire types, item states, permission words; wb.store/install/permission.* + installController.ts the install screen's state machine (links, drops, store items, confirm) + InstallDialog.tsx StoreView.tsx store.css the install screen and the Store view (React peer, --wb-* tokens) + frame/ the shell frame: createShell(site) (see "The shell frame" below) + panel/ the panel: createPanel(site), the app's own tab (see "The panel" below) + installerMessages.ts the Windows installer's words (wb.installer.*) +packages/waybetter/ the published npm package (runtime + shell as ESM + .d.ts, theme.schema.json, + store-catalog.schema.json, the `waybetter store build|sign|verify`, + `waybetter release windows|macos`, `waybetter i18n check|extract`, + `waybetter privacy-scan` and `waybetter build-env` commands, `waybetter/build`, locales/ (51 catalogs and translator notes), + windows/ (the installer template and its language files)) +dev-tools/ development harnesses for a running or built app (perf probes, close and + stress checks); not published (dev-tools/README.md) +docs/STORE.md the Store: shared catalog format, signing and keys, tooling, trust model, how to add it +packages/create-waybetter/ `npm create waybetter`: plugin, theme and app scaffolds (no dependencies) +``` + +Both TypeScript packages are plain source (`.ts`, ESM, `type: module`) with no runtime +dependencies, so an app can bundle them with esbuild/Vite and run their tests with Node's type +stripping. Anything that needs the Tauri API (window controls, the shell frame) takes it as a +parameter. The React parts (the Store screens, the shell frame) have React, and the frame dockview, +as optional peers: the app's copies are used. + +## The shell frame + +`packages/shell/src/frame` (`waybetter/shell/frame`) is the whole shell of a wayBetter app. An app +describes its site and gets tabs in the titlebar row, split panes and link drags into the dock, the +smart address bar, the new-tab page, the command palette, the account switcher, decks of site +columns, workspaces, the developer-mode and sync chips, the gallery/clipboard panel, pane themes, +its own panel tab, keyboard shortcuts, overlays that raise the shell above the tab webviews, the +one-layout-in-flight `tabs_sync` and session restore: + +```tsx +import { invoke } from '@tauri-apps/api/core'; // or window.__TAURI__ (withGlobalTauri) +import { listen } from '@tauri-apps/api/event'; +import { getCurrentWindow } from '@tauri-apps/api/window'; +import { createShell, type ShellSite } from 'waybetter/shell/frame'; + +const site: ShellSite = { name: 'Kick', product: 'wayBetter for Kick', homeUrl, loginUrl, logoutUrl, + isSiteUrl, accounts, searchUrl, address, panel: { id, title, component }, newTab, palette, + deck, media, themes, overlays, features, start }; +const Shell = createShell(site, { native: { invoke, listen, currentWindow: getCurrentWindow }, i18n }); +createRoot(root).render(); +``` + +What the site supplies (`frame/site.ts`, every field documented there): + +- names and pages: `name` (in messages as `{site}`), `product`, `logo`, `homeUrl`, `loginUrl`, + `logoutUrl`, `isSiteUrl`, the account rules, `searchUrl` for typed text; +- the address bar: `address(url)` (chips, usually `parseAddress` with an `AddressSite`) and an + optional `addressCompleter` (inline completions, e.g. search operators); +- slots: `panel` (the app's own tab and its sections), `newTab` (search label, quick links), + `palette` (placeholder, the literal search, completions, the panel's sections, the site's pages), + `deck` (column kinds with labels and icons, the page each loads, titles, value parsing and + completions, column flags and presets, an optional compose dock), `media` (which pages have a + composer), `themes` (a `createThemeStore(adapter)`: the app's theme documents, chrome colors via + `chromeVars`, pane themes), `overlays` (the app's own dialogs), `start()` (read site settings, + call `siteChanged()` when site text changes); +- `features`: the native features the app wires up (workspaces, sync, developer mode, plugin + palette commands); an app without them shows nothing of them. + +The frame's words are `wb.*` messages in the framework catalogs (51 languages; English source in +`frame/frameMessages.ts`): the app passes its i18n instance with the framework catalogs merged in. +Styles come with the components (dockview's, then `shell.css`, `deck.css`, `workspaces.css`, +`accountSwitcher.css`, `paneTheme.css`); colors are `--wb-c-*` tokens with Night Ink fallbacks, +set by the theme store (the chrome and each pane group) and cached for the first frame: +`bootScript()` (`frame/boot.ts`) is the `boot.js` an app serves before its modules (a Vite plugin or +a build step writes it). `installPreviewMocks(handlers)` answers native commands from memory, so +the real shell renders in a plain browser for development previews and screenshots. + +Native commands the frame calls: the host's (`tabs_sync`, `tab_navigate`, `tab_action`, +`shell_focus`, `shell_raise`, `open_external_url`, `window_system_menu`, `profiles_*`), and for the +features an app turns on `settings_get`, `column_configure`, `workspaces_*`, `sync_*`, `dev_*`, +`plugins_list`, `tab_run_command`, `media_get`/`gallery_*`/`clip_*`/`tab_attach_image`/ +`tab_insert_text`, `theme_scopes_*` and `gfonts_*`, `app_ready`/`update_status`/`apply_update`. It +listens to `tab-state`, `tab-open`, `tab-shortcut`, `link-drag`, `open-panel`, `profiles-changed`, +`tab-commands`, `dev-event`, `update-status`, `tab-still` and `clipboard-changed`. + +## The panel + +`packages/shell/src/panel` (`waybetter/shell/panel`) is an app's own tab in the shell: a home page, +Appearance (the theme gallery, customization, account and pane themes, downloaded fonts, theme +import/export) and the Theme Builder (undo/redo, a palette from three colors, a contrast report, a +font per role with the Google Fonts browser), plugins and custom CSS, the Store, Make (example +plugins, the plugin UI kit, the theme API, bundled docs), accounts, Power User (deck settings), +settings (language, links and session, keyword alerts, the media panel), backup and sync, developer +mode, updates, and a search across every setting. It lives in the shell package, next to the frame +it renders in: it uses the frame's stores (profiles, decks, themes, sync, developer mode), its +native bridge and its language, so `createShell` comes first. + +```tsx +import { createPanel, type PanelSite } from 'waybetter/shell/panel'; + +const panel: PanelSite = { brand: { name: 'wayBetter', logo }, home, themes, sections, order, make, + store, languages, settings, power, backup: true, updates: true }; +const Panel = createPanel(panel); +const Shell = createShell({ ...site, panel: { id: 'app', title: 'wayBetter', component: Panel } }, options); +``` + +What the app supplies (`panel/site.ts`, every field documented there): + +- `brand` and `home`: the header and the home page's words (kicker, title, lede, chips, actions, + highlight cards, the About block), `version()` for its chip; +- `sections` and `order`: its own sections (a label, an icon path, a component that gets `notify` + and `openSection`; `searchable` ones also show in the settings search), placed among the built-in + ones. X adds Tweaks and Drafts; +- `themes`: its theme store and catalog (`createThemeStore`, `createThemeCatalog`), accent swatches, + the **preview** component (a miniature of the site drawn from a theme document, used by the gallery + and the builder), the site font's name, the palette a draft starts from, and for Make's theme view + `resolved(choice, mode)` with the site's own display modes; +- `make`: example plugins, an example theme file and bundled Markdown docs; +- `store`: the install controller (the Store section, and removing a plugin from the list); +- `languages`: the language list and state (`createLanguage`, `frame/language.ts`); +- `settings`, `power`, `cssExamples`: keyword alerts, extra settings rows, which column flags and + which memory measure Power User lists, placeholder CSS with the site's selectors. + +A built-in section shows only when the app serves what it needs: Appearance, the Theme Builder and +the Store with `themes` (and `store`), Make with `make`, Power User with `site.deck`, backup with +`backup` (its sync half with the frame's `sync` feature), Developer with the frame's `developer` +feature, Updates with `updates`. An app with nothing but plugins gets Home, Plugins, Accounts and +Settings (this is what `npm create waybetter app` generates). + +Building blocks for the app's own sections: the panel's controls (`Section`, `Row`, `Toggle`, +`Segmented`, `Select`, `Slider`, `ColorField`, `Button`, `Badge`, ...; `panel/controls`), the +feature toggles (`useFeatures` + `FeatureGroups` over `features_get/set`: the app names its flags +and groups, its catalog has `features..label` and `.description`), and `compareLines`. + +The panel's words are `wb.*` messages too (English source in `panel/panelMessages.ts`, translator +notes in `locales/en.meta.json`). Three families of keys stay the app's, by convention, because +they name its own things: `plugin..name|description` (its bundled plugins), +`theme..description` (its built-in themes) and `features.*` (its tweaks). + +Native commands the panel calls: the host's `plugins_list`, `plugin_set_enabled`, +`plugins_open_folder`, `custom_css_get/set`, `features_get/set`, `settings_get/set`, +`profiles_*` and `open_external_url`, and for what the app turns on `alerts_get/set`, +`media_get/set`/`gallery_add_folder`/`clip_remove`, `backup_*`, `sync_*`, `dev_*`, the theme +store's commands and `gfonts_*`, `install_records`/`install_forget`/`plugin_remove`/`store_catalog`, +`app_ready`/`update_status`/`apply_update`. + +The Google Fonts list the font browser shows is an offline snapshot +(`panel/fonts/googleFontsCatalog.json`; `packages/shell/scripts/google-fonts-catalog.mjs` +regenerates it). The app never fetches the list, only the font files the owner picks (natively). + +## The site adapter + +A site adapter is three small, explicit things. + +### 1. Native: `SiteSpec` (Rust) + +```rust +use waybetter_host::site::{AccountRules, SiteSpec}; + +fn kick_handle(value: &str) -> bool { + (3..=25).contains(&value.len()) && value.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') +} + +pub static SITE: SiteSpec = SiteSpec { + product: "wayBetter for Kick", + hosts: &["kick.com"], // exact https origin(s) of site tabs + runtime_global: "WayBetterKick", // window. of the page runtime + accounts: AccountRules { + valid_handle: kick_handle, + avatar_prefixes: &["https://files.kick.com/"], + max_name_chars: 50, + max_avatar_len: 512, + }, +}; +``` + +`SiteSpec::is_origin` is the only definition of "a site tab". Site-only commands check +`policy::require_site_tab(&SITE, label, url)` (or `host::site_tab_only`), which also requires a +`tab-*` label. + +### 2. Page: `SiteAdapter` (TypeScript) + +```ts +import { configureRuntime, type SiteAdapter } from 'waybetter/packages/runtime/src/site.ts'; + +export const KICK: SiteAdapter = { + product: 'wayBetter for Kick', + hosts: ['kick.com'], + runtimeGlobal: 'WayBetterKick', + heavyPath: null, // pages where offOnHeavy DOM features pause + apiMarks: ['/api/'], // request URLs the net hub stages may see + xhrMarks: [], + plugins: { name: 'WayBetterKick', product: 'wayBetter for Kick', storagePrefix: 'wbk-plugin:', + styleDataKey: 'wbkPlugin', toastId: 'wbk-toast', toastBackground: '#53fc18', + itemSelector: '[data-chat-entry]', chordKeys: [] }, + rail: { prefix: 'wbk', rail: '#sidebar-wrapper', anchor: 'a[href="/"]', main: 'main', + modalOpen: '[role="dialog"]', menuOpen: '[role="menu"]', + paint: { width: 64, background: '#0b0e0f', line: 'rgba(255,255,255,.12)', accent: '#53fc18', rtl: false } }, + account: { read: readKickAccount, signedOut: root => !!root.querySelector('[data-test="login"]') }, + links: { configKey: 'site', clickedUrl: kickClickedUrl }, + themeSources: { dark: KICK_DARK_AXIS }, +}; +configureRuntime(KICK); +``` + +Each runtime module takes only its piece (`installPaneNav(window, KICK.rail!)`, +`installLinkRouting(window, KICK.links!)`, `installAccountReport(window, KICK.account!, invoke)`, +`createCorePluginApi(window, KICK.plugins)`), so a site without a rail simply does not install it. + +What every runtime entry does the same way is composed by `runtime/siteRuntime`: +`pageInvoke(window, product)` (the IPC bridge, read at call time), `createFeatureFlags({ defaults, +installers, apply })` (parts that install on enable and dispose on disable; a deck column's flag +overrides sit on top of the owner's) and `installSiteRuntime({ win, site, version, plugins, strings, +features, theme, fonts, pane, links, column, extra, queues })`, which builds the runtime object +(`features.apply`, `i18n.set`, `links.configure`, `pane.set`, `fonts.provide`, `column.set`, +`open()`, `api`, `withPlugin`, `devError`), publishes it as `window.wayBetter` and the app's own +names, takes over what native code queued before it existed and starts the palette command report. +`createPageStrings` (`runtime/pageStrings`) is the page's language and `installPanelButton` +(`runtime/panelButton`) keeps the way into the panel on the page: the adapter's `mountNav` puts +an entry into the site's own navigation, and where the page has none a floating button stands in. + +### 3. Capabilities (Tauri JSON, keyed by webview label) + +The security model is the same for every app and must stay keyed by webview label: + +| webview | may call | +| --- | --- | +| `shell` (local assets only) | the app's own commands and the host's `commands::SHELL` (`tabs_sync`, `tab_navigate`, `tab_action`, `shell_raise`, `profiles_*`, `i18n_*`, `plugins_*`, `custom_css_*`, `features_*`, `settings_*`, ...) | +| `tab-*` (any site) | only tab chrome about itself: `tab_report`, `tab_shortcut`, `tab_link_drag` | +| `tab-*` on the exact site origin | the app's short, reviewed list of site-only commands, and the host's `commands::SITE` (`open_panel`) | +| other local webviews (`popover-*`, ...) | their own narrow capability | + +```json +{ "identifier": "tab-chrome", "webviews": ["tab-*"], "local": false, + "remote": { "urls": ["https://*/*", "http://*/*"] }, + "permissions": ["allow-tab-report", "allow-tab-shortcut", "allow-tab-link-drag"] } +``` + +```json +{ "identifier": "site-tab", "webviews": ["tab-*"], "local": false, + "remote": { "urls": ["https://kick.com/*"] }, + "permissions": ["allow-open-panel"] } +``` + +Native code re-checks every one of these (the capability file alone is not the boundary): the +caller's label, the webview's own URL (never the page's claim), payload bounds. A tab can speak only +about itself; the account it reports is recorded only for its own profile, only while it is on the +site, and a shell save can never change it (`ProfileSettings::keep_accounts_from`). + +`waybetter_host::testkit` checks this in an app's own tests: `Capabilities::from_dir` reads every +capability file, `assert_host_commands` keeps the host's commands shell-only / tab-only, +`assert_shell_only` / `assert_tab_only` do the same for the app's, `assert_site_only(command, &SITE)` +checks that a site command is granted only on the site's own URLs, `assert_no_plugin_apis` refuses +Tauri plugin JS APIs, and `assert_guarded` / `assert_host_guards` check that each command's first +statement checks its caller. + +## What the host gives an app + +- `app` (feature `app`): the whole app. `App::new(AppConfig, hooks).setup(..).run(context, + handler)` (or `run_app`) registers single-instance, deep-link (opt-in), window-state, opener, + updater (opt-in), process, notification and dialog; makes the app-data folder (0700 on Unix), + loads the profiles and the language, runs the app's setup, then builds the window (frameless + with the shell's titlebar, or the OS frame), restores its geometry (lost geometry reset), + routes helper-window closes (Windows), follows window resizes natively and adds the shell + webview (transparent: it can rise above the tabs; macOS needs the `macos-private-api` feature). + It serves `commands::SHELL` (`tabs_sync`, `tab_navigate`, `tab_action`, `open_external_url`, + `shell_focus`, `shell_ready`, `tab_still_ready`, `shell_raise`, `window_system_menu`, `profiles_get`/`profiles_set`, + `i18n_get`/`i18n_set`, `plugins_list`, `plugin_set_enabled`, `plugins_open_folder`, + `custom_css_get`/`custom_css_set`, `features_get`/`features_set`, `settings_get`/`settings_set`), + `commands::TAB` (`tab_shortcut`, `tab_link_drag`) and `commands::SITE` (`open_panel`), each + checking its caller first, and dispatches every other command to the app's handler. It keeps + the page state those commands read and save (`PageState`: the plugin store in app data + `plugins`, made from the `PluginHost` in `AppConfig::new(site, title, plugins)`; the feature flags + in `features.json`; `ShellSettings` in `settings.json`): the app reads it with `page(app)`, gets a + loaded document's scripts from `page_scripts(app)` (flags, links, custom CSS, plugins) and writes + it with `set_features`, `set_settings` and `set_custom_css` (a backup import). Tab webviews get their + profile's data folder, the app's document-start scripts, navigation/pop-up/load/title/download + handling, stills and memory targets; `SiteHooks` is where the app says what only it knows (page + scripts, legacy domains, link routing, per-tab state, what a finished site page gets). Helpers: + `profiles`, `tab_profile`, `account_seen`, `tr`/`trf`, `i18n_page_script`, `notify`, + `open_external`. + To show the first window only after restored panes are placed, opt in on both sides: + `AppConfig::defer_window_show = true` and `ShellSite.deferWindowShow = true`, and grant the + shell `allow-shell-ready`. The default still shows the window immediately. An opted-in app + shows it after initial `tabs_sync`, with a three-second fallback if shell startup fails. +- `commands`: the host's command lists (`SHELL`, `TAB`, `SITE`) and `manifest(&[..])` for the app's `build.rs`. +- `settings`: `ShellSettings` (home page, where links to other sites and to the site's own pages + open, session restore; missing fields take the defaults), `links_script`, and the feature flags' + validation (a small map of booleans) and `features_script`. +- `testkit`: see the capabilities section. +- `policy`: `SHELL_LABEL`, `tab_id`, `require_local`, `require_site_tab`, `clamp_tab_rect` (tabs never + cover the titlebar or, while restored, the resize band). +- `profiles`: `ProfileSettings` (validated, default profile required, profiles with open tabs cannot be + removed), `data_dir` (ids cannot escape `profiles/`), `orphan_dirs`, `store_identifier` (macOS). +- `plugins`: `PluginStore` with a `PluginHost` (runtime global, origin, product, bundled plugins). + Bundled plugins are written disabled and upgraded only while untouched. +- `hotfix`: minisign-verified, schema-checked, monotonic, expiring data; delivered frozen as data. +- `update`: check schedule with jitter, crash handshake (automatic apply off after two failed boots). +- `tabs`: shell payloads and validation; `deliver_script` hands JSON to a runtime member or parks it. +- `bridge`: the tab bridge (`SOURCE`, or `script(BridgeOptions)` to leave shortcut and link-drag + forwarding off when the shell does not handle them). +- `backup` + `sync`: the `.waybetter` settings backup (the app registers its sections and files; + secret-looking keys are scrubbed both ways) and encrypted snapshots in a folder the owner syncs. +- `workspaces`: validation of saved layouts (slug ids, known tab kinds, http(s) URLs, size caps). +- `devmode`: the live-reload watcher (plugins, `custom.css`, one theme file; the app turns the theme + document into its own state through a callback). +- `alerts`: keyword settings, snippets, `Throttle`, `AlertGate` over any `KeywordMatch`; + `alerts::notify` (feature `tauri`) shows a native notification. +- `media`: gallery folders and the opt-in clipboard history; `media::clipboard::watch` (feature + `tauri`) polls the OS clipboard and never reads a copy a password manager marked private. +- `gfonts` + `fonts` (feature `net`): Google Fonts downloaded natively from the two Google hosts + only, cached with a sha256 manifest and handed to site pages as bytes (`page_script(&SITE, ..)`). +- `updater` (features `tauri` + `net`): the update loop, the signed hotfix channel and + `status`/`apply`/`ready` for the app's commands, configured by an `UpdaterConfig`. +- `plugins::commands`: palette commands a site tab reports, and `run_script(&SITE, id)`. +- `store`: the wayBetter Store for any app from a `StoreConfig` (app id, link scheme, store URL, + public keys with rotation, download hosts): `waybetter://install` link parsing, the allow-list, + size caps, catalog verification (Ed25519, strict schema, each app sees only its items), `Store` + (pending links, staged installs, commit of exactly the staged bytes, records, offline catalog), + and with feature `net` no-redirect/no-cookie downloads. The shell half is `waybetter/shell`'s + `InstallHost`, `StoreView` and install controller; the tooling is `waybetter store` + (docs/STORE.md). +- `host` (feature `tauri`): `shell_only`, `tab_only`, `site_tab_only`, `emit_shell`, `tab_webview`, + `eval_in_site_tabs`, `navigate_tab`, `tab_action`, `forward_shortcut`, `forward_link_drag`, + `read_json`/`write_json`, `remove_profile_dirs`, `prune_profile_dirs`, `migrate_identifier`, + `system_menu`. + +The app keeps its own `#[tauri::command]` wrappers for everything else, and its capability files; +its `build.rs` lists its commands through `commands::manifest`, which adds the host's. + +The npm package adds the app-side tooling: + +- `waybetter/build`: `buildRuntime({ entry, outfile, catalog, prefixes, ... })` bundles a page + runtime into one IIFE with the app's esbuild (`?inline` CSS as text, other CSS dropped, only the + runtime's own catalog prefixes compiled in). +- `waybetter release windows|macos`: signed native releases and the update manifest from the + app's `waybetter.release.json` (product and file names, key folder, CDN and API URLs, an optional + manifest validator). Windows: the signed NSIS build, the installer and `.sig` in + `/upload`, `latest.json` (other platforms of the version kept); macOS: signs a universal + build's updater bundle and adds both darwin platforms. It never uploads: it prints the steps. + The key is read only into the build's environment or handed to the Tauri signer by path. +- `waybetter build-env -- ` and `waybetter privacy-scan`: nothing an app publishes may + name the person who built it. A Rust binary embeds the absolute paths of its sources (the Cargo + registry, the rustup toolchain, the workspace: about 1,400 strings holding the account name in + one app), so `build-env` runs a build with those roots remapped to `/home`, `/src`, `/cargo`, + `/rustup` and `/target` (`--remap-path-prefix` appended to the flags already set, + `/PDBALTPATH:%_PDB%` on MSVC, `-ffile-prefix-map` for C sources on gcc and clang). MSVC has no + prefix map, so there the C and C++ a build script compiles (a CMake library, the cc crate) lose + the same roots through `/d1trimfile:` in the `CL` variable, and any PDB they link through + `/PDBALTPATH` in `LINK`; cl.exe and link.exe read both themselves, whatever runs them: + `waybetter build-env -- tauri build`, on every platform. `privacy-scan` is the proof: it searches + files, binaries (UTF-8, UTF-16), archives (npm tarballs, zip, tar, .deb, DMG; NSIS installers and + AppImages through 7-Zip), git-tracked files and, with `--history`, every blob, path, commit + message and identity of a repository for the terms in a file kept outside every repository + (`"forbiddenTerms"` in `waybetter.release.json`, or `WAYBETTER_FORBIDDEN_TERMS`) plus the + machine's account name, and prints hits masked (`m***`). `waybetter release` builds with + `build-env` and refuses to release an artifact with a hit or one it could not open. The `.pdb` + next to a Windows binary still holds every path: never publish it. +- `waybetter strings check `: a string pack (data that replaces the wrapped site's own UI + strings) against the site's string inventory: only inventory keys, parameter names, plural and + select kinds, no markup; prints the coverage. See docs/STRING-PACKS.md. +- `waybetter i18n check|extract`: an app's locale catalogs against the framework's rules (file + shape, keys English lacks, ICU syntax, placeholder parity, plural forms, no markup), the + framework's catalogs in the same languages, the generated `languages.json` and native + localization files (macOS `Info.plist` and `InfoPlist.strings`, the Linux `.desktop` template), + bundled plugins' inline English, and the keys the code looks up; configured by the app's + `waybetter.i18n.json`. +- `waybetter/windows/languages/.nsh`: the installer's messages for the 17 languages + Tauri does not ship itself, generated from the framework catalogs (`wb.installer.*`; + `node packages/waybetter/scripts/installer-languages.mjs --write`). An app lists them under + `bundle.windows.nsis.customLanguageFiles`. +- `waybetter/windows/installer.nsi`: the Windows installer, a template for Tauri's NSIS bundler + (`bundle.windows.nsis.template`). No wizard and no UAC: it installs for the current user, makes + the Desktop and Start menu shortcuts and opens the app. Run again by hand, it only installs when + it is newer than what is installed (an upgrade in place, app data untouched); otherwise it opens + the installed app and exits 0, so an old setup left in Downloads never replaces or downgrades an + install the updater has moved on. `/FORCE` reinstalls the same version (repair), `/NORUN` does + not open the app, `/UPDATE` is the updater's path and always installs. An app renamed after its + first release keeps its registry keys by defining `WAYBETTER_LEGACY_NAME` in its installer hooks + (`bundle.windows.nsis.installerHooks`). + +## Consuming it + +wayBetter for X adds this repository as a git submodule at `waybetter/` and consumes it from source: + +- Rust: a path dependency, `waybetter-host = { path = "../../../waybetter/crates/waybetter-host" }`, + with `features = ["app", "net", "macos-private-api"]` enabled by the app's desktop feature (and + as a build-dependency for `commands::manifest`). +- TypeScript: relative imports of `waybetter/packages/*/src/*.ts`: the X site for the shell frame + (`src/shell/site.tsx`), the page runtime's adapter and a few X modules. Its Vite config dedupes + React, dockview and the Tauri API (the frame's imports use the app's copies) and serves + `bootScript()` as `/boot.js`. The + packages are not Bun workspace members of the app on purpose: the app's server CI clones without + submodules and runs `bun i`, which fails when a declared workspace package is missing; and Node's + type stripping refuses `.ts` files under `node_modules`, while sources outside it work with Bun's + isolated linker on Windows. + +## Dev loop + +`waybetter dev [--stable] --watch ""...` starts the app's watchers, waits for their +first build and runs `tauri dev` (`--stable` adds `--no-watch`: a Rust file saved by someone else +does not restart the app; restart it yourself after Rust changes). Debug builds only: + +- The app names its page scripts with `waybetter_host::page_script!(include_str!("../x.js"), "x.js")` + in `SiteHooks::init_scripts`. A debug build reads the file from disk (path relative to the app + crate, falling back to the embedded copy) each time a tab's init scripts are built and watches it + (`devloop`, using `devmode`'s debounced signature watcher). When it changes, every tab webview is + rebuilt on its current URL through `tabs_sync`, because a webview's document-start scripts are + fixed at creation. Route is kept, scroll is not. About 1 s from save to visible. +- `buildRuntime({ watch: watchRequested(), ... })` (`waybetter/build`) keeps esbuild rebuilding the + file; a failed build leaves the last good one. +- The shell reloads through the frontend dev server (`beforeDevCommand`), instantly. +- Restart needed: Rust, `tauri.conf.json`, capabilities, bundled plugin sources (`include_str!` in the + plugin table; installed plugin files reload with developer mode as before). +- Release builds contain none of it: `devloop` is `cfg(debug_assertions)`, the macro's release arm is + `$embedded.to_owned()` and the path literal is never expanded. `release_guard` (lib.rs) checks that + every mention is gated; `cargo test --release` also runs `release_page_script_is_the_embedded_copy`. +- `.taurignore` the watched output files (`observer.js`, `x-runtime.js`), or plain `tauri dev` restarts + on every rebuild. `create-waybetter` apps get `npm run dev` and `npm run dev:stable`. + +## Scripts (no CI) + +```sh +bun install # typescript + @types/node for the checks +bun run typecheck # tsc over both packages and their tests, and create-waybetter (checkJs) +bun run test # node --test (runtime + shell), cargo test (headless host), create-waybetter +bun run test:ts +bun run test:rust +bun run test:create # scaffolds into temp dirs; its cargo check of an app is ~1 min cold + # (WAYBETTER_SKIP_CARGO_CHECK=1 skips it; needs the local crate cache) +bun run check # typecheck + build:packages + test +bun run check:tauri # cargo check with the app feature (slow: builds Tauri and its plugins) +bun run build # typecheck + cargo build +bun run pack:check # npm pack --dry-run of waybetter and create-waybetter +node packages/waybetter/scripts/installer-languages.mjs [--write] # windows/languages/*.nsh from the catalogs +node packages/shell/scripts/google-fonts-catalog.mjs # the font browser's offline list +``` + +`dev-tools/` has the harnesses for a running or built app (perf probes, the graceful-close check, +tab and webview stress); see its README. + +Requires Bun 1.4.2+, Node 24+ and Rust 1.88+. diff --git a/packages/create-waybetter/README.md b/packages/create-waybetter/README.md index 3d9f921..0ae43bb 100644 --- a/packages/create-waybetter/README.md +++ b/packages/create-waybetter/README.md @@ -6,7 +6,9 @@ npm create waybetter Scaffolds something for [wayBetter](https://waybetter.fyi), the framework behind wayBetter for X: a **plugin**, a **theme**, or a whole new **wayBetter app** for another site. It asks what it needs -when run in a terminal; every answer is also a flag. No dependencies, Node 18.3+. +when run in a terminal; every answer is also a flag. No dependencies, Node 18.3+. Source: [git.crt.fyi/CRT/waybetter](https://git.crt.fyi/CRT/waybetter) +(`packages/create-waybetter`); its tests scaffold each kind into a temporary folder and check the +result against the framework's real contracts. ## Plugin @@ -40,10 +42,14 @@ Presets: `midnight`, `paper`, `dusk`. Import it in **wayBetter → Appearance ## App ```sh -npm create waybetter app -- --site kick.com -npm create waybetter app -- --site youtube.com --name "wayBetter for YouTube" +npm create waybetter app kickapp -- --site kick.com --name "wayBetter for Kick" --yes +npm create waybetter app ytapp -- --site youtube.com --name "wayBetter for YouTube" ``` +The first argument after `app` is the folder to create. The tool then prints its next steps: +`git init && git submodule add https://git.crt.fyi/CRT/waybetter.git waybetter`, `npm install`, +`npm run build`, `npm run tauri dev`, and replacing the placeholder selectors. + A wayBetter app skeleton, the same system as wayBetter for X: a Tauri 2 window with a trusted local shell and one native child webview per site tab (`waybetter-host`), the page runtime and shell models from the `waybetter` package, and the site adapter in its three parts: diff --git a/packages/shell/README.md b/packages/shell/README.md index 5605e57..db0d293 100644 --- a/packages/shell/README.md +++ b/packages/shell/README.md @@ -2,8 +2,8 @@ Sources of `waybetter/shell/*`: the shell models, the Store screens, the shell frame (`src/frame`, `createShell`) and the panel (`src/panel`, `createPanel`: the app's own tab). Published as part of -the [`waybetter`](../waybetter/README.md) package; not published on its own. The repository README's -"The shell frame" and "The panel" sections describe what an app supplies. +the [`waybetter`](../waybetter/README.md) package; not published on its own. The repository's +`docs/ARCHITECTURE.md` ("The shell frame" and "The panel") describes what an app supplies. The panel is here rather than in a package of its own because it is drawn inside the frame and shares its state: the frame's profile, deck, theme, sync and developer-mode stores, its native diff --git a/packages/waybetter/README.md b/packages/waybetter/README.md index 5d8c9c0..f326eb6 100644 --- a/packages/waybetter/README.md +++ b/packages/waybetter/README.md @@ -4,6 +4,12 @@ The framework behind the wayBetter apps: the apps you already use in a light nat window, extended in place the way BetterDiscord extends Discord. Websites and services that ship a heavy Electron client alike: every wayBetter app is the same shell, runtime and one small adapter. +This package is the TypeScript half and the command line. The native half is the Rust crate +`waybetter-host`, which is not on npm: an app takes it from the +[repository](https://git.crt.fyi/CRT/waybetter) as a git submodule or a path dependency. The +repository README explains how the three layers fit together and shows a minimal adapter; +`docs/ARCHITECTURE.md` there lists every module. + - **`waybetter/runtime/*`**: the page runtime. One DOM-mutation/animation-frame hub, one fetch/XHR hub, a plugin API core with a themed UI kit (toasts, alerts, confirmations, prompts, dialogs), a theme API, an OKLab theme color model, split-pane rail hiding, link routing and @@ -180,7 +186,7 @@ or, in a project that installs the package, `"$schema": "./node_modules/waybette ```sh npm create waybetter plugin # *.plugin.js (or --ts) using api.scope, storage, ui and theme npm create waybetter theme # theme JSON with "$schema" pointing at theme.schema.json -npm create waybetter app -- --site youtube.com # a new wayBetter app (Tauri 2 + waybetter-host) +npm create waybetter app myapp -- --site youtube.com # a new wayBetter app (Tauri 2 + waybetter-host) ``` [`create-waybetter`](https://www.npmjs.com/package/create-waybetter) generates code against this @@ -190,7 +196,7 @@ package's real API and schema; `--help` lists every option. | Project | Target | What it is | | --- | --- | --- | -| [wayBetter for X](https://waybetter.fyi/x/) | x.com (website) | Desktop app around the live X: tabs, split panes, real accounts side by side, themes, plugins, drafts and fixes for X's own bugs. The first wayBetter app. | +| [wayBetter for X](https://git.crt.fyi/CRT/waybetter-for-x) | x.com (website) | Desktop app around the live X: tabs, split panes, real accounts side by side, themes, plugins, drafts and fixes for X's own bugs. The first wayBetter app. | Built something on wayBetter? Add it to this list with a pull request: name and link, what it extends, one line on what it does. From 16957f4ea7774624a28d9483df7a13a9021ab98d Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 30 Sep 2026 23:22:36 +0700 Subject: [PATCH 24/72] Theme engine v2, the document side: component tokens, layout variants, decoration, icon packs A theme may now say how each piece of a site is built, not only one radius and one density: - components (themeComponents.ts): 36 generic parts with clamped tokens (radius, border incl. 98.css-style bevels, fill by color role / glass / gradient, padding, sizes, type, shadow, shape, hover/active/focus), presets and parents; compiled over a site's part map as soft values (--wb-part-*) and rigid rules; text on a chosen fill keeps its contrast. - variants (themeVariants.ts): fixed words on six axes; the owner holds an axis or switches layout changes off; the look of a variant is the site's skin. - decoration (themeDecor.ts): dividers, chrome (title bar, masthead, prompt), a focus ring that is always visible, selection, scrollbars, links, motion under reduced-motion. - icon packs (themeIcons.ts): a standalone document of glyphs by semantic name (path data, colored layers or a small PNG, never an SVG document), with license, source and credits; a theme only names a pack; the owner's icon choice is separate; drawn as CSS masks of the current color over the site's own svg boxes, behind forced-colors and mask-support guards, per group. - a theme document gains the optional groups components, variants, decor, icons and colors.actions; a theme without them is sanitized to exactly what it was. - theme.schema.json and the new icons.schema.json are generated from the same tables (scripts/theme-schema.mjs; a test fails when they are stale). Co-Authored-By: Claude Opus 5.5 --- packages/runtime/src/themeChoice.ts | 2 +- packages/runtime/src/themeComponents.ts | 472 ++ packages/runtime/src/themeDecor.ts | 154 + packages/runtime/src/themeIcons.ts | 296 ++ packages/runtime/src/themeSchema.ts | 154 + packages/runtime/src/themeSpec.ts | 52 +- packages/runtime/src/themeVariants.ts | 64 + packages/runtime/tests/themeStructure.test.ts | 278 + packages/waybetter/icons.schema.json | 646 +++ packages/waybetter/package.json | 2 + packages/waybetter/scripts/theme-schema.mjs | 32 + packages/waybetter/theme.schema.json | 4625 ++++++++++++++++- 12 files changed, 6689 insertions(+), 88 deletions(-) create mode 100644 packages/runtime/src/themeComponents.ts create mode 100644 packages/runtime/src/themeDecor.ts create mode 100644 packages/runtime/src/themeIcons.ts create mode 100644 packages/runtime/src/themeSchema.ts create mode 100644 packages/runtime/src/themeVariants.ts create mode 100644 packages/runtime/tests/themeStructure.test.ts create mode 100644 packages/waybetter/icons.schema.json create mode 100644 packages/waybetter/scripts/theme-schema.mjs diff --git a/packages/runtime/src/themeChoice.ts b/packages/runtime/src/themeChoice.ts index 300eaa7..fc021e4 100644 --- a/packages/runtime/src/themeChoice.ts +++ b/packages/runtime/src/themeChoice.ts @@ -10,7 +10,7 @@ export type ThemeChoice = { preset: string; accent: string | null; overrides: Th /** Imported themes kept in a choice (the JSON Schema of the native side says the same). */ export const MAX_USER_THEMES = 24; -const OVERRIDE_GROUPS = ['colors', 'font', 'shape', 'layout', 'background', 'effects', 'css'] as const; +const OVERRIDE_GROUPS = ['colors', 'font', 'shape', 'layout', 'background', 'effects', 'css', 'variants'] as const; export type ThemeCatalog = { /** The site's built-in themes; the first is its own look (and the default choice). */ diff --git a/packages/runtime/src/themeComponents.ts b/packages/runtime/src/themeComponents.ts new file mode 100644 index 0000000..340a518 --- /dev/null +++ b/packages/runtime/src/themeComponents.ts @@ -0,0 +1,472 @@ +// Component tokens: the part of a theme that says how each piece of the site is built (a button's +// radius and border, a post's padding and fill, the size and case of a handle), instead of one radius +// and one density for everything. A theme names generic components (`post`, `buttonPrimary`, +// `navItem`); the site adapter says which selectors they are (its part map). Pure. +// +// Safety is the same as the rest of a theme document: every token is a clamped number, a fixed word +// or a color role name. No token carries CSS text, a selector or a color literal, so one contrast +// pass over the palette covers every component, and the CSS is built from the vocabulary below. +// +// How it lands in the page: values are custom properties at zero specificity +// (`:where(:root){--wb-part-post-radius:0px}`), rules are rigid (`:root:root {border-radius: +// var(--wb-part-post-radius) !important}`). An owner's Custom CSS or a plugin overrides a value by +// setting the variable, for the whole page or for one subtree, without fighting `!important`. +// +// The bevel borders (`bevel-out`, `bevel-in`) follow 98.css's raised and sunken edges (MIT, Jordan +// Scales, https://github.com/jdan/98.css): four inset shadows, here computed from the theme's roles. + +import { contrastRatio, hexToRgb, mix, relativeLuminance, type FontRoleName } from './themeApi.ts'; + +// --------------------------------------------------------------------------------------------- +// Vocabulary + +/** Color roles a component may name. `onAccent` is the readable label on the accent. */ +export const COLOR_ROLES = ['bg', 'surface', 'elevated', 'page', 'border', 'text', 'muted', 'accent', 'onAccent', 'inverse', 'onInverse'] as const; +export type ColorRole = typeof COLOR_ROLES[number]; +export type RoleColors = Record; + +export const BORDER_STYLES = ['none', 'solid', 'dashed', 'dotted', 'double', 'bevel-out', 'bevel-in'] as const; +export const SHADOWS = ['none', 'soft', 'deep', 'hard', 'inset', 'glow'] as const; +export const CASES = ['none', 'upper', 'lower', 'capitalize', 'small-caps'] as const; +export const AVATAR_SHAPES = ['circle', 'rounded', 'square', 'squircle', 'hexagon', 'octagon', 'diamond'] as const; +export const CORNERS = ['round', 'cut'] as const; +const FONT_ROLES: readonly FontRoleName[] = ['interface', 'post', 'heading', 'numbers', 'mono', 'chrome', 'dialog']; + +export type Gradient = { from: ColorRole; to: ColorRole; angle: number }; +export type Fill = ColorRole | 'transparent' | 'glass' | Gradient; +export type StateTokens = { fill?: Fill; text?: ColorRole; borderColor?: ColorRole; shadow?: typeof SHADOWS[number]; lift?: number; scale?: number; underline?: boolean }; +export type ComponentTokens = { + preset?: string; + radius?: number | 'pill'; + borderWidth?: number; + borderStyle?: typeof BORDER_STYLES[number]; + borderColor?: ColorRole; + fill?: Fill; + text?: ColorRole; + padX?: number; + padY?: number; + gap?: number; + height?: number; + width?: number; + size?: number; + maxHeight?: number; + font?: FontRoleName; + fontSize?: number; + weight?: number; + case?: typeof CASES[number]; + tracking?: number; + leading?: number; + shadow?: typeof SHADOWS[number]; + shape?: typeof AVATAR_SHAPES[number]; + corner?: typeof CORNERS[number]; + visible?: boolean; + hover?: StateTokens; + active?: StateTokens; + focus?: StateTokens; +}; + +type ComponentDef = { + /** Tokens set on the parent apply to this component too. */ + parent?: string; + /** A text part: type tokens land on its leaves. */ + text?: boolean; + /** Size ranges in px (absent: the token is not accepted on this component). */ + height?: [number, number]; width?: [number, number]; size?: [number, number]; maxHeight?: [number, number]; fontSize?: [number, number]; + /** Tokens only some components take. */ + shape?: boolean; corner?: boolean; visible?: boolean; + /** Glass fills (a blur) are allowed here; never on parts that repeat down a timeline. */ + glass?: boolean; + /** Gradient fills are allowed here (bars and buttons). */ + gradient?: boolean; + /** Presets of this component's family. */ + presets?: keyof typeof PRESETS; + /** Contrast its text must reach on its own fill. */ + contrast?: number; +}; + +const LABEL: [number, number] = [12, 20]; +const SMALL: [number, number] = [11, 18]; +/** Every component a theme can name. Sites map them to selectors; a component a site does not have is ignored. */ +export const COMPONENTS = { + nav: { width: [56, 320], glass: true, gradient: true }, + navItem: { height: [36, 64], fontSize: LABEL, text: true }, + topBar: { height: [40, 64], glass: true, gradient: true, fontSize: LABEL }, + tabs: { presets: 'tabs', gradient: true }, + tab: { height: [32, 56], fontSize: LABEL, text: true, presets: 'tabs' }, + post: { corner: true, presets: 'post', contrast: 7 }, + avatar: { size: [20, 64], shape: true, visible: true }, + displayName: { text: true, fontSize: LABEL, visible: true }, + handle: { text: true, fontSize: SMALL, visible: true }, + postText: { text: true, fontSize: [13, 24], contrast: 7 }, + meta: { text: true, fontSize: SMALL }, + actionBar: {}, + action: { size: [28, 44] }, + count: { text: true, fontSize: SMALL, visible: true }, + media: { corner: true, maxHeight: [200, 700] }, + linkCard: { corner: true }, + quote: {}, + button: { height: [24, 56], fontSize: LABEL, text: true, gradient: true, presets: 'button' }, + buttonPrimary: { parent: 'button', height: [24, 56], fontSize: LABEL, text: true, gradient: true, presets: 'button' }, + buttonSecondary: { parent: 'button', height: [24, 56], fontSize: LABEL, text: true, gradient: true, presets: 'button' }, + buttonGhost: { parent: 'button', height: [24, 56], fontSize: LABEL, text: true, gradient: true, presets: 'button' }, + input: { height: [32, 56], fontSize: LABEL, text: true, presets: 'input' }, + search: { height: [32, 56], fontSize: LABEL, text: true, presets: 'input' }, + composer: { fontSize: [13, 24], text: true }, + /** The tool icons under a composer (media, poll, emoji); `text` is their color. */ + composerTool: { size: [28, 44] }, + panel: { glass: true, presets: 'panel' }, + menu: { parent: 'panel', glass: true, presets: 'panel' }, + dialog: { parent: 'panel', glass: true, presets: 'panel' }, + toast: { parent: 'panel', glass: true, presets: 'panel' }, + hoverCard: { parent: 'panel', glass: true, presets: 'panel' }, + sidebarCard: { parent: 'panel', glass: true, corner: true, presets: 'panel' }, + badge: { size: [14, 24], corner: true, fontSize: SMALL, text: true }, + pill: { fontSize: SMALL, text: true }, + divider: {}, + scrollbar: {}, + profileHeader: {}, +} as const satisfies Record; +export type ComponentId = keyof typeof COMPONENTS; +export const COMPONENT_IDS = Object.keys(COMPONENTS) as ComponentId[]; +export type ThemeComponents = Partial>; + +/** Clamp ranges of the tokens every component shares (the JSON Schema says the same; tested). */ +export const TOKEN_LIMITS = { + radius: [0, 32], borderWidth: [0, 4], padX: [0, 32], padY: [0, 32], gap: [0, 24], weight: [100, 900], + tracking: [-0.05, 0.2], leading: [1.1, 2], angle: [0, 360], lift: [0, 4], scale: [0.96, 1.04], +} as const; + +/** Named token bundles per family; a theme's own tokens win over its preset's. Frozen once shipped. */ +export const PRESETS = { + button: { + pill: { radius: 'pill', borderWidth: 0 }, + soft: { radius: 8, borderWidth: 0 }, + square: { radius: 0, borderWidth: 1, borderStyle: 'solid' }, + outline: { radius: 6, borderWidth: 1, borderStyle: 'solid', fill: 'transparent', text: 'text', borderColor: 'border' }, + bevel: { radius: 0, borderStyle: 'bevel-out', fill: 'surface', text: 'text', active: { shadow: 'inset' } }, + gloss: { radius: 'pill', borderWidth: 1, borderStyle: 'solid', shadow: 'soft' }, + 'flat-link': { radius: 0, borderWidth: 0, fill: 'transparent', text: 'accent', hover: { underline: true } }, + }, + post: { + flat: { radius: 0, borderWidth: 0, fill: 'transparent', shadow: 'none' }, + card: { radius: 14, borderWidth: 1, borderStyle: 'solid', borderColor: 'border', fill: 'surface' }, + bubble: { radius: 20, borderWidth: 0, fill: 'surface' }, + window: { radius: 0, borderStyle: 'bevel-out', fill: 'surface' }, + ruled: { radius: 0, borderWidth: 0, fill: 'transparent' }, + }, + input: { + pill: { radius: 'pill', borderWidth: 1, borderStyle: 'solid', borderColor: 'border' }, + underline: { radius: 0, borderWidth: 0, fill: 'transparent' }, + sunken: { radius: 0, borderStyle: 'bevel-in', fill: 'bg', text: 'text' }, + boxed: { radius: 4, borderWidth: 1, borderStyle: 'solid', borderColor: 'border', fill: 'bg' }, + }, + panel: { + sheet: { radius: 12, borderWidth: 1, borderStyle: 'solid', borderColor: 'border', fill: 'surface', shadow: 'soft' }, + window: { radius: 0, borderStyle: 'bevel-out', fill: 'surface', shadow: 'none' }, + glass: { radius: 16, borderWidth: 1, borderStyle: 'solid', borderColor: 'border', fill: 'glass', shadow: 'soft' }, + }, + tabs: { + underline: { radius: 0 }, + pills: { radius: 'pill' }, + folder: { radius: 6, borderWidth: 1, borderStyle: 'solid', borderColor: 'border' }, + blocks: { radius: 0, borderWidth: 1, borderStyle: 'solid', borderColor: 'border' }, + }, +} as const satisfies Record>; + +// --------------------------------------------------------------------------------------------- +// Sanitizing + +const obj = (value: unknown): Record => value && typeof value === 'object' && !Array.isArray(value) ? value as Record : {}; +const finite = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value); +const clamp = (value: number, [min, max]: readonly [number, number]) => Math.min(max, Math.max(min, value)); +const oneOf = (value: unknown, options: readonly T[]): T | undefined => options.includes(value as T) ? value as T : undefined; +const role = (value: unknown) => oneOf(value, COLOR_ROLES); + +function sanitizeFill(value: unknown, def: ComponentDef): Fill | undefined { + if (value === 'transparent') return 'transparent'; + if (value === 'glass') return def.glass ? 'glass' : undefined; + const named = role(value); + if (named) return named; + const source = obj(value); + const from = role(source.from), to = role(source.to); + if (def.gradient && from && to) return { from, to, angle: Math.round(clamp(finite(source.angle) ? source.angle : 180, TOKEN_LIMITS.angle)) }; + return undefined; +} + +function sanitizeState(value: unknown, def: ComponentDef): StateTokens | undefined { + const source = obj(value); + const out: StateTokens = {}; + const fill = sanitizeFill(source.fill, def); if (fill !== undefined) out.fill = fill; + const text = role(source.text); if (text) out.text = text; + const borderColor = role(source.borderColor); if (borderColor) out.borderColor = borderColor; + const shadow = oneOf(source.shadow, SHADOWS); if (shadow) out.shadow = shadow; + if (finite(source.lift)) out.lift = +clamp(source.lift, TOKEN_LIMITS.lift).toFixed(1); + if (finite(source.scale)) out.scale = +clamp(source.scale, TOKEN_LIMITS.scale).toFixed(3); + if (typeof source.underline === 'boolean') out.underline = source.underline; + return Object.keys(out).length ? out : undefined; +} + +/** One component's tokens from JSON: clamped, unknown names and tokens the component does not take dropped. */ +export function sanitizeComponentTokens(id: ComponentId, value: unknown): ComponentTokens | undefined { + const def: ComponentDef = COMPONENTS[id]; + const source = obj(value); + const out: ComponentTokens = {}; + if (def.presets && typeof source.preset === 'string' && Object.hasOwn(PRESETS[def.presets], source.preset)) out.preset = source.preset; + if (source.radius === 'pill') out.radius = 'pill'; + else if (finite(source.radius)) out.radius = Math.round(clamp(source.radius, TOKEN_LIMITS.radius)); + if (finite(source.borderWidth)) out.borderWidth = +clamp(source.borderWidth, TOKEN_LIMITS.borderWidth).toFixed(1); + const borderStyle = oneOf(source.borderStyle, BORDER_STYLES); if (borderStyle) out.borderStyle = borderStyle; + const borderColor = role(source.borderColor); if (borderColor) out.borderColor = borderColor; + const fill = sanitizeFill(source.fill, def); if (fill !== undefined) out.fill = fill; + const text = role(source.text); if (text) out.text = text; + for (const key of ['padX', 'padY', 'gap'] as const) if (finite(source[key])) out[key] = Math.round(clamp(source[key] as number, TOKEN_LIMITS[key])); + for (const key of ['height', 'width', 'size', 'maxHeight', 'fontSize'] as const) { + const range = def[key]; + if (range && finite(source[key])) out[key] = Math.round(clamp(source[key] as number, range)); + } + if (def.text || def.fontSize) { + const font = oneOf(source.font, FONT_ROLES); if (font) out.font = font; + if (finite(source.weight)) out.weight = Math.round(clamp(source.weight, TOKEN_LIMITS.weight) / 50) * 50; + const textCase = oneOf(source.case, CASES); if (textCase && id !== 'postText') out.case = textCase; + if (finite(source.tracking)) out.tracking = +clamp(source.tracking, TOKEN_LIMITS.tracking).toFixed(3); + if (finite(source.leading)) out.leading = +clamp(source.leading, TOKEN_LIMITS.leading).toFixed(2); + } + const shadow = oneOf(source.shadow, SHADOWS); if (shadow) out.shadow = shadow; + if (def.shape) { const shape = oneOf(source.shape, AVATAR_SHAPES); if (shape) out.shape = shape; } + if (def.corner) { const corner = oneOf(source.corner, CORNERS); if (corner) out.corner = corner; } + if (def.visible && typeof source.visible === 'boolean') out.visible = source.visible; + for (const state of ['hover', 'active', 'focus'] as const) { const tokens = sanitizeState(source[state], def); if (tokens) out[state] = tokens; } + return Object.keys(out).length ? out : undefined; +} + +/** The `components` group from JSON. Null when nothing valid is left (the theme sets no component). */ +export function sanitizeComponents(value: unknown): ThemeComponents | null { + const source = obj(value); + const out: ThemeComponents = {}; + for (const id of COMPONENT_IDS) { + if (!Object.hasOwn(source, id)) continue; + const tokens = sanitizeComponentTokens(id, source[id]); + if (tokens) out[id] = tokens; + } + return Object.keys(out).length ? out : null; +} + +/** Every component with its preset and its parent's tokens folded in (own tokens win, then the preset, then the parent). */ +export function resolveComponents(components: ThemeComponents): ThemeComponents { + const expand = (id: ComponentId, tokens: ComponentTokens | undefined): ComponentTokens => { + if (!tokens) return {}; + const def: ComponentDef = COMPONENTS[id]; + const preset = tokens.preset && def.presets ? (PRESETS[def.presets] as Record)[tokens.preset] : undefined; + const { preset: _name, ...own } = tokens; + return { ...preset, ...own }; + }; + const out: ThemeComponents = {}; + for (const id of COMPONENT_IDS) { + const def: ComponentDef = COMPONENTS[id]; + const parent = def.parent as ComponentId | undefined; + const inherited = parent ? expand(parent, components[parent]) : {}; + const merged = { ...inherited, ...expand(id, components[id]) }; + if (Object.keys(merged).length) out[id] = merged; + } + return out; +} + +// --------------------------------------------------------------------------------------------- +// Compiling + +/** A site's selectors for one component. */ +export type PartDef = { + /** The component's box. */ + sel: string; + /** Its text leaves (sites often put type on leaf spans); defaults to the box. */ + text?: string; + /** Where a fill is painted when it is not the box itself. */ + fill?: string; + /** Tokens the site cannot honor on this part (left out of the CSS). */ + skip?: ReadonlyArray; +}; +export type PartMap = Partial>; + +export type ComponentContext = { + /** Every role as `#rrggbb` (the theme's palette, legible). */ + colors: RoleColors; + /** `font-family` per font role. */ + fonts: Record; +}; + +const rgba = (hex: string, alpha: number) => `rgba(${hexToRgb(hex).join(', ')}, ${alpha})`; +const dark = (hex: string) => relativeLuminance(hex) < 0.18; + +/** The most readable of the theme's text-capable roles on `fill`. */ +export function readableRole(fill: string, colors: RoleColors, preferred?: ColorRole): ColorRole { + const candidates: ColorRole[] = ['text', 'onAccent', 'onInverse', 'bg', 'inverse']; + if (preferred && !candidates.includes(preferred)) candidates.unshift(preferred); + return candidates.reduce((best, candidate) => contrastRatio(colors[candidate], fill) > contrastRatio(colors[best], fill) ? candidate : best, preferred ?? 'text'); +} + +function fillCss(fill: Fill, colors: RoleColors): { decl: Array<[string, string]>; solid: string | null } { + if (fill === 'transparent') return { decl: [['background-color', 'transparent'], ['background-image', 'none']], solid: null }; + if (fill === 'glass') return { decl: [['background-color', rgba(colors.surface, 0.72)], ['backdrop-filter', 'blur(14px) saturate(1.4)'], ['-webkit-backdrop-filter', 'blur(14px) saturate(1.4)']], solid: colors.surface }; + if (typeof fill === 'string') return { decl: [['background-color', colors[fill]], ['background-image', 'none']], solid: colors[fill] }; + // A gradient is judged at its less readable end: the midpoint stands in for both when choosing a label. + return { decl: [['background-color', colors[fill.to]], ['background-image', `linear-gradient(${fill.angle}deg, ${colors[fill.from]}, ${colors[fill.to]})`]], solid: mix(colors[fill.from], colors[fill.to], 0.5) }; +} + +/** Raised and sunken edges after 98.css: two light and two dark inset lines, from the part's own fill. */ +function bevel(out: boolean, face: string): string { + const light = mix(face, '#ffffff', 0.85), soft = mix(face, '#ffffff', 0.35), shade = mix(face, '#000000', 0.35), deep = mix(face, '#000000', 0.9); + return out + ? `inset -1px -1px ${deep}, inset 1px 1px ${light}, inset -2px -2px ${shade}, inset 2px 2px ${soft}` + : `inset -1px -1px ${light}, inset 1px 1px ${shade}, inset -2px -2px ${soft}, inset 2px 2px ${deep}`; +} + +function shadowCss(name: typeof SHADOWS[number], colors: RoleColors): string { + const base = dark(colors.bg); + switch (name) { + case 'soft': return base ? `0 1px 2px ${rgba('#000000', 0.4)}, 0 8px 24px ${rgba('#000000', 0.35)}` : `0 1px 2px ${rgba('#000000', 0.06)}, 0 8px 24px ${rgba('#000000', 0.1)}`; + case 'deep': return `0 0 0 1px ${rgba(colors.border, 0.6)}, 0 24px 64px ${rgba('#000000', base ? 0.6 : 0.28)}`; + case 'hard': return `4px 4px 0 ${colors.accent}`; + case 'inset': return `inset 1px 1px 3px ${rgba('#000000', base ? 0.6 : 0.25)}`; + case 'glow': return `0 0 0 1px ${rgba(colors.accent, 0.5)}, 0 0 18px ${rgba(colors.accent, 0.35)}`; + default: return 'none'; + } +} + +const SHAPES: Record> = { + circle: [['border-radius', '50%']], + rounded: [['border-radius', '26%']], + square: [['border-radius', '2px']], + squircle: [['border-radius', '34%']], + hexagon: [['border-radius', '0'], ['clip-path', 'polygon(25% 4%, 75% 4%, 100% 50%, 75% 96%, 25% 96%, 0 50%)']], + octagon: [['border-radius', '0'], ['clip-path', 'polygon(30% 0, 70% 0, 100% 30%, 100% 70%, 70% 100%, 30% 100%, 0 70%, 0 30%)']], + diamond: [['border-radius', '0'], ['clip-path', 'polygon(50% 0, 100% 50%, 50% 100%, 0 50%)']], +}; +const CASE_CSS: Record> = { + none: [['text-transform', 'none'], ['font-variant-caps', 'normal']], + upper: [['text-transform', 'uppercase']], + lower: [['text-transform', 'lowercase']], + capitalize: [['text-transform', 'capitalize']], + 'small-caps': [['text-transform', 'none'], ['font-variant-caps', 'all-small-caps']], +}; + +/** A part rule's selector: two `:root`s lift it over the site's atomic classes and inline styles' non-important values. */ +export const partRule = (selector: string) => selector.split(/,(?![^(]*\))/).map(one => `:root:root ${one.trim()}`).join(','); + +export type CompiledComponents = { + /** `--wb-part-*` declarations (for `:where(:root)`). */ + values: string[]; + /** Rules that read them. */ + rules: string[]; + /** What the contrast pass changed, for import notes and the builder's report. */ + notes: string[]; +}; + +/** + * CSS for a theme's components over a site's part map. A component without a part, and a token the + * part skips, emits nothing. Text on a fill the theme chose is held to the component's contrast + * (the text role is swapped for the most readable one); sizes stay at or above a 24px target. + */ +export function compileComponents(components: ThemeComponents, parts: PartMap, ctx: ComponentContext): CompiledComponents { + const values: string[] = [], rules: string[] = [], notes: string[] = []; + const resolved = resolveComponents(components); + for (const id of COMPONENT_IDS) { + const tokens = resolved[id], part = parts[id]; + if (!tokens || !part) continue; + const def: ComponentDef = COMPONENTS[id]; + const skip = new Set(part.skip ?? []); + const has = (key: K): boolean => tokens[key] !== undefined && !skip.has(key); + const box: string[] = [], type: string[] = [], fillRule: string[] = []; + const put = (list: string[], token: string, property: string, value: string) => { + const name = `--wb-part-${id}-${token}`; + if (!values.some(item => item.startsWith(`${name}:`))) values.push(`${name}:${value}`); + list.push(`${property}:var(${name}) !important`); + }; + + // Fill first: the text role depends on it. + let face: string | null = null; + if (has('fill')) { + const { decl, solid } = fillCss(tokens.fill!, ctx.colors); + face = solid; + decl.forEach(([property, value], index) => put(part.fill ? fillRule : box, `fill${index ? `-${index}` : ''}`, property, value)); + } + let textRole = has('text') ? tokens.text! : undefined; + if (face && (def.text || textRole)) { + const need = def.contrast ?? 4.5; + if (!textRole || contrastRatio(ctx.colors[textRole], face) < need) { + const readable = readableRole(face, ctx.colors, textRole); + if (textRole && readable !== textRole) notes.push(`${id}: text "${textRole}" on its fill is under ${need}:1, using "${readable}"`); + textRole = readable; + } + } + if (textRole) put(type, 'text', 'color', ctx.colors[textRole]); + + if (has('radius')) put(box, 'radius', 'border-radius', tokens.radius === 'pill' ? '9999px' : `${tokens.radius}px`); + const style = has('borderStyle') ? tokens.borderStyle! : undefined; + if (style === 'bevel-out' || style === 'bevel-in') { + const base = face ?? ctx.colors.surface; + put(box, 'border-style', 'border-style', 'none'); + put(box, 'bevel', 'box-shadow', bevel(style === 'bevel-out', base)); + } else { + if (style) put(box, 'border-style', 'border-style', style); + if (has('borderWidth')) put(box, 'border-width', 'border-width', `${tokens.borderWidth}px`); + // A width without a style would draw nothing: X's boxes are `border: 0 solid`. + if (has('borderWidth') && !style && tokens.borderWidth! > 0) put(box, 'border-style', 'border-style', 'solid'); + if (has('shadow')) put(box, 'shadow', 'box-shadow', shadowCss(tokens.shadow!, ctx.colors)); + } + if (has('borderColor')) put(box, 'border-color', 'border-color', ctx.colors[tokens.borderColor!]); + if (has('padX')) put(box, 'pad-x', 'padding-inline', `${tokens.padX}px`); + if (has('padY')) put(box, 'pad-y', 'padding-block', `${tokens.padY}px`); + if (has('gap')) put(box, 'gap', 'gap', `${tokens.gap}px`); + if (has('height')) put(box, 'height', 'min-height', `${Math.max(24, tokens.height!)}px`); + if (has('width')) put(box, 'width', 'width', `${tokens.width}px`); + if (has('size')) { put(box, 'size', 'width', `${tokens.size}px`); box.push(`height:var(--wb-part-${id}-size) !important`); } + if (has('maxHeight')) put(box, 'max-height', 'max-height', `${tokens.maxHeight}px`); + if (has('shape')) SHAPES[tokens.shape!].forEach(([property, value], index) => put(box, `shape${index ? `-${index}` : ''}`, property, value)); + if (has('corner') && tokens.corner === 'cut') put(box, 'corner', 'clip-path', 'polygon(0 0, calc(100% - 12px) 0, 100% 12px, 100% 100%, 12px 100%, 0 calc(100% - 12px))'); + if (has('visible') && tokens.visible === false) put(box, 'display', 'display', 'none'); + + if (has('font')) put(type, 'font', 'font-family', ctx.fonts[tokens.font!]); + if (has('fontSize')) { + put(type, 'font-size', 'font-size', `${tokens.fontSize}px`); + put(type, 'line-height', 'line-height', String(tokens.leading ?? 1.3)); + } else if (has('leading')) put(type, 'line-height', 'line-height', String(tokens.leading)); + if (has('weight')) put(type, 'weight', 'font-weight', String(tokens.weight)); + if (has('case')) CASE_CSS[tokens.case!].forEach(([property, value], index) => put(type, `case${index ? `-${index}` : ''}`, property, value)); + if (has('tracking')) put(type, 'tracking', 'letter-spacing', `${tokens.tracking}em`); + + const textSel = part.text ?? part.sel; + if (box.length) rules.push(`${partRule(part.sel)}{${box.join(';')}}`); + if (fillRule.length) rules.push(`${partRule(part.fill!)}{${fillRule.join(';')}}`); + if (type.length) rules.push(`${partRule(textSel)}{${type.join(';')}}`); + + for (const state of ['hover', 'active', 'focus'] as const) { + const tokensOf = tokens[state]; + if (!tokensOf || skip.has(state)) continue; + const pseudo = state === 'focus' ? ':focus-visible' : `:${state}`; + const still: string[] = [], moving: string[] = [], label: string[] = []; + let stateFace = face; + if (tokensOf.fill !== undefined) { const { decl, solid } = fillCss(tokensOf.fill, ctx.colors); stateFace = solid ?? face; for (const [property, value] of decl) still.push(`${property}:${value} !important`); } + let stateText = tokensOf.text; + if (stateFace && (stateText || tokensOf.fill !== undefined) && (def.text || stateText)) { + if (!stateText || contrastRatio(ctx.colors[stateText], stateFace) < (def.contrast ?? 4.5)) stateText = readableRole(stateFace, ctx.colors, stateText); + } + if (stateText) label.push(`color:${ctx.colors[stateText]} !important`); + if (tokensOf.underline !== undefined) label.push(`text-decoration:${tokensOf.underline ? 'underline' : 'none'} !important`); + if (tokensOf.borderColor) still.push(`border-color:${ctx.colors[tokensOf.borderColor]} !important`); + if (tokensOf.shadow) still.push(`box-shadow:${tokensOf.shadow === 'inset' && (style === 'bevel-out' || style === 'bevel-in') ? bevel(false, face ?? ctx.colors.surface) : shadowCss(tokensOf.shadow, ctx.colors)} !important`); + const transforms = [tokensOf.lift ? `translateY(-${tokensOf.lift}px)` : '', tokensOf.scale && tokensOf.scale !== 1 ? `scale(${tokensOf.scale})` : ''].filter(Boolean); + if (transforms.length) moving.push(`transform:${transforms.join(' ')} !important`); + const stateSel = (selector: string) => selector.split(/,(?![^(]*\))/).map(one => `${one.trim()}${pseudo}`).join(','); + if (still.length) rules.push(`${partRule(stateSel(part.sel))}{${still.join(';')}}`); + // The label of a hovered or pressed part: the box and the text leaves under it. + if (label.length) rules.push(`${partRule(`${stateSel(part.sel)},${part.sel.split(/,(?![^(]*\))/).map(one => `${one.trim()}${pseudo} :is(span,div,a)`).join(',')}`)}{${label.join(';')}}`); + // Movement only for people who have not asked for less of it. + if (moving.length) rules.push(`@media (prefers-reduced-motion:no-preference){${partRule(stateSel(part.sel))}{${moving.join(';')}}}`); + } + } + return { values, rules, notes }; +} + +/** The `colors.actions` group: the colors of an on state (liked, reposted, bookmarked) and of the reply hover. */ +export const ACTION_NAMES = ['reply', 'repost', 'like', 'bookmark'] as const; +export type ActionColors = Partial>; diff --git a/packages/runtime/src/themeDecor.ts b/packages/runtime/src/themeDecor.ts new file mode 100644 index 0000000..1733232 --- /dev/null +++ b/packages/runtime/src/themeDecor.ts @@ -0,0 +1,154 @@ +// Decoration: what a theme draws between and around the components: divider lines, a title bar or a +// masthead, the focus ring, selection, scrollbars, link underlines, the feel of motion. Fixed words +// and clamped numbers, colors by role. Where the lines and bars go is the site's (its decor targets). +// Pure. + +import { contrastRatio } from './themeApi.ts'; +import { COLOR_ROLES, type ColorRole, type RoleColors } from './themeComponents.ts'; + +export const DIVIDER_STYLES = ['none', 'hairline', 'solid', 'dashed', 'dotted', 'double'] as const; +export const CHROME_KINDS = ['none', 'titlebar', 'masthead', 'prompt'] as const; +export const RING_STYLES = ['solid', 'dashed', 'dotted', 'double'] as const; +export const MOTION_CURVES = ['standard', 'snappy', 'spring', 'linear', 'steps'] as const; +export const LINK_UNDERLINES = ['always', 'hover', 'never'] as const; + +export type ThemeDecor = { + dividers?: { style: typeof DIVIDER_STYLES[number]; color?: ColorRole; width?: number }; + /** A drawn frame around the main column: a window title bar, a newspaper masthead, a terminal prompt. `title` is plain text. */ + chrome?: { kind: typeof CHROME_KINDS[number]; title?: string }; + focusRing?: { width?: number; style?: typeof RING_STYLES[number]; color?: ColorRole; offset?: number }; + selection?: { fill: ColorRole; text: ColorRole }; + scrollbar?: { width?: 'auto' | 'thin'; thumb?: ColorRole; track?: ColorRole; style?: 'flat' | 'classic' }; + links?: { underline: typeof LINK_UNDERLINES[number] }; + motion?: { duration?: number; curve?: typeof MOTION_CURVES[number]; press?: number }; +}; + +const obj = (value: unknown): Record => value && typeof value === 'object' && !Array.isArray(value) ? value as Record : {}; +const oneOf = (value: unknown, options: readonly T[]): T | undefined => options.includes(value as T) ? value as T : undefined; +const num = (value: unknown, min: number, max: number): number | undefined => typeof value === 'number' && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : undefined; +const role = (value: unknown) => oneOf(value, COLOR_ROLES); +/** Text a theme may put into a drawn bar: letters, digits, spaces and a little punctuation; it is written into a CSS string. */ +export const chromeTitle = (value: unknown) => typeof value === 'string' ? value.replace(/[^\p{L}\p{N} .,:!?&+\-_/#@*~()[\]|>$]/gu, '').replace(/&/g, '+').trim().slice(0, 24) : ''; + +/** The `decor` group from JSON. Null when nothing valid is left. */ +export function sanitizeDecor(value: unknown): ThemeDecor | null { + const source = obj(value); + const out: ThemeDecor = {}; + const dividers = obj(source.dividers), dividerStyle = oneOf(dividers.style, DIVIDER_STYLES); + if (dividerStyle) { + const color = role(dividers.color), width = num(dividers.width, 0, 3); + out.dividers = { style: dividerStyle, ...(color ? { color } : {}), ...(width !== undefined ? { width: +width.toFixed(1) } : {}) }; + } + const chrome = obj(source.chrome), kind = oneOf(chrome.kind, CHROME_KINDS); + if (kind && kind !== 'none') { const title = chromeTitle(chrome.title); out.chrome = { kind, ...(title ? { title } : {}) }; } + const ring = obj(source.focusRing); + if (Object.keys(ring).length) { + const width = num(ring.width, 2, 4), style = oneOf(ring.style, RING_STYLES), color = role(ring.color), offset = num(ring.offset, 0, 4); + const focusRing = { ...(width !== undefined ? { width: Math.round(width) } : {}), ...(style ? { style } : {}), ...(color ? { color } : {}), ...(offset !== undefined ? { offset: Math.round(offset) } : {}) }; + if (Object.keys(focusRing).length) out.focusRing = focusRing; + } + const selection = obj(source.selection), fill = role(selection.fill), text = role(selection.text); + if (fill && text) out.selection = { fill, text }; + const bar = obj(source.scrollbar); + if (Object.keys(bar).length) { + const width = oneOf(bar.width, ['auto', 'thin'] as const), thumb = role(bar.thumb), track = role(bar.track), style = oneOf(bar.style, ['flat', 'classic'] as const); + const scrollbar = { ...(width ? { width } : {}), ...(thumb ? { thumb } : {}), ...(track ? { track } : {}), ...(style ? { style } : {}) }; + if (Object.keys(scrollbar).length) out.scrollbar = scrollbar; + } + const underline = oneOf(obj(source.links).underline, LINK_UNDERLINES); + if (underline) out.links = { underline }; + const motion = obj(source.motion); + if (Object.keys(motion).length) { + const duration = num(motion.duration, 0, 400), curve = oneOf(motion.curve, MOTION_CURVES), press = num(motion.press, 0.96, 1); + const value = { ...(duration !== undefined ? { duration: Math.round(duration) } : {}), ...(curve ? { curve } : {}), ...(press !== undefined ? { press: +press.toFixed(3) } : {}) }; + if (Object.keys(value).length) out.motion = value; + } + return Object.keys(out).length ? out : null; +} + +/** Where a site's decoration goes. Every entry is optional: a site without it draws nothing for that key. */ +export type DecorTargets = { + /** Rows whose bottom edge is the divider between items (a site's list cells). */ + divider?: string; + /** Links inside running text. */ + link?: string; + /** What takes keyboard focus. */ + focusable?: string; + /** What moves with `motion` (buttons, links, rows). */ + moving?: string; + /** What a press shrinks. */ + pressable?: string; + /** The scrollable roots. */ + scroller?: string; + /** The site's drawing of each chrome kind. */ + chrome?: Partial, (title: string, ctx: Context) => string>>; +}; + +const CURVES: Record = { + standard: 'cubic-bezier(.2,.7,.2,1)', snappy: 'cubic-bezier(.3,1.4,.5,1)', spring: 'cubic-bezier(.2,1.6,.4,1)', linear: 'linear', steps: 'steps(3,end)', +}; + +/** The role among `candidates` that reaches `ratio` on every surface, else the most visible one. */ +function visibleOn(colors: RoleColors, wanted: ColorRole, surfaces: string[], ratio: number): string { + const worst = (hex: string) => Math.min(...surfaces.map(surface => contrastRatio(hex, surface))); + if (worst(colors[wanted]) >= ratio) return colors[wanted]; + return (['accent', 'text', 'inverse'] as ColorRole[]).map(name => colors[name]).reduce((best, hex) => worst(hex) > worst(best) ? hex : best, colors[wanted]); +} + +/** + * CSS for a theme's decoration. A focus ring is always drawn when the theme names one (at least 2px + * and 3:1 on the page's surfaces: the color is swapped for a visible one otherwise); motion only + * for people who have not asked for less of it. + */ +export function compileDecor(decor: ThemeDecor, targets: DecorTargets, ctx: Context): string[] { + const out: string[] = []; + const { colors } = ctx; + const surfaces = [colors.bg, colors.surface, colors.page]; + if (decor.dividers && targets.divider) { + const { style, color = 'border', width } = decor.dividers; + const line = style === 'none' ? '0 none' : `${style === 'hairline' ? 1 : width ?? (style === 'double' ? 3 : 1)}px ${style === 'hairline' ? 'solid' : style} ${colors[color]}`; + out.push(`:root:root :is(${targets.divider}){border-bottom:${line} !important}`); + } + if (decor.focusRing && targets.focusable) { + const { width = 2, style = 'solid', color = 'accent', offset = 2 } = decor.focusRing; + out.push(`:root:root :is(${targets.focusable}):focus-visible{outline:${Math.max(2, width)}px ${style} ${visibleOn(colors, color, surfaces, 3)} !important;outline-offset:${offset}px !important}`); + } + if (decor.selection) { + const fill = colors[decor.selection.fill]; + const text = contrastRatio(colors[decor.selection.text], fill) >= 4.5 ? colors[decor.selection.text] : (contrastRatio('#ffffff', fill) >= contrastRatio('#000000', fill) ? '#ffffff' : '#000000'); + out.push(`:root:root ::selection{background-color:${fill} !important;color:${text} !important}`); + } + if (decor.scrollbar) { + const { width, thumb = 'border', track, style } = decor.scrollbar; + const scroller = targets.scroller ?? 'html,body'; + const thumbColor = visibleOn(colors, thumb, [track ? colors[track] : colors.page], 1.5); + out.push(`:root:root :is(${scroller}){scrollbar-color:${thumbColor} ${track ? colors[track] : 'transparent'} !important${width ? `;scrollbar-width:${width} !important` : ''}}`); + // The classic look needs the engine's own scrollbar parts; `scrollbar-color` would switch them off where both are set. + if (style === 'classic') { + const face = track ? colors[track] : colors.surface; + out.push(`@supports selector(::-webkit-scrollbar){:root:root :is(${scroller}){scrollbar-color:auto !important;scrollbar-width:auto !important}:root:root ::-webkit-scrollbar{width:16px;height:16px;background:${face}}:root:root ::-webkit-scrollbar-thumb{background:${colors.surface};box-shadow:inset -1px -1px ${colors.text},inset 1px 1px ${colors.bg},inset -2px -2px ${colors.muted},inset 2px 2px ${colors.elevated}}:root:root ::-webkit-scrollbar-corner{background:${face}}}`); + } + } + if (decor.links && targets.link) { + const { underline } = decor.links; + out.push(`:root:root :is(${targets.link}){text-decoration:${underline === 'always' ? 'underline' : 'none'} !important;text-underline-offset:2px}`); + if (underline === 'hover') out.push(`:root:root :is(${targets.link}):hover{text-decoration:underline !important}`); + } + if (decor.motion && (targets.moving || targets.pressable)) { + const { duration, curve = 'standard', press } = decor.motion; + const rules: string[] = []; + if (duration !== undefined && targets.moving) { + rules.push(`:root:root :is(${targets.moving}){transition:background-color ${duration}ms ${CURVES[curve]},color ${duration}ms ${CURVES[curve]},border-color ${duration}ms ${CURVES[curve]},box-shadow ${duration}ms ${CURVES[curve]},transform ${duration}ms ${CURVES[curve]} !important}`); + } + if (press !== undefined && press < 1 && targets.pressable) rules.push(`:root:root :is(${targets.pressable}):active{transform:scale(${press}) !important}`); + if (rules.length) out.push(`@media (prefers-reduced-motion:no-preference){${rules.join('')}}`); + } + if (decor.chrome) { + const css = targets.chrome?.[decor.chrome.kind as Exclude]?.(decor.chrome.title ?? '', ctx); + if (css) out.push(css); + } + return out; +} + +/** A theme's text as a CSS string literal (for `content`): the allow-list of `chromeTitle` plus escaping of what could end the string. */ +export const cssString = (value: string) => `"${value.replace(/[\\"\n\r\f]/g, match => `\\${match.charCodeAt(0).toString(16)} `)}"`; diff --git a/packages/runtime/src/themeIcons.ts b/packages/runtime/src/themeIcons.ts new file mode 100644 index 0000000..d38dd4e --- /dev/null +++ b/packages/runtime/src/themeIcons.ts @@ -0,0 +1,296 @@ +// Icon packs: a standalone document (`*.icons.json`) of glyphs by semantic name (`home`, `like`, +// `reply`), drawn over a site's own icons. A theme only names a pack (a suggestion); the owner's icon +// choice is separate ("Follow the theme", a pack, or the site's own icons). Pure. +// +// A pack is data, never an SVG document: a glyph is path data (checked against a path grammar), a few +// colored layers of path data, or a small PNG. The engine builds the SVG itself, so no element, +// attribute, script or reference can arrive with a pack. +// +// Drawing: nothing in the site's DOM is rewritten. The site's own `` box gets the glyph as a CSS +// mask filled with `currentColor` (so the site's color states keep working: a liked heart stays the +// like color) and its own paths are made transparent. Colored glyphs (layers, PNG) are a background +// image instead. Which `` is which icon is the site's table (container first, path signature +// second). No glyph, no match or no pack: no rule, the site's icon stays. + +import { COLOR_ROLES, type ColorRole, type RoleColors } from './themeComponents.ts'; + +/** Semantic names a pack may draw. `.active` is a selected navigation item, `.on` an action that is set. */ +export const ICON_NAMES = [ + 'home', 'home.active', 'explore', 'explore.active', 'notifications', 'notifications.active', 'messages', 'messages.active', + 'grok', 'bookmarks', 'bookmarks.active', 'lists', 'communities', 'premium', 'profile', 'profile.active', 'more', 'compose', + 'reply', 'repost', 'repost.on', 'like', 'like.on', 'views', 'bookmark', 'bookmark.on', 'share', + 'verified', 'logo', 'caret', 'back', 'close', 'search', 'settings', + 'media', 'gif', 'poll', 'emoji', 'schedule', 'location', 'pinned', 'repostContext', 'lock', +] as const; +export type IconName = typeof ICON_NAMES[number]; +export const ICON_GROUPS = ['nav', 'actions', 'composer', 'misc'] as const; +export type IconGroup = typeof ICON_GROUPS[number]; + +/** Limits of a pack (the JSON Schema and the Store check say the same). */ +export const ICON_LIMITS = { names: 64, pathChars: 4000, layers: 6, pngChars: 6000, packBytes: 120_000, labelChars: 12, overrides: 8 } as const; +/** Path data only: commands, numbers, separators. */ +export const PATH_GRAMMAR = /^[MmLlHhVvCcSsQqTtAaZz0-9eE\s,.+-]{1,4000}$/; +const PNG_DATA = /^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/; +const HEX = /^#[0-9a-f]{6}$/i; +/** Words a theme or pack may put next to an action: written into CSS strings. */ +const LABEL_TEXT = /^[\p{L}\p{N} [\]().:+\-_/#@*~!?]{1,12}$/u; + +export type IconFill = ColorRole | string | { from: string; to: string }; +export type IconGlyph = + | { d: string; rule?: 'evenodd'; stroke?: boolean } + | { layers: Array<{ d: string; fill: IconFill; opacity?: number; rule?: 'evenodd' }> } + | { png: string; pixel?: boolean }; +export type IconStyle = { stroke: number; cap: 'round' | 'square' | 'butt'; join: 'round' | 'miter' | 'bevel'; scale: number }; +export const BASE_ICON_STYLE: IconStyle = { stroke: 1.75, cap: 'round', join: 'round', scale: 1 }; +export const ICON_LABEL_NAMES = ['reply', 'repost', 'like', 'views', 'bookmark', 'share'] as const; +export type IconLabels = Partial>; +export type IconSymbols = { like?: 'heart' | 'star' | 'custom'; separator?: 'dot' | 'bullet' | 'slash' | 'dash' | 'pipe' | 'none' }; + +export type IconPack = { + id: string; + name: string; + description: string; + author: string; + /** SPDX id, or `own` for the author's own drawings, or a plain name for artwork under other terms. */ + license: string; + /** Where the drawings come from (a project name or URL as text) and whom to credit. */ + source: string; + credits: string; + version: 1; + style: IconStyle; + glyphs: Partial>; + symbols?: IconSymbols; + labels?: IconLabels; +}; + +/** What a theme says about icons: a pack by id, plus small adjustments. Never a whole pack. */ +export type ThemeIcons = { pack?: string; style?: Partial; overrides?: Partial>; symbols?: IconSymbols; labels?: IconLabels }; + +const obj = (value: unknown): Record => value && typeof value === 'object' && !Array.isArray(value) ? value as Record : {}; +const plain = (value: unknown, max: number) => typeof value === 'string' ? value.replace(/[\u0000-\u001f\u007f<>]/g, '').trim().slice(0, max) : ''; +const num = (value: unknown, min: number, max: number, fallback: number) => typeof value === 'number' && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback; +const path = (value: unknown): value is string => typeof value === 'string' && PATH_GRAMMAR.test(value); + +function sanitizeFill(value: unknown): IconFill | null { + if (typeof value === 'string') return (COLOR_ROLES as readonly string[]).includes(value) ? value : HEX.test(value) ? value.toLowerCase() : null; + const source = obj(value); + return typeof source.from === 'string' && typeof source.to === 'string' && HEX.test(source.from) && HEX.test(source.to) ? { from: source.from.toLowerCase(), to: source.to.toLowerCase() } : null; +} + +/** One glyph from JSON, or null when it is not valid path data, layers or a small PNG. */ +export function sanitizeGlyph(value: unknown): IconGlyph | null { + const source = obj(value); + if (path(source.d)) return { d: source.d.trim(), ...(source.rule === 'evenodd' ? { rule: 'evenodd' as const } : {}), ...(source.stroke === true ? { stroke: true } : {}) }; + if (Array.isArray(source.layers)) { + const layers = source.layers.slice(0, ICON_LIMITS.layers).flatMap(raw => { + const layer = obj(raw), fill = sanitizeFill(layer.fill); + if (!path(layer.d) || !fill) return []; + return [{ d: layer.d.trim(), fill, ...(typeof layer.opacity === 'number' ? { opacity: +num(layer.opacity, 0, 1, 1).toFixed(2) } : {}), ...(layer.rule === 'evenodd' ? { rule: 'evenodd' as const } : {}) }]; + }); + return layers.length ? { layers } : null; + } + if (typeof source.png === 'string' && source.png.length <= ICON_LIMITS.pngChars + 22 && PNG_DATA.test(source.png)) return { png: source.png, ...(source.pixel === true ? { pixel: true } : {}) }; + return null; +} + +export const sanitizeIconStyle = (value: unknown, base: IconStyle = BASE_ICON_STYLE): IconStyle => { + const source = obj(value); + const pick = (item: unknown, options: readonly T[], fallback: T) => options.includes(item as T) ? item as T : fallback; + return { + stroke: +num(source.stroke, 1, 2.5, base.stroke).toFixed(2), cap: pick(source.cap, ['round', 'square', 'butt'] as const, base.cap), + join: pick(source.join, ['round', 'miter', 'bevel'] as const, base.join), scale: +num(source.scale, 0.8, 1.25, base.scale).toFixed(2), + }; +}; + +function sanitizeGlyphs(value: unknown, max: number): Partial> { + const source = obj(value); + const out: Partial> = {}; + let count = 0; + for (const name of ICON_NAMES) { + if (count >= max || !Object.hasOwn(source, name)) continue; + const glyph = sanitizeGlyph(source[name]); + if (glyph) { out[name] = glyph; count++; } + } + return out; +} +function sanitizeSymbols(value: unknown): IconSymbols | undefined { + const source = obj(value); + const out: IconSymbols = {}; + if (source.like === 'heart' || source.like === 'star' || source.like === 'custom') out.like = source.like; + if (['dot', 'bullet', 'slash', 'dash', 'pipe', 'none'].includes(source.separator as string)) out.separator = source.separator as IconSymbols['separator']; + return Object.keys(out).length ? out : undefined; +} +function sanitizeLabels(value: unknown): IconLabels | undefined { + const source = obj(value); + const out: IconLabels = {}; + for (const name of ICON_LABEL_NAMES) if (typeof source[name] === 'string' && LABEL_TEXT.test(source[name] as string)) out[name] = (source[name] as string).trim(); + return Object.keys(out).length ? out : undefined; +} + +/** Any JSON to a valid pack, or null when it has no id, no name or no valid glyph. */ +export function sanitizeIconPack(input: unknown): IconPack | null { + const source = obj(input); + const name = plain(source.name, 60); + const id = typeof source.id === 'string' && /^[a-z0-9-]{1,40}$/.test(source.id) ? source.id : ''; + const glyphs = sanitizeGlyphs(source.glyphs, ICON_LIMITS.names); + if (!id || !name || !Object.keys(glyphs).length) return null; + const symbols = sanitizeSymbols(source.symbols), labels = sanitizeLabels(source.labels); + return { + id, name, description: plain(source.description, 200), author: plain(source.author, 60), license: plain(source.license, 60) || 'unknown', + source: plain(source.source, 200), credits: plain(source.credits, 400), version: 1, style: sanitizeIconStyle(source.style), glyphs, + ...(symbols ? { symbols } : {}), ...(labels ? { labels } : {}), + }; +} + +/** Parses an imported `*.icons.json`; errors are human-readable. */ +export function parseIconPackJson(json: string): { pack: IconPack; warnings: string[] } | { error: string } { + if (json.length > ICON_LIMITS.packBytes) return { error: 'This icon pack is larger than 120 KB.' }; + let raw: unknown; + try { raw = JSON.parse(json); } catch { return { error: 'This file is not valid JSON.' }; } + const pack = sanitizeIconPack(raw); + if (!pack) return { error: 'An icon pack needs an "id", a "name" and at least one valid glyph.' }; + const dropped = Object.keys(obj(obj(raw).glyphs)).length - Object.keys(pack.glyphs).length; + const warnings: string[] = []; + if (dropped > 0) warnings.push(`${dropped} glyph(s) were ignored: unknown names, or drawings that are not plain path data.`); + if (pack.license === 'unknown') warnings.push('This pack does not say under which license its drawings are.'); + return { pack, warnings }; +} + +/** The `icons` group of a theme from JSON. Null when it says nothing valid. */ +export function sanitizeThemeIcons(value: unknown): ThemeIcons | null { + const source = obj(value); + const out: ThemeIcons = {}; + if (typeof source.pack === 'string' && /^[a-z0-9-]{1,40}$/.test(source.pack)) out.pack = source.pack; + if (Object.keys(obj(source.style)).length) { + const style = obj(source.style), full = sanitizeIconStyle(style); + out.style = Object.fromEntries((['stroke', 'cap', 'join', 'scale'] as const).filter(key => key in style).map(key => [key, full[key]])) as Partial; + } + const overrides = sanitizeGlyphs(source.overrides, ICON_LIMITS.overrides); + if (Object.keys(overrides).length) out.overrides = overrides; + const symbols = sanitizeSymbols(source.symbols); if (symbols) out.symbols = symbols; + const labels = sanitizeLabels(source.labels); if (labels) out.labels = labels; + return Object.keys(out).length ? out : null; +} + +// --------------------------------------------------------------------------------------------- +// The owner's choice and the catalog + +/** `theme`: follow the theme's suggestion; `site`: the site's own icons; otherwise a pack id. */ +export type IconChoice = 'theme' | 'site' | string; +export const normalizeIconChoice = (value: unknown): IconChoice => typeof value === 'string' && /^[a-z0-9-]{1,40}$/.test(value) ? value : 'theme'; + +export type IconCatalog = { + packs: readonly IconPack[]; + get(id: string | undefined): IconPack | null; + /** The pack that is drawn: the owner's pick, else the theme's suggestion; null for the site's own icons or an unknown pack. */ + resolve(choice: IconChoice, theme: ThemeIcons | null | undefined): IconPack | null; +}; +export function createIconCatalog(builtins: readonly IconPack[], installed: readonly IconPack[] = []): IconCatalog { + const packs = [...builtins, ...installed.filter(pack => !builtins.some(item => item.id === pack.id))]; + const get = (id: string | undefined) => packs.find(pack => pack.id === id) ?? null; + return { packs, get, resolve: (choice, theme) => choice === 'site' ? null : choice === 'theme' ? get(theme?.pack) : get(choice) }; +} + +// --------------------------------------------------------------------------------------------- +// Drawing + +const esc = (value: string) => value.replace(/[<>&"']/g, ''); +const paint = (fill: IconFill, colors: RoleColors | null, id: string): { attr: string; def: string } => { + if (typeof fill === 'string') return { attr: HEX.test(fill) ? fill : colors?.[fill as ColorRole] ?? '#000000', def: '' }; + return { attr: `url(#${id})`, def: `` }; +}; + +/** The SVG document of a glyph, built from validated data. `colors` resolves role fills of layers; a single path is black (it is used as a mask). */ +export function glyphSvg(glyph: IconGlyph, style: IconStyle, colors: RoleColors | null = null): string | null { + const open = ''; + if ('d' in glyph) { + const attrs = glyph.stroke + ? `fill="none" stroke="#000" stroke-width="${style.stroke}" stroke-linecap="${style.cap}" stroke-linejoin="${style.join}"` + : `fill="#000"${glyph.rule ? ' fill-rule="evenodd"' : ''}`; + return `${open}`; + } + if ('layers' in glyph) { + const defs: string[] = []; + const paths = glyph.layers.map((layer, index) => { + const { attr, def } = paint(layer.fill, colors, `g${index}`); + if (def) defs.push(def); + return ``; + }); + return `${open}${defs.length ? `${defs.join('')}` : ''}${paths.join('')}`; + } + return null; +} +const svgUrl = (svg: string) => `url("data:image/svg+xml,${encodeURIComponent(svg).replace(/'/g, '%27').replace(/"/g, '%22')}")`; +/** True for glyphs that carry their own colors (drawn as an image, not as a mask of the current color). */ +export const isColored = (glyph: IconGlyph) => !('d' in glyph); + +/** How a site finds one of its icons: the container that holds it (stable hooks), else the start of its path data. */ +export type IconMatcher = { + /** Selector of the icon's `` by its container (`[data-testid="like"] svg`). */ + ctx?: string; + /** Prefixes of the site's own path data for this icon, for icons without a container hook. */ + sig?: readonly string[]; + group: IconGroup; + /** Needed for its group to be drawn at all (a rail never shows half ours, half the site's). */ + core?: boolean; +}; +export type IconTable = Partial>; + +/** Selectors of the `` boxes of one icon. */ +export function iconSelectors(matcher: IconMatcher): string[] { + const out: string[] = []; + if (matcher.ctx) out.push(...matcher.ctx.split(/,(?![^(]*\))/).map(one => one.trim())); + for (const prefix of matcher.sig ?? []) if (PATH_GRAMMAR.test(prefix)) out.push(`svg:has(> g > path[d^="${prefix}"])`); + return out; +} + +export type IconContext = { + colors: RoleColors | null; + /** Attribute on `` that lists the groups that are on (`data-wb-icons="nav actions"`); absent: every group draws. */ + gate?: string; + /** The owner lets themes and packs change icons (default: yes). */ + allowed?: boolean; +}; + +/** + * CSS that draws `pack` over a site's icons. One rule per glyph the pack has and the site's table + * knows, inside guards: forced colors remove backgrounds (a masked icon would vanish) and an engine + * without masks would paint solid squares. + */ +export function compileIcons(pack: IconPack | null, theme: ThemeIcons | null | undefined, table: IconTable, ctx: IconContext): string { + if (ctx.allowed === false) return ''; + const glyphs: Partial> = { ...pack?.glyphs, ...theme?.overrides }; + const style = { ...(pack?.style ?? BASE_ICON_STYLE), ...theme?.style }; + const masked: string[] = [], colored: string[] = [], hidden: string[] = []; + for (const name of ICON_NAMES) { + const glyph = glyphs[name], matcher = table[name]; + if (!glyph || !matcher) continue; + const gate = ctx.gate ? `html[${ctx.gate}~="${matcher.group}"] ` : ''; + const selectors = iconSelectors(matcher).map(one => `${gate}${one}`); + if (!selectors.length) continue; + const size = `${Math.round(style.scale * 100)}%`; + if ('png' in glyph) { + colored.push(`${selectors.join(',')}{background:url("${glyph.png}") center / ${size} no-repeat !important;${glyph.pixel ? 'image-rendering:pixelated;' : ''}}`); + } else { + const svg = glyphSvg(glyph, style, ctx.colors); + if (!svg) continue; + if (isColored(glyph)) colored.push(`${selectors.join(',')}{background:${svgUrl(svg)} center / ${size} no-repeat !important}`); + else masked.push(`${selectors.join(',')}{background-color:currentColor !important;-webkit-mask:${svgUrl(svg)} center / ${size} no-repeat;mask:${svgUrl(svg)} center / ${size} no-repeat}`); + } + hidden.push(...selectors.map(one => `${one} > *`)); + } + if (!hidden.length) return ''; + const hide = `${hidden.join(',')}{opacity:0 !important}`; + const images = colored.length ? `${colored.join('\n')}\n` : ''; + // Colored glyphs need no mask support; masked ones are dropped together with their hiding rule where masks are missing. + if (!masked.length) return `@media (forced-colors:none){\n${images}${hide}\n}`; + return `@media (forced-colors:none){@supports ((mask-image:url("")) or (-webkit-mask-image:url(""))){\n${images}${masked.join('\n')}\n${hide}\n}}`; +} + +/** The groups of `table` whose core icons are all on the page (`has(selector)` says whether one matches). Empty table entries count as present. */ +export function iconGroupsPresent(table: IconTable, has: (selector: string) => boolean): IconGroup[] { + return ICON_GROUPS.filter(group => { + const core = ICON_NAMES.map(name => table[name]).filter((matcher): matcher is IconMatcher => !!matcher && matcher.group === group && !!matcher.core); + return core.every(matcher => iconSelectors(matcher).some(selector => { try { return has(selector); } catch { return false; } })); + }); +} diff --git a/packages/runtime/src/themeSchema.ts b/packages/runtime/src/themeSchema.ts new file mode 100644 index 0000000..c51949d --- /dev/null +++ b/packages/runtime/src/themeSchema.ts @@ -0,0 +1,154 @@ +// The JSON Schema of a theme's structure groups and of an icon pack, generated from the same tables +// the sanitizers use (themeComponents.ts, themeVariants.ts, themeDecor.ts, themeIcons.ts), so a range +// or a word exists in one place. `theme.schema.json` and `icons.schema.json` in the `waybetter` +// package are written from here (`scripts/theme-schema.mjs`); a test fails when they are stale. Pure. + +import { + ACTION_NAMES, AVATAR_SHAPES, BORDER_STYLES, CASES, COLOR_ROLES, COMPONENTS, COMPONENT_IDS, CORNERS, PRESETS, SHADOWS, TOKEN_LIMITS, +} from './themeComponents.ts'; +import { CHROME_KINDS, DIVIDER_STYLES, LINK_UNDERLINES, MOTION_CURVES, RING_STYLES } from './themeDecor.ts'; +import { ICON_LABEL_NAMES, ICON_LIMITS, ICON_NAMES, PATH_GRAMMAR } from './themeIcons.ts'; +import { VARIANT_AXES, VARIANT_AXIS_NAMES } from './themeVariants.ts'; + +type Json = Record; +const range = ([minimum, maximum]: readonly [number, number], type = 'number'): Json => ({ type, minimum, maximum }); +const words = (values: readonly string[]): Json => ({ enum: [...values] }); +const closed = (properties: Json, extra: Json = {}): Json => ({ type: 'object', additionalProperties: false, properties, ...extra }); +/** Schema-side guard for words written into CSS strings (the sanitizer's allow-list is stricter: letters, digits and a little punctuation). */ +const LABEL_PATTERN = String.raw`^[^\u0000-\u001f"\\<>&{};'` + '`]+$'; +const role = { $ref: '#/$defs/role' }; +const hex = { $ref: '#/$defs/hex' }; + +type Def = { parent?: string; text?: boolean; height?: readonly [number, number]; width?: readonly [number, number]; size?: readonly [number, number]; maxHeight?: readonly [number, number]; fontSize?: readonly [number, number]; shape?: boolean; corner?: boolean; visible?: boolean; glass?: boolean; gradient?: boolean; presets?: keyof typeof PRESETS }; + +// Fills and states come in four kinds (with or without glass, with or without a gradient); each is one shared definition. +const kind = (def: Def) => `${def.glass ? 'Glass' : ''}${def.gradient ? 'Gradient' : ''}`; +function fillDef(glass: boolean, gradient: boolean): Json { + const options: Json[] = [role, { const: 'transparent' }]; + if (glass) options.push({ const: 'glass' }); + if (gradient) options.push(closed({ from: role, to: role, angle: range(TOKEN_LIMITS.angle) }, { required: ['from', 'to'] })); + return { oneOf: options }; +} +const stateDef = (name: string): Json => closed({ + fill: { $ref: `#/$defs/fill${name}` }, text: role, borderColor: role, shadow: { $ref: '#/$defs/shadow' }, lift: range(TOKEN_LIMITS.lift), scale: range(TOKEN_LIMITS.scale), underline: { type: 'boolean' }, +}); +const fill = (def: Def): Json => ({ $ref: `#/$defs/fill${kind(def)}` }); +const state = (def: Def): Json => ({ $ref: `#/$defs/state${kind(def)}` }); + +function component(def: Def, id: string): Json { + const properties: Json = { + radius: { oneOf: [range(TOKEN_LIMITS.radius), { const: 'pill' }] }, + borderWidth: range(TOKEN_LIMITS.borderWidth), borderStyle: words(BORDER_STYLES), borderColor: role, + fill: fill(def), text: role, + padX: range(TOKEN_LIMITS.padX), padY: range(TOKEN_LIMITS.padY), gap: range(TOKEN_LIMITS.gap), + shadow: { $ref: '#/$defs/shadow' }, hover: state(def), active: state(def), focus: state(def), + }; + if (def.presets) properties.preset = words(Object.keys(PRESETS[def.presets])); + for (const key of ['height', 'width', 'size', 'maxHeight', 'fontSize'] as const) if (def[key]) properties[key] = range(def[key]!); + if (def.text || def.fontSize) { + properties.font = { $ref: '#/$defs/fontRoleName' }; + properties.weight = range(TOKEN_LIMITS.weight); + if (id !== 'postText') properties.case = words(CASES); + properties.tracking = range(TOKEN_LIMITS.tracking); + properties.leading = range(TOKEN_LIMITS.leading); + } + if (def.shape) properties.shape = words(AVATAR_SHAPES); + if (def.corner) properties.corner = words(CORNERS); + if (def.visible) properties.visible = { type: 'boolean' }; + return closed(properties); +} + +const glyph: Json = { + oneOf: [ + closed({ d: { $ref: '#/$defs/pathData' }, rule: { const: 'evenodd' }, stroke: { type: 'boolean' } }, { required: ['d'] }), + closed({ + layers: { + type: 'array', minItems: 1, maxItems: ICON_LIMITS.layers, + items: closed({ d: { $ref: '#/$defs/pathData' }, fill: { oneOf: [role, hex, closed({ from: hex, to: hex }, { required: ['from', 'to'] })] }, opacity: range([0, 1]), rule: { const: 'evenodd' } }, { required: ['d', 'fill'] }), + }, + }, { required: ['layers'] }), + closed({ png: { type: 'string', maxLength: ICON_LIMITS.pngChars + 22, pattern: '^data:image/png;base64,[A-Za-z0-9+/]+={0,2}$' }, pixel: { type: 'boolean' } }, { required: ['png'] }), + ], +}; +const iconStyle = closed({ stroke: range([1, 2.5]), cap: words(['round', 'square', 'butt']), join: words(['round', 'miter', 'bevel']), scale: range([0.8, 1.25]) }); +const symbols = closed({ like: words(['heart', 'star', 'custom']), separator: words(['dot', 'bullet', 'slash', 'dash', 'pipe', 'none']) }); +const labels = closed(Object.fromEntries(ICON_LABEL_NAMES.map(name => [name, { type: 'string', minLength: 1, maxLength: ICON_LIMITS.labelChars, pattern: LABEL_PATTERN }]))); +const glyphs = (maxProperties: number): Json => closed(Object.fromEntries(ICON_NAMES.map(name => [name, { $ref: '#/$defs/glyph' }])), { maxProperties }); + +/** `$defs` shared by the structure groups and the pack schema. */ +export const structureDefs = (): Json => ({ + role: { description: 'A color role of the theme. Components never carry a color literal.', ...words(COLOR_ROLES) }, + fontRoleName: words(['interface', 'post', 'heading', 'numbers', 'mono', 'chrome', 'dialog']), + shadow: words(SHADOWS), + ...Object.fromEntries([[false, false], [true, false], [false, true], [true, true]].flatMap(([glass, gradient]) => { + const name = `${glass ? 'Glass' : ''}${gradient ? 'Gradient' : ''}`; + return [[`fill${name}`, fillDef(glass!, gradient!)], [`state${name}`, stateDef(name)]]; + })), + pathData: { type: 'string', minLength: 1, maxLength: ICON_LIMITS.pathChars, pattern: PATH_GRAMMAR.source.replace(/\{1,4000\}\$$/, '+$') }, + glyph, +}); + +/** The properties a theme document gains: `components`, `variants`, `decor`, `icons`. */ +export function structureProperties(): Json { + return { + components: { + description: 'How each piece of the site is built. Every token is optional; a missing token changes nothing.', + ...closed(Object.fromEntries(COMPONENT_IDS.map(id => [id, component(COMPONENTS[id] as Def, id)]))), + }, + variants: { + description: 'Structural choices. The first option of each axis is the site\'s own layout.', + ...closed(Object.fromEntries(VARIANT_AXIS_NAMES.map(axis => [axis, words(VARIANT_AXES[axis])]))), + }, + decor: { + description: 'Lines, bars, focus ring, selection, scrollbars, link underlines, motion.', + ...closed({ + dividers: closed({ style: words(DIVIDER_STYLES), color: role, width: range([0, 3]) }, { required: ['style'] }), + chrome: closed({ kind: words(CHROME_KINDS), title: { type: 'string', maxLength: 24 } }, { required: ['kind'] }), + focusRing: closed({ width: range([2, 4]), style: words(RING_STYLES), color: role, offset: range([0, 4]) }), + selection: closed({ fill: role, text: role }, { required: ['fill', 'text'] }), + scrollbar: closed({ width: words(['auto', 'thin']), thumb: role, track: role, style: words(['flat', 'classic']) }), + links: closed({ underline: words(LINK_UNDERLINES) }, { required: ['underline'] }), + motion: closed({ duration: range([0, 400]), curve: words(MOTION_CURVES), press: range([0.96, 1]) }), + }), + }, + icons: { + description: 'The icon pack this theme suggests (by id), with small adjustments. A whole pack is its own document (icons.schema.json).', + ...closed({ pack: { type: 'string', pattern: '^[a-z0-9-]{1,40}$' }, style: iconStyle, overrides: glyphs(ICON_LIMITS.overrides), symbols, labels }), + }, + }; +} + +/** `colors.actions`. */ +export const actionColorsSchema = (): Json => ({ + description: 'Colors of a set action (liked, reposted, bookmarked) and of the reply hover. Absent: the site\'s own.', + ...closed(Object.fromEntries(ACTION_NAMES.map(name => [name, hex]))), +}); + +/** The JSON Schema of an icon pack document (`*.icons.json`). */ +export function iconPackSchema(id: string): Json { + return { + $schema: 'https://json-schema.org/draft/2020-12/schema', + $id: id, + title: 'wayBetter icon pack', + description: 'Glyphs by semantic name, drawn over a site\'s own icons. Path data, colored layers of path data, or small PNGs: never an SVG document.', + type: 'object', + required: ['id', 'name', 'license', 'glyphs'], + additionalProperties: false, + properties: { + $schema: { type: 'string' }, + id: { type: 'string', pattern: '^[a-z0-9-]{1,40}$' }, + name: { type: 'string', minLength: 1, maxLength: 60 }, + description: { type: 'string', maxLength: 200 }, + author: { type: 'string', maxLength: 60 }, + license: { type: 'string', minLength: 1, maxLength: 60, description: 'SPDX id, "own" for the author\'s own drawings, or a plain name for artwork under other terms.' }, + source: { type: 'string', maxLength: 200 }, + credits: { type: 'string', maxLength: 400 }, + version: { const: 1 }, + style: iconStyle, + glyphs: { ...glyphs(ICON_LIMITS.names), minProperties: 1 }, + symbols, + labels, + }, + $defs: { hex: { type: 'string', pattern: '^#[0-9a-fA-F]{6}$' }, ...structureDefs() }, + }; +} diff --git a/packages/runtime/src/themeSpec.ts b/packages/runtime/src/themeSpec.ts index b17c400..5e251f7 100644 --- a/packages/runtime/src/themeSpec.ts +++ b/packages/runtime/src/themeSpec.ts @@ -18,6 +18,10 @@ import { FONT_ROLE_NAMES, MONO_FAMILIES, contrastRatio, hexToRgb, mix, relativeLuminance, type FontRoleName } from './themeApi.ts'; import { deriveColors } from './themeTokens.ts'; +import { ACTION_NAMES, sanitizeComponents, type ActionColors, type ThemeComponents } from './themeComponents.ts'; +import { sanitizeDecor, type ThemeDecor } from './themeDecor.ts'; +import { sanitizeThemeIcons, type ThemeIcons } from './themeIcons.ts'; +import { sanitizeVariants, type ThemeVariants } from './themeVariants.ts'; export { FONT_ROLE_NAMES } from './themeApi.ts'; export type { FontRoleName } from './themeApi.ts'; @@ -26,8 +30,12 @@ export type Role = 'bg' | 'surface' | 'elevated' | 'border' | 'text' | 'muted' | /** The site's filled primary button (X: "Post"/"Follow"): an `inverse` background with an `onInverse` label. */ export type ButtonRole = 'inverse' | 'onInverse'; export type Palette = Record & Partial>; -/** `page` is the canvas behind the site's columns (defaults to `bg`); the columns stay on `bg`. */ -export type ThemeColors = Palette & { page?: string }; +/** + * `page` is the canvas behind the site's columns (defaults to `bg`); the columns stay on `bg`. + * `actions` are the colors of a set action (liked, reposted, bookmarked) and of the reply hover; + * absent, the site's own action colors stay. + */ +export type ThemeColors = Palette & { page?: string; actions?: ActionColors }; export type Density = 'compact' | 'default' | 'comfortable'; export type AvatarShape = 'circle' | 'rounded' | 'square'; @@ -91,6 +99,16 @@ export type ThemeSpec = { effects: EffectsSpec; /** Free-form CSS appended last (owner-trusted, like Custom CSS). */ css: string; + // The groups below are optional and additive: a theme without them is drawn exactly as before, + // and an app that does not know them drops them and draws the rest. + /** How each piece of the site is built (themeComponents.ts). */ + components?: ThemeComponents; + /** Structural choices: where the navigation sits, how a post is laid out (themeVariants.ts). */ + variants?: ThemeVariants; + /** Lines, bars, focus ring, selection, scrollbars, motion (themeDecor.ts). */ + decor?: ThemeDecor; + /** Which icon pack the theme suggests, with small adjustments (themeIcons.ts). */ + icons?: ThemeIcons; }; /** Panel overrides: any group may be partially overridden on top of the selected theme. */ @@ -104,6 +122,8 @@ export type ThemeOverrides = { effects?: Partial; /** The theme's own CSS as edited in the panel (replaces the theme document's `css`). */ css?: { text: string }; + /** The owner's say on a theme's layout suggestions, axis by axis (an axis set to the site's own option switches it off). */ + variants?: Record; }; // --------------------------------------------------------------------------------------------- @@ -149,7 +169,7 @@ export function reach(color: string, surfaces: string[], ratio: number): string * and links reach WCAG AA (4.5:1) on every surface, including the page canvas, and the site's filled * button keeps a readable label and stands out from the page (3:1). */ -export function ensureContrast(colors: T): T { +export function ensureContrast(colors: T): T { const surfaces = [colors.bg, colors.surface, colors.elevated, ...(colors.page ? [colors.page] : [])]; const out = { ...colors }; out.text = reach(colors.text, surfaces, 7); @@ -160,6 +180,8 @@ export function ensureContrast(colors: T) const onInverse = colors.onInverse ?? colors.bg; out.inverse = reach(inverse, [colors.bg], 3); out.onInverse = reach(onInverse, [out.inverse], 4.5); + // Action colors are icons and counts: non-text contrast on the column and on a raised row. + if (colors.actions) out.actions = Object.fromEntries(Object.entries(colors.actions).map(([name, color]) => [name, reach(color as string, [colors.bg, colors.surface], 3)])); return out; } @@ -192,6 +214,9 @@ function sanitizeColors(value: unknown): ThemeColors | null { .filter(role => isHex(source[role])).map(role => [role, (source[role] as string).toLowerCase()])); const colors = deriveColors(named as { bg: string; text: string; accent: string }) as ThemeColors; for (const role of ['inverse', 'onInverse', 'page'] as const) if (isHex(source[role])) colors[role] = (source[role] as string).toLowerCase(); + const actions = obj(source.actions); + const named_actions = Object.fromEntries(ACTION_NAMES.filter(name => isHex(actions[name])).map(name => [name, (actions[name] as string).toLowerCase()])); + if (Object.keys(named_actions).length) colors.actions = named_actions; return colors; } @@ -309,9 +334,20 @@ export function sanitizeSpec(input: unknown): ThemeSpec { background: sanitizeBackground(source.background), effects: sanitizeEffects(source.effects, BASE_EFFECTS), css: typeof source.css === 'string' ? source.css.slice(0, MAX_CSS_CHARS) : '', + ...structureGroups(source), }; } +/** The optional structure groups of a theme, each present only when it says something valid. */ +function structureGroups(source: Record): Pick { + const components = sanitizeComponents(source.components), variants = sanitizeVariants(source.variants); + const decor = sanitizeDecor(source.decor), icons = sanitizeThemeIcons(source.icons); + return { ...(components ? { components } : {}), ...(variants ? { variants } : {}), ...(decor ? { decor } : {}), ...(icons ? { icons } : {}) }; +} + +/** True when a theme carries any of the structure groups (components, variants, decoration, icons). */ +export const hasStructure = (theme: ThemeSpec) => !!(theme.components || theme.variants || theme.decor || theme.icons); + /** Parses an imported file; errors are human-readable. */ export function parseThemeJson(json: string): { theme: ThemeSpec; warnings: string[] } | { error: string } { let raw: unknown; @@ -345,13 +381,21 @@ export function applyOverrides(theme: ThemeSpec, overrides: ThemeOverrides = {}, background: o.background ? sanitizeBackground(o.background) : theme.background, effects: o.effects ? sanitizeEffects({ ...theme.effects, ...o.effects }, theme.effects) : theme.effects, css: o.css && typeof o.css.text === 'string' ? o.css.text.slice(0, MAX_CSS_CHARS) : theme.css, + ...variantOverrides(theme, o.variants), }; } +/** A theme's variants with the owner's per-axis say on top (the raw merge goes through the sanitizer, so the site's own option removes the axis). */ +function variantOverrides(theme: ThemeSpec, overrides: unknown): Pick { + if (!overrides || typeof overrides !== 'object') return {}; + const variants = sanitizeVariants({ ...theme.variants, ...(overrides as Record) }); + return { variants: variants ?? undefined }; +} + /** True when a theme changes nothing about the site (the site's own look without overrides). */ export function isNeutral(theme: ThemeSpec): boolean { return !theme.colors && JSON.stringify([theme.font, theme.shape, theme.layout, theme.effects]) === JSON.stringify([BASE_FONT, BASE_SHAPE, BASE_LAYOUT, BASE_EFFECTS]) - && theme.background.kind === 'none' && !theme.css; + && theme.background.kind === 'none' && !theme.css && !hasStructure(theme); } // --------------------------------------------------------------------------------------------- diff --git a/packages/runtime/src/themeVariants.ts b/packages/runtime/src/themeVariants.ts new file mode 100644 index 0000000..02be505 --- /dev/null +++ b/packages/runtime/src/themeVariants.ts @@ -0,0 +1,64 @@ +// Layout variants: the structural choices a theme may suggest (navigation on top, compact posts, +// worded actions), as fixed words on a few axes. The vocabulary and the precedence are here; what a +// variant looks like on a site is that site's CSS (its skins). Pure. +// +// A theme suggests, the owner decides: an axis an owner's own switch already controls is left to that +// switch, and the owner can turn layout changes by themes off altogether. + +/** The axes and their options. The first option of each axis is the site's own layout (no rule). */ +export const VARIANT_AXES = { + nav: ['labels', 'icons', 'top', 'bottom'], + post: ['default', 'cards', 'bubbles', 'compact', 'broadsheet'], + actions: ['icons', 'labels', 'quiet'], + header: ['default', 'solid', 'bar'], + sidebar: ['default', 'narrow', 'hidden'], + width: ['default', 'full'], +} as const; +export type VariantAxis = keyof typeof VARIANT_AXES; +export const VARIANT_AXIS_NAMES = Object.keys(VARIANT_AXES) as VariantAxis[]; +export type ThemeVariants = { [A in VariantAxis]?: typeof VARIANT_AXES[A][number] }; + +/** The `variants` group from JSON: known axes and options only; an axis left at the site's own layout is dropped. */ +export function sanitizeVariants(value: unknown): ThemeVariants | null { + const source = value && typeof value === 'object' && !Array.isArray(value) ? value as Record : {}; + const out: Record = {}; + for (const axis of VARIANT_AXIS_NAMES) { + const options: readonly string[] = VARIANT_AXES[axis]; + const option = source[axis]; + if (typeof option === 'string' && options.includes(option) && option !== options[0]) out[axis] = option; + } + return Object.keys(out).length ? out as ThemeVariants : null; +} + +export type VariantGate = { + /** The owner lets themes change the layout (default: yes). */ + allowed?: boolean; + /** Axes an owner's own switch controls right now: the theme's suggestion is not drawn for them. */ + owned?: readonly VariantAxis[]; +}; + +/** The variants that are drawn: the theme's (with the owner's customization already merged in), minus what the owner holds. */ +export function resolveVariants(variants: ThemeVariants | null | undefined, gate: VariantGate = {}): ThemeVariants { + if (!variants || gate.allowed === false) return {}; + const out: Record = {}; + for (const axis of VARIANT_AXIS_NAMES) { + const option = variants[axis]; + if (option && !gate.owned?.includes(axis)) out[axis] = option; + } + return out as ThemeVariants; +} + +/** A site's CSS for each variant it can draw: `skins.nav.top(ctx)` returns the rules. */ +export type VariantSkins = { [A in VariantAxis]?: Partial string>> }; + +/** The CSS of the resolved variants, in axis order. A variant the site has no skin for draws nothing. */ +export function compileVariants(variants: ThemeVariants, skins: VariantSkins, ctx: Context): string[] { + const out: string[] = []; + for (const axis of VARIANT_AXIS_NAMES) { + const option = variants[axis]; + const build = option ? (skins[axis] as Record string) | undefined> | undefined)?.[option] : undefined; + const css = build?.(ctx); + if (css) out.push(css); + } + return out; +} diff --git a/packages/runtime/tests/themeStructure.test.ts b/packages/runtime/tests/themeStructure.test.ts new file mode 100644 index 0000000..8f59c10 --- /dev/null +++ b/packages/runtime/tests/themeStructure.test.ts @@ -0,0 +1,278 @@ +// A theme's structure groups (components, variants, decoration, icons) and icon packs: what the +// sanitizers accept, what the compilers emit, and that the published schemas are generated from the +// same tables. Site selectors here are made up; a site's own part map is tested in that site's app. +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { contrastRatio } from '../src/themeApi.ts'; +import { + COMPONENTS, COMPONENT_IDS, PRESETS, TOKEN_LIMITS, compileComponents, partRule, readableRole, resolveComponents, sanitizeComponents, + type ComponentContext, type PartMap, type RoleColors, +} from '../src/themeComponents.ts'; +import { chromeTitle, compileDecor, cssString, sanitizeDecor } from '../src/themeDecor.ts'; +import { + BASE_ICON_STYLE, ICON_LIMITS, ICON_NAMES, PATH_GRAMMAR, compileIcons, createIconCatalog, glyphSvg, iconGroupsPresent, normalizeIconChoice, parseIconPackJson, sanitizeGlyph, + sanitizeIconPack, sanitizeThemeIcons, type IconPack, type IconTable, +} from '../src/themeIcons.ts'; +import { applyOverrides, hasStructure, isNeutral, sanitizeSpec } from '../src/themeSpec.ts'; +import { VARIANT_AXES, compileVariants, resolveVariants, sanitizeVariants } from '../src/themeVariants.ts'; + +const COLORS: RoleColors = { + bg: '#ffffff', surface: '#f5f8fa', elevated: '#e8f1f7', page: '#c0deed', border: '#e1e8ed', text: '#292f33', muted: '#5b6b78', + accent: '#0077b0', onAccent: '#ffffff', inverse: '#0077b0', onInverse: '#ffffff', +}; +const CTX: ComponentContext = { + colors: COLORS, + fonts: { interface: 'Helvetica, sans-serif', post: 'Georgia, serif', heading: 'Helvetica, sans-serif', numbers: 'Helvetica, sans-serif', mono: 'monospace', chrome: 'system-ui', dialog: 'system-ui' }, +}; +const PARTS: PartMap = { + post: { sel: '[data-part="post"]' }, + postText: { sel: '[data-part="text"]', text: '[data-part="text"],[data-part="text"] :is(span,a)' }, + buttonPrimary: { sel: '[data-part="primary"]', text: '[data-part="primary"] span' }, + buttonSecondary: { sel: '[data-part="secondary"]' }, + avatar: { sel: '[data-part="avatar"]', skip: ['size'] }, + handle: { sel: '[data-part="handle"]' }, + search: { sel: '[data-part="search"]' }, +}; +const css = (components: unknown) => { const out = compileComponents(sanitizeComponents(components) ?? {}, PARTS, CTX); return { ...out, text: [...out.values, ...out.rules].join('\n') }; }; + +test('component tokens are clamped, unknown names and tokens a component does not take are dropped', () => { + const clean = sanitizeComponents({ + post: { radius: 999, borderWidth: -3, borderStyle: 'groove', fill: '#ff0000', padX: 12.6, shadow: 'soft', visible: false, fontSize: 40, corner: 'cut', nonsense: 1 }, + avatar: { shape: 'hexagon', size: 3, visible: false, corner: 'cut' }, + postText: { fontSize: 99, case: 'upper', weight: 433, tracking: 9, leading: 0.2, font: 'post' }, + buttonPrimary: { preset: 'bevel', radius: 'pill', fill: { from: 'accent', to: 'surface', angle: 720 }, hover: { lift: 40, scale: 2, underline: true, fill: 'url(x)' } }, + topBar: { fill: 'glass', height: 1 }, + handle: { fill: 'glass', preset: 'bevel' }, + rocket: { radius: 4 }, + nav: 'javascript:alert(1)', + })!; + assert.deepEqual(clean.post, { radius: TOKEN_LIMITS.radius[1], borderWidth: 0, padX: 13, shadow: 'soft', corner: 'cut' }, 'no literal color, no unknown style, no font size or visibility on a post'); + assert.deepEqual(clean.avatar, { size: 20, shape: 'hexagon', visible: false }); + assert.deepEqual(clean.postText, { fontSize: 24, font: 'post', weight: 450, tracking: 0.2, leading: 1.1 }, 'post text never changes case'); + assert.deepEqual(clean.buttonPrimary, { preset: 'bevel', radius: 'pill', fill: { from: 'accent', to: 'surface', angle: 360 }, hover: { lift: 4, scale: 1.04, underline: true } }); + assert.deepEqual(clean.topBar, { fill: 'glass', height: 40 }); + assert.equal(clean.handle, undefined, 'glass is for bars and panels; a handle has no presets'); + assert.ok(!('rocket' in clean) && !('nav' in clean)); + assert.equal(sanitizeComponents({ post: {} }), null); + assert.equal(sanitizeComponents('nope'), null); +}); + +test('presets and parents: own tokens win over the preset, the preset over the parent', () => { + const resolved = resolveComponents(sanitizeComponents({ button: { radius: 4, weight: 700 }, buttonPrimary: { preset: 'pill', borderWidth: 2 }, panel: { preset: 'window' }, menu: { radius: 8 } })!); + assert.deepEqual(resolved.buttonPrimary, { radius: 'pill', weight: 700, borderWidth: 2 }); + assert.deepEqual(resolved.buttonSecondary, { radius: 4, weight: 700 }); + assert.equal(resolved.menu!.radius, 8); + assert.equal(resolved.menu!.borderStyle, 'bevel-out'); + assert.equal(resolved.dialog!.radius, 0); + // Every preset is itself valid vocabulary for a component of its family. + for (const [family, presets] of Object.entries(PRESETS)) { + const id = COMPONENT_IDS.find(item => (COMPONENTS[item] as { presets?: string }).presets === family)!; + for (const [name, tokens] of Object.entries(presets)) assert.deepEqual(sanitizeComponents({ [id]: tokens })![id], tokens, `${family}.${name}`); + } +}); + +test('compiled components: soft values, rigid rules, nothing for a part the site does not have', () => { + const out = css({ post: { radius: 0, borderWidth: 1, borderColor: 'border', padX: 16, fill: 'surface' }, postText: { fontSize: 17, font: 'post', leading: 1.5 }, nav: { width: 200 }, avatar: { size: 32, shape: 'square' } }); + assert.ok(out.values.includes('--wb-part-post-radius:0px') && out.values.includes('--wb-part-postText-font-size:17px') && out.values.includes('--wb-part-postText-line-height:1.5')); + assert.ok(out.rules.includes(':root:root [data-part="post"]{background-color:var(--wb-part-post-fill) !important;background-image:var(--wb-part-post-fill-1) !important;border-radius:var(--wb-part-post-radius) !important;border-width:var(--wb-part-post-border-width) !important;border-style:var(--wb-part-post-border-style) !important;border-color:var(--wb-part-post-border-color) !important;padding-inline:var(--wb-part-post-pad-x) !important}'), out.rules[0]); + assert.ok(out.rules.some(rule => rule.startsWith(':root:root [data-part="text"],:root:root [data-part="text"] :is(span,a){') && rule.includes('font-family:var(--wb-part-postText-font)')), 'type lands on the text leaves'); + assert.ok(!out.text.includes('nav') && !out.text.includes('--wb-part-avatar-size'), 'no part, or a skipped token: no rule'); + assert.ok(out.text.includes('--wb-part-avatar-shape:2px')); + // Every rule is important and every value it reads was emitted with it. + for (const rule of out.rules) for (const name of rule.match(/var\((--[\w-]+)\)/g) ?? []) assert.ok(out.values.some(value => value.startsWith(`${name.slice(4, -1)}:`)), name); + assert.equal(partRule('a, b:is(c,d)'), ':root:root a,:root:root b:is(c,d)'); + assert.equal(compileComponents({}, PARTS, CTX).rules.length, 0); +}); + +test('text on a fill the theme chose keeps its contrast: the role is swapped for a readable one', () => { + // Accent text on an accent button (1:1), and a post filled with the theme's text color. + const out = css({ buttonPrimary: { fill: 'accent', text: 'accent' }, post: { fill: 'text' }, postText: { text: 'muted' }, avatar: { fill: 'surface' } }); + assert.ok(out.values.includes(`--wb-part-buttonPrimary-text:${COLORS.onAccent}`)); + assert.ok(out.notes.some(note => note.startsWith('buttonPrimary:'))); + assert.ok(out.values.includes(`--wb-part-postText-text:${COLORS.muted}`), 'no fill of its own: the theme\'s role stands (the palette guarantees it on the theme\'s surfaces)'); + assert.ok(!out.text.includes('--wb-part-avatar-text'), 'a fill alone colors no text on a part that is not a text part'); + assert.equal(readableRole('#000000', COLORS), 'onAccent'); + for (const role of ['accent', 'text', 'surface', 'inverse'] as const) { + const label = css({ buttonPrimary: { fill: role } }).values.find(value => value.startsWith('--wb-part-buttonPrimary-text:'))!.split(':')[1]!; + assert.ok(contrastRatio(label, COLORS[role]) >= 4.5, `${role}: ${label}`); + } +}); + +test('bevels are four inset lines from the part\'s fill; states move only without reduced motion', () => { + const out = css({ buttonPrimary: { preset: 'bevel', hover: { lift: 2, fill: 'elevated' }, active: { shadow: 'inset', scale: 0.98 }, focus: { borderColor: 'accent' } } }); + const bevel = out.values.find(value => value.startsWith('--wb-part-buttonPrimary-bevel:'))!; + assert.equal(bevel.match(/inset/g)!.length, 4); + assert.ok(out.values.includes('--wb-part-buttonPrimary-border-style:none')); + assert.ok(out.rules.some(rule => rule.startsWith(':root:root [data-part="primary"]:hover{background-color:#e8f1f7 !important'))); + assert.ok(out.rules.some(rule => rule.startsWith('@media (prefers-reduced-motion:no-preference){:root:root [data-part="primary"]:hover{transform:translateY(-2px) !important}'))); + assert.ok(out.rules.some(rule => rule.includes('[data-part="primary"]:active{box-shadow:inset') && rule.match(/inset/g)!.length === 4), 'a pressed bevel is the sunken bevel'); + assert.ok(out.rules.some(rule => rule.startsWith(':root:root [data-part="primary"]:focus-visible{border-color:#0077b0 !important}'))); + assert.ok(out.rules.filter(rule => rule.includes('transform')).every(rule => rule.startsWith('@media (prefers-reduced-motion:no-preference)'))); +}); + +test('variants: known axes and options only; the owner holds an axis or switches layout changes off', () => { + assert.deepEqual(sanitizeVariants({ nav: 'top', post: 'default', actions: 'explode', header: 'bar', zoom: 'in' }), { nav: 'top', header: 'bar' }); + assert.equal(sanitizeVariants({ nav: 'labels', post: 'default' }), null, 'the site\'s own options are not a variant'); + assert.deepEqual(resolveVariants({ nav: 'top', post: 'compact', sidebar: 'hidden' }, { owned: ['sidebar'] }), { nav: 'top', post: 'compact' }); + assert.deepEqual(resolveVariants({ nav: 'top' }, { allowed: false }), {}); + assert.deepEqual(resolveVariants(null), {}); + const skins = { nav: { top: (ctx: { bar: string }) => `nav{top:0;background:${ctx.bar}}` }, post: { compact: () => 'article{padding:4px}' } }; + assert.deepEqual(compileVariants({ post: 'compact', nav: 'top', actions: 'labels' }, skins, { bar: 'red' }), ['nav{top:0;background:red}', 'article{padding:4px}'], 'axis order; no skin, no rule'); + for (const options of Object.values(VARIANT_AXES)) assert.ok(options.length >= 2); +}); + +test('an owner\'s per-axis say rides on the theme: the site\'s own option removes the axis', () => { + const theme = sanitizeSpec({ name: 'T', variants: { nav: 'top', post: 'compact' } }); + assert.deepEqual(applyOverrides(theme, { variants: { nav: 'labels', actions: 'labels' } }).variants, { post: 'compact', actions: 'labels' }); + assert.deepEqual(applyOverrides(theme).variants, { nav: 'top', post: 'compact' }); + assert.equal(applyOverrides(theme, { variants: { nav: 'labels', post: 'default' } }).variants, undefined); +}); + +test('decoration: clamps, plain titles, a focus ring that is always visible', () => { + const decor = sanitizeDecor({ + dividers: { style: 'dashed', color: 'muted', width: 9 }, chrome: { kind: 'titlebar', title: 'Timeline"};body{display:none}', glyphs: { home: { d: 'M0 0h1' }, rocket: { d: 'M0 0' }, like: { d: '<' } } })); + assert.ok('pack' in parsed && parsed.pack.name === 'P b' && parsed.pack.license === 'unknown' && parsed.warnings.length === 2); + assert.ok('error' in parseIconPackJson('{')); + assert.ok('error' in parseIconPackJson(JSON.stringify({ id: 'p', name: 'P', glyphs: {} }))); + assert.ok('error' in parseIconPackJson(' '.repeat(ICON_LIMITS.packBytes + 1))); + assert.equal(new Set(ICON_NAMES).size, ICON_NAMES.length); + assert.ok(ICON_NAMES.length <= ICON_LIMITS.names); +}); + +test('a theme names a pack and may adjust it a little; the owner\'s icon choice is separate', () => { + const icons = sanitizeThemeIcons({ pack: 'test-pack', style: { stroke: 9 }, overrides: { home: { d: 'M1 1h2' }, rocket: { d: 'M0 0' } }, symbols: { like: 'star', verified: 'nope' }, labels: { reply: 'reply', like: 'a"b', share: 'way too long a label' }, glyphs: { home: { d: 'M0 0' } } })!; + assert.deepEqual(icons, { pack: 'test-pack', style: { stroke: 2.5 }, overrides: { home: { d: 'M1 1h2' } }, symbols: { like: 'star' }, labels: { reply: 'reply' } }); + assert.equal(sanitizeThemeIcons({ pack: 'NOPE!' }), null); + const catalog = createIconCatalog([PACK]); + assert.equal(catalog.resolve('theme', icons), PACK); + assert.equal(catalog.resolve('theme', null), null); + assert.equal(catalog.resolve('site', icons), null, 'the owner asked for the site\'s own icons'); + assert.equal(catalog.resolve('missing-pack', icons), null, 'a pack that is not installed falls back to the site\'s icons'); + assert.equal(catalog.resolve('test-pack', null), PACK, 'an explicit pick needs no theme'); + assert.equal(normalizeIconChoice('test-pack'), 'test-pack'); + assert.equal(normalizeIconChoice({}), 'theme'); +}); + +test('icons are drawn as masks of the current color (colored glyphs as images), behind guards, per group', () => { + const out = compileIcons(PACK, null, TABLE, { colors: COLORS, gate: 'data-wb-icons' }); + assert.ok(out.startsWith('@media (forced-colors:none){@supports ((mask-image:url("")) or (-webkit-mask-image:url(""))){')); + const home = out.split('\n').find(line => line.startsWith('html[data-wb-icons~="nav"] [data-nav="home"] svg{'))!; + assert.ok(home.includes('background-color:currentColor !important') && home.includes('-webkit-mask:url("data:image/svg+xml,') && home.includes('mask:url("data:image/svg+xml,') && home.includes('/ 90% no-repeat')); + const svgOf = (line: string) => decodeURIComponent(/url\("data:image\/svg\+xml,([^"]*)"\)/.exec(line)![1]!); + assert.ok(svgOf(home).includes('stroke-width="2" stroke-linecap="square" stroke-linejoin="miter"'), 'the pack\'s stroke style'); + const reply = out.split('\n').find(line => line.startsWith('html[data-wb-icons~="actions"] [data-act="reply"] svg{'))!; + assert.ok(reply.includes('background:url("data:image/svg+xml,') && !reply.includes('mask'), 'layers carry their own colors'); + assert.ok(svgOf(reply).includes(`fill="${COLORS.accent}" opacity="0.8"`) && svgOf(reply).includes(' g > path[d^="M12 2.59l5.7 5.7"]){background:url("data:image/png;base64,iVBORw0KGgo=") center / 90% no-repeat !important;image-rendering:pixelated;}')); + assert.ok(out.includes('[data-act="unlike"] svg > *') && out.includes('{opacity:0 !important}'), 'the site\'s own paths are hidden, not removed'); + assert.ok(!out.includes('explore') && !out.includes('script'), 'no glyph: the site\'s icon stays; a signature that is not path data is never written'); + // No encoded quote can end the url("…") early. + for (const url of out.match(/url\("data:image\/svg\+xml,[^)]*\)/g)!) assert.ok(!url.slice(5, -2).includes('"')); + assert.equal(compileIcons(PACK, null, TABLE, { colors: COLORS, allowed: false }), ''); + assert.equal(compileIcons(null, null, TABLE, { colors: COLORS }), ''); + assert.ok(compileIcons(null, { overrides: { explore: { d: 'M2 2h20v20H2z' } } }, TABLE, { colors: null }).includes('[data-nav="explore"] svg{'), 'a theme\'s own override needs no pack'); + assert.equal(glyphSvg({ png: 'data:image/png;base64,AAAA' }, BASE_ICON_STYLE), null); +}); + +test('a group is drawn only when all of its core icons are on the page', () => { + const present = (selectors: string[]) => iconGroupsPresent(TABLE, selector => selectors.includes(selector)); + assert.deepEqual(present(['[data-nav="home"] svg', '[data-nav="explore"] svg', '[data-act="like"] svg', '[data-act="reply"] svg']), ['nav', 'actions', 'composer', 'misc']); + assert.deepEqual(present(['[data-nav="home"] svg', '[data-act="like"] svg', '[data-act="reply"] svg']), ['actions', 'composer', 'misc'], 'a rail never shows half ours, half the site\'s'); + assert.deepEqual(iconGroupsPresent(TABLE, () => { throw new Error('bad selector'); }), ['composer', 'misc']); +}); + +test('a theme document: structure groups are optional, additive and dropped when empty', () => { + const v1 = sanitizeSpec({ name: 'Plain', colors: { bg: '#ffffff', text: '#111111', accent: '#0066cc' } }); + for (const key of ['components', 'variants', 'decor', 'icons']) assert.ok(!(key in v1), `${key} absent from a theme that does not set it`); + assert.ok(!hasStructure(v1)); + const v2 = sanitizeSpec({ + name: 'Built', colors: { bg: '#ffffff', text: '#111111', accent: '#0066cc', actions: { like: '#F5A623', reply: 'red' } }, + components: { post: { preset: 'card' }, nope: {} }, variants: { nav: 'top' }, decor: { links: { underline: 'always' } }, icons: { pack: 'wb-classic' }, + }); + assert.deepEqual(v2.colors!.actions, { like: '#f5a623' }); + assert.deepEqual([v2.components, v2.variants, v2.decor, v2.icons], [{ post: { preset: 'card' } }, { nav: 'top' }, { links: { underline: 'always' } }, { pack: 'wb-classic' }]); + assert.ok(hasStructure(v2)); + assert.ok(!isNeutral(sanitizeSpec({ name: 'Only structure', variants: { nav: 'top' } })), 'a theme that only moves the navigation is not the site\'s own look'); + assert.ok(!hasStructure(sanitizeSpec({ name: 'Nothing', components: { post: {} }, variants: { nav: 'labels' } })), 'empty groups and the site\'s own options are no structure'); +}); + +test('the published schemas are generated from these tables and current', () => { + const script = fileURLToPath(new URL('../../waybetter/scripts/theme-schema.mjs', import.meta.url)); + const run = spawnSync(process.execPath, [script, '--check'], { encoding: 'utf8' }); + assert.equal(run.status, 0, run.stderr); + const schema = JSON.parse(readFileSync(new URL('../../waybetter/theme.schema.json', import.meta.url), 'utf8')); + assert.deepEqual(Object.keys(schema.properties.components.properties), COMPONENT_IDS); + assert.deepEqual([schema.properties.components.properties.post.properties.radius.oneOf[0].minimum, schema.properties.components.properties.post.properties.radius.oneOf[0].maximum], [...TOKEN_LIMITS.radius]); + assert.deepEqual(schema.properties.variants.properties.nav.enum, [...VARIANT_AXES.nav]); + assert.equal(schema.properties.components.properties.postText.properties.case, undefined); + assert.ok(new RegExp(schema.$defs.pathData.pattern).test('M4 4L20 20') && !new RegExp(schema.$defs.pathData.pattern).test('')); + const icons = JSON.parse(readFileSync(new URL('../../waybetter/icons.schema.json', import.meta.url), 'utf8')); + assert.deepEqual(Object.keys(icons.properties.glyphs.properties), [...ICON_NAMES]); + assert.deepEqual(icons.required, ['id', 'name', 'license', 'glyphs']); +}); diff --git a/packages/waybetter/icons.schema.json b/packages/waybetter/icons.schema.json new file mode 100644 index 0000000..d10e6b5 --- /dev/null +++ b/packages/waybetter/icons.schema.json @@ -0,0 +1,646 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://unpkg.com/waybetter/icons.schema.json", + "title": "wayBetter icon pack", + "description": "Glyphs by semantic name, drawn over a site's own icons. Path data, colored layers of path data, or small PNGs: never an SVG document.", + "type": "object", + "required": [ + "id", + "name", + "license", + "glyphs" + ], + "additionalProperties": false, + "properties": { + "$schema": { + "type": "string" + }, + "id": { + "type": "string", + "pattern": "^[a-z0-9-]{1,40}$" + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 60 + }, + "description": { + "type": "string", + "maxLength": 200 + }, + "author": { + "type": "string", + "maxLength": 60 + }, + "license": { + "type": "string", + "minLength": 1, + "maxLength": 60, + "description": "SPDX id, \"own\" for the author's own drawings, or a plain name for artwork under other terms." + }, + "source": { + "type": "string", + "maxLength": 200 + }, + "credits": { + "type": "string", + "maxLength": 400 + }, + "version": { + "const": 1 + }, + "style": { + "type": "object", + "additionalProperties": false, + "properties": { + "stroke": { + "type": "number", + "minimum": 1, + "maximum": 2.5 + }, + "cap": { + "enum": [ + "round", + "square", + "butt" + ] + }, + "join": { + "enum": [ + "round", + "miter", + "bevel" + ] + }, + "scale": { + "type": "number", + "minimum": 0.8, + "maximum": 1.25 + } + } + }, + "glyphs": { + "type": "object", + "additionalProperties": false, + "properties": { + "home": { + "$ref": "#/$defs/glyph" + }, + "home.active": { + "$ref": "#/$defs/glyph" + }, + "explore": { + "$ref": "#/$defs/glyph" + }, + "explore.active": { + "$ref": "#/$defs/glyph" + }, + "notifications": { + "$ref": "#/$defs/glyph" + }, + "notifications.active": { + "$ref": "#/$defs/glyph" + }, + "messages": { + "$ref": "#/$defs/glyph" + }, + "messages.active": { + "$ref": "#/$defs/glyph" + }, + "grok": { + "$ref": "#/$defs/glyph" + }, + "bookmarks": { + "$ref": "#/$defs/glyph" + }, + "bookmarks.active": { + "$ref": "#/$defs/glyph" + }, + "lists": { + "$ref": "#/$defs/glyph" + }, + "communities": { + "$ref": "#/$defs/glyph" + }, + "premium": { + "$ref": "#/$defs/glyph" + }, + "profile": { + "$ref": "#/$defs/glyph" + }, + "profile.active": { + "$ref": "#/$defs/glyph" + }, + "more": { + "$ref": "#/$defs/glyph" + }, + "compose": { + "$ref": "#/$defs/glyph" + }, + "reply": { + "$ref": "#/$defs/glyph" + }, + "repost": { + "$ref": "#/$defs/glyph" + }, + "repost.on": { + "$ref": "#/$defs/glyph" + }, + "like": { + "$ref": "#/$defs/glyph" + }, + "like.on": { + "$ref": "#/$defs/glyph" + }, + "views": { + "$ref": "#/$defs/glyph" + }, + "bookmark": { + "$ref": "#/$defs/glyph" + }, + "bookmark.on": { + "$ref": "#/$defs/glyph" + }, + "share": { + "$ref": "#/$defs/glyph" + }, + "verified": { + "$ref": "#/$defs/glyph" + }, + "logo": { + "$ref": "#/$defs/glyph" + }, + "caret": { + "$ref": "#/$defs/glyph" + }, + "back": { + "$ref": "#/$defs/glyph" + }, + "close": { + "$ref": "#/$defs/glyph" + }, + "search": { + "$ref": "#/$defs/glyph" + }, + "settings": { + "$ref": "#/$defs/glyph" + }, + "media": { + "$ref": "#/$defs/glyph" + }, + "gif": { + "$ref": "#/$defs/glyph" + }, + "poll": { + "$ref": "#/$defs/glyph" + }, + "emoji": { + "$ref": "#/$defs/glyph" + }, + "schedule": { + "$ref": "#/$defs/glyph" + }, + "location": { + "$ref": "#/$defs/glyph" + }, + "pinned": { + "$ref": "#/$defs/glyph" + }, + "repostContext": { + "$ref": "#/$defs/glyph" + }, + "lock": { + "$ref": "#/$defs/glyph" + } + }, + "maxProperties": 64, + "minProperties": 1 + }, + "symbols": { + "type": "object", + "additionalProperties": false, + "properties": { + "like": { + "enum": [ + "heart", + "star", + "custom" + ] + }, + "separator": { + "enum": [ + "dot", + "bullet", + "slash", + "dash", + "pipe", + "none" + ] + } + } + }, + "labels": { + "type": "object", + "additionalProperties": false, + "properties": { + "reply": { + "type": "string", + "minLength": 1, + "maxLength": 12, + "pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$" + }, + "repost": { + "type": "string", + "minLength": 1, + "maxLength": 12, + "pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$" + }, + "like": { + "type": "string", + "minLength": 1, + "maxLength": 12, + "pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$" + }, + "views": { + "type": "string", + "minLength": 1, + "maxLength": 12, + "pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$" + }, + "bookmark": { + "type": "string", + "minLength": 1, + "maxLength": 12, + "pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$" + }, + "share": { + "type": "string", + "minLength": 1, + "maxLength": 12, + "pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$" + } + } + } + }, + "$defs": { + "hex": { + "type": "string", + "pattern": "^#[0-9a-fA-F]{6}$" + }, + "role": { + "description": "A color role of the theme. Components never carry a color literal.", + "enum": [ + "bg", + "surface", + "elevated", + "page", + "border", + "text", + "muted", + "accent", + "onAccent", + "inverse", + "onInverse" + ] + }, + "fontRoleName": { + "enum": [ + "interface", + "post", + "heading", + "numbers", + "mono", + "chrome", + "dialog" + ] + }, + "shadow": { + "enum": [ + "none", + "soft", + "deep", + "hard", + "inset", + "glow" + ] + }, + "fill": { + "oneOf": [ + { + "$ref": "#/$defs/role" + }, + { + "const": "transparent" + } + ] + }, + "state": { + "type": "object", + "additionalProperties": false, + "properties": { + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "lift": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "scale": { + "type": "number", + "minimum": 0.96, + "maximum": 1.04 + }, + "underline": { + "type": "boolean" + } + } + }, + "fillGlass": { + "oneOf": [ + { + "$ref": "#/$defs/role" + }, + { + "const": "transparent" + }, + { + "const": "glass" + } + ] + }, + "stateGlass": { + "type": "object", + "additionalProperties": false, + "properties": { + "fill": { + "$ref": "#/$defs/fillGlass" + }, + "text": { + "$ref": "#/$defs/role" + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "lift": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "scale": { + "type": "number", + "minimum": 0.96, + "maximum": 1.04 + }, + "underline": { + "type": "boolean" + } + } + }, + "fillGradient": { + "oneOf": [ + { + "$ref": "#/$defs/role" + }, + { + "const": "transparent" + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "from": { + "$ref": "#/$defs/role" + }, + "to": { + "$ref": "#/$defs/role" + }, + "angle": { + "type": "number", + "minimum": 0, + "maximum": 360 + } + }, + "required": [ + "from", + "to" + ] + } + ] + }, + "stateGradient": { + "type": "object", + "additionalProperties": false, + "properties": { + "fill": { + "$ref": "#/$defs/fillGradient" + }, + "text": { + "$ref": "#/$defs/role" + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "lift": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "scale": { + "type": "number", + "minimum": 0.96, + "maximum": 1.04 + }, + "underline": { + "type": "boolean" + } + } + }, + "fillGlassGradient": { + "oneOf": [ + { + "$ref": "#/$defs/role" + }, + { + "const": "transparent" + }, + { + "const": "glass" + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "from": { + "$ref": "#/$defs/role" + }, + "to": { + "$ref": "#/$defs/role" + }, + "angle": { + "type": "number", + "minimum": 0, + "maximum": 360 + } + }, + "required": [ + "from", + "to" + ] + } + ] + }, + "stateGlassGradient": { + "type": "object", + "additionalProperties": false, + "properties": { + "fill": { + "$ref": "#/$defs/fillGlassGradient" + }, + "text": { + "$ref": "#/$defs/role" + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "lift": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "scale": { + "type": "number", + "minimum": 0.96, + "maximum": 1.04 + }, + "underline": { + "type": "boolean" + } + } + }, + "pathData": { + "type": "string", + "minLength": 1, + "maxLength": 4000, + "pattern": "^[MmLlHhVvCcSsQqTtAaZz0-9eE\\s,.+-]+$" + }, + "glyph": { + "oneOf": [ + { + "type": "object", + "additionalProperties": false, + "properties": { + "d": { + "$ref": "#/$defs/pathData" + }, + "rule": { + "const": "evenodd" + }, + "stroke": { + "type": "boolean" + } + }, + "required": [ + "d" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "layers": { + "type": "array", + "minItems": 1, + "maxItems": 6, + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "d": { + "$ref": "#/$defs/pathData" + }, + "fill": { + "oneOf": [ + { + "$ref": "#/$defs/role" + }, + { + "$ref": "#/$defs/hex" + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "from": { + "$ref": "#/$defs/hex" + }, + "to": { + "$ref": "#/$defs/hex" + } + }, + "required": [ + "from", + "to" + ] + } + ] + }, + "opacity": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "rule": { + "const": "evenodd" + } + }, + "required": [ + "d", + "fill" + ] + } + } + }, + "required": [ + "layers" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "png": { + "type": "string", + "maxLength": 6022, + "pattern": "^data:image/png;base64,[A-Za-z0-9+/]+={0,2}$" + }, + "pixel": { + "type": "boolean" + } + }, + "required": [ + "png" + ] + } + ] + } + } +} diff --git a/packages/waybetter/package.json b/packages/waybetter/package.json index 80e591c..7ed4fd1 100644 --- a/packages/waybetter/package.json +++ b/packages/waybetter/package.json @@ -185,6 +185,7 @@ "import": "./dist/shell/*.js" }, "./theme.schema.json": "./theme.schema.json", + "./icons.schema.json": "./icons.schema.json", "./store-catalog.schema.json": "./store-catalog.schema.json", "./cli/store": "./cli/store.mjs", "./cli/release": "./cli/release.mjs", @@ -200,6 +201,7 @@ "build", "cli", "theme.schema.json", + "icons.schema.json", "store-catalog.schema.json", "i18n.schema.json", "i18n-meta.schema.json", diff --git a/packages/waybetter/scripts/theme-schema.mjs b/packages/waybetter/scripts/theme-schema.mjs new file mode 100644 index 0000000..f16d06b --- /dev/null +++ b/packages/waybetter/scripts/theme-schema.mjs @@ -0,0 +1,32 @@ +// Writes the generated parts of `theme.schema.json` (a theme's structure groups: components, +// variants, decoration, icons, action colors) and the whole `icons.schema.json` (icon packs) from +// the runtime's vocabulary tables, so a range or a word is defined once. +// +// node scripts/theme-schema.mjs rewrite both files +// node scripts/theme-schema.mjs --check exit 1 when a file is stale (the test runs this) +import { readFileSync, writeFileSync } from 'node:fs'; +import { actionColorsSchema, iconPackSchema, structureDefs, structureProperties } from '../../runtime/src/themeSchema.ts'; + +const check = process.argv.includes('--check'); +const file = name => new URL(`../${name}`, import.meta.url); + +/** The theme schema with its generated parts replaced. */ +export function themeSchema(current) { + const schema = structuredClone(current); + Object.assign(schema.properties, structureProperties()); + const colors = schema.properties.colors.oneOf.find(option => option.type === 'object'); + colors.properties.actions = actionColorsSchema(); + Object.assign(schema.$defs, structureDefs()); + return schema; +} +export const iconsSchema = () => iconPackSchema('https://unpkg.com/waybetter/icons.schema.json'); + +const stale = []; +for (const [name, build] of [['theme.schema.json', () => themeSchema(JSON.parse(readFileSync(file('theme.schema.json'), 'utf8')))], ['icons.schema.json', iconsSchema]]) { + const next = `${JSON.stringify(build(), null, 2)}\n`; + let current = ''; + try { current = readFileSync(file(name), 'utf8').replace(/\r\n/g, '\n'); } catch { /* Not written yet. */ } + if (current === next) continue; + if (check) stale.push(name); else { writeFileSync(file(name), next); console.log(`wrote ${name}`); } +} +if (stale.length) { console.error(`stale: ${stale.join(', ')} (run node scripts/theme-schema.mjs)`); process.exit(1); } diff --git a/packages/waybetter/theme.schema.json b/packages/waybetter/theme.schema.json index b18be5b..f790856 100644 --- a/packages/waybetter/theme.schema.json +++ b/packages/waybetter/theme.schema.json @@ -4,35 +4,117 @@ "title": "wayBetter theme", "description": "A wayBetter theme document (data, not a stylesheet). Only `name` is required. Apps sanitize every field before use: values out of range are clamped and unknown values fall back to the default, so this schema describes what is kept unchanged.", "type": "object", - "required": ["name"], + "required": [ + "name" + ], "additionalProperties": false, "properties": { - "$schema": { "type": "string" }, - "id": { "type": "string", "pattern": "^[a-z0-9-]{1,40}$", "description": "Derived from the name when missing." }, - "name": { "type": "string", "minLength": 1, "maxLength": 60, "pattern": "\\S" }, - "description": { "type": "string", "maxLength": 200 }, - "author": { "type": "string", "maxLength": 60 }, - "version": { "const": 1 }, - "mode": { "enum": ["light", "dark", "auto"], "default": "auto", "description": "Which way scrollbars and form controls lean." }, + "$schema": { + "type": "string" + }, + "id": { + "type": "string", + "pattern": "^[a-z0-9-]{1,40}$", + "description": "Derived from the name when missing." + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 60, + "pattern": "\\S" + }, + "description": { + "type": "string", + "maxLength": 200 + }, + "author": { + "type": "string", + "maxLength": 60 + }, + "version": { + "const": 1 + }, + "mode": { + "enum": [ + "light", + "dark", + "auto" + ], + "default": "auto", + "description": "Which way scrollbars and form controls lean." + }, "colors": { "description": "bg, text and accent are required; every other role is derived from them when missing. null keeps the site's own colors.", "oneOf": [ - { "type": "null" }, + { + "type": "null" + }, { "type": "object", - "required": ["bg", "text", "accent"], + "required": [ + "bg", + "text", + "accent" + ], "additionalProperties": false, "properties": { - "bg": { "$ref": "#/$defs/hex", "description": "Column background." }, - "surface": { "$ref": "#/$defs/hex", "description": "Raised surface (cards, inputs)." }, - "elevated": { "$ref": "#/$defs/hex", "description": "Hover / selected surface." }, - "border": { "$ref": "#/$defs/hex" }, - "text": { "$ref": "#/$defs/hex" }, - "muted": { "$ref": "#/$defs/hex", "description": "Secondary text." }, - "accent": { "$ref": "#/$defs/hex", "description": "Links, focus, selected tabs." }, - "inverse": { "$ref": "#/$defs/hex", "description": "The filled primary button." }, - "onInverse": { "$ref": "#/$defs/hex", "description": "The filled primary button's label." }, - "page": { "$ref": "#/$defs/hex", "description": "The canvas behind the columns (defaults to bg)." } + "bg": { + "$ref": "#/$defs/hex", + "description": "Column background." + }, + "surface": { + "$ref": "#/$defs/hex", + "description": "Raised surface (cards, inputs)." + }, + "elevated": { + "$ref": "#/$defs/hex", + "description": "Hover / selected surface." + }, + "border": { + "$ref": "#/$defs/hex" + }, + "text": { + "$ref": "#/$defs/hex" + }, + "muted": { + "$ref": "#/$defs/hex", + "description": "Secondary text." + }, + "accent": { + "$ref": "#/$defs/hex", + "description": "Links, focus, selected tabs." + }, + "inverse": { + "$ref": "#/$defs/hex", + "description": "The filled primary button." + }, + "onInverse": { + "$ref": "#/$defs/hex", + "description": "The filled primary button's label." + }, + "page": { + "$ref": "#/$defs/hex", + "description": "The canvas behind the columns (defaults to bg)." + }, + "actions": { + "description": "Colors of a set action (liked, reposted, bookmarked) and of the reply hover. Absent: the site's own.", + "type": "object", + "additionalProperties": false, + "properties": { + "reply": { + "$ref": "#/$defs/hex" + }, + "repost": { + "$ref": "#/$defs/hex" + }, + "like": { + "$ref": "#/$defs/hex" + }, + "bookmark": { + "$ref": "#/$defs/hex" + } + } + } } } ] @@ -41,29 +123,86 @@ "type": "object", "additionalProperties": false, "properties": { - "family": { "$ref": "#/$defs/fontStack", "description": "Interface font stack; empty keeps the site's font. Shorthand of roles.interface.family (kept for older apps); when roles.interface is present it wins." }, - "tweet": { "$ref": "#/$defs/fontStack", "description": "Post text stack; shorthand of roles.post.family (roles.post wins)." }, + "family": { + "$ref": "#/$defs/fontStack", + "description": "Interface font stack; empty keeps the site's font. Shorthand of roles.interface.family (kept for older apps); when roles.interface is present it wins." + }, + "tweet": { + "$ref": "#/$defs/fontStack", + "description": "Post text stack; shorthand of roles.post.family (roles.post wins)." + }, "roles": { "type": "object", "additionalProperties": false, "description": "Which font goes where. A role is \"inherit\" (the interface font; an inheriting mono role keeps a monospaced face) or its own stack with optional settings.", "properties": { - "interface": { "$ref": "#/$defs/interfaceRole", "description": "The site's whole UI; every other role inherits it." }, - "post": { "$ref": "#/$defs/fontRole", "description": "Post text." }, - "heading": { "$ref": "#/$defs/fontRole", "description": "Display names and headings." }, - "numbers": { "$ref": "#/$defs/fontRole", "description": "Counts (likes, reposts, followers)." }, - "mono": { "$ref": "#/$defs/fontRole", "description": "Code." }, - "chrome": { "$ref": "#/$defs/fontRole", "description": "The app's own window: tabs, address bar, titlebar, panel." }, - "dialog": { "$ref": "#/$defs/fontRole", "description": "Plugin dialogs and toasts (the UI kit)." } + "interface": { + "$ref": "#/$defs/interfaceRole", + "description": "The site's whole UI; every other role inherits it." + }, + "post": { + "$ref": "#/$defs/fontRole", + "description": "Post text." + }, + "heading": { + "$ref": "#/$defs/fontRole", + "description": "Display names and headings." + }, + "numbers": { + "$ref": "#/$defs/fontRole", + "description": "Counts (likes, reposts, followers)." + }, + "mono": { + "$ref": "#/$defs/fontRole", + "description": "Code." + }, + "chrome": { + "$ref": "#/$defs/fontRole", + "description": "The app's own window: tabs, address bar, titlebar, panel." + }, + "dialog": { + "$ref": "#/$defs/fontRole", + "description": "Plugin dialogs and toasts (the UI kit)." + } } }, - "scale": { "type": "number", "minimum": 0.85, "maximum": 1.2, "default": 1 }, - "weight": { "type": "integer", "minimum": 300, "maximum": 500, "default": 400 }, - "bold": { "type": "integer", "minimum": 500, "maximum": 800, "default": 700 }, - "tracking": { "type": "number", "minimum": -0.03, "maximum": 0.06, "default": 0, "description": "Letter spacing in em." }, + "scale": { + "type": "number", + "minimum": 0.85, + "maximum": 1.2, + "default": 1 + }, + "weight": { + "type": "integer", + "minimum": 300, + "maximum": 500, + "default": 400 + }, + "bold": { + "type": "integer", + "minimum": 500, + "maximum": 800, + "default": 700 + }, + "tracking": { + "type": "number", + "minimum": -0.03, + "maximum": 0.06, + "default": 0, + "description": "Letter spacing in em." + }, "leading": { "description": "Post line height; 0 keeps the site's.", - "anyOf": [{ "const": 0 }, { "type": "number", "minimum": 1.2, "maximum": 1.8 }], + "anyOf": [ + { + "const": 0 + }, + { + "type": "number", + "minimum": 1.2, + "maximum": 1.8 + } + ], "default": 0 } } @@ -72,68 +211,176 @@ "type": "object", "additionalProperties": false, "properties": { - "radius": { "type": "integer", "minimum": 0, "maximum": 28, "default": 16, "description": "Card radius in px." }, - "button": { "type": "integer", "minimum": 0, "maximum": 9999, "default": 9999, "description": "Button radius in px (9999 = pill)." }, - "avatar": { "enum": ["circle", "rounded", "square"], "default": "circle" } + "radius": { + "type": "integer", + "minimum": 0, + "maximum": 28, + "default": 16, + "description": "Card radius in px." + }, + "button": { + "type": "integer", + "minimum": 0, + "maximum": 9999, + "default": 9999, + "description": "Button radius in px (9999 = pill)." + }, + "avatar": { + "enum": [ + "circle", + "rounded", + "square" + ], + "default": "circle" + } } }, "layout": { "type": "object", "additionalProperties": false, "properties": { - "column": { "type": "integer", "minimum": 520, "maximum": 820, "default": 600 }, - "sidebar": { "type": "integer", "minimum": 290, "maximum": 400, "default": 350 }, - "density": { "enum": ["compact", "default", "comfortable"], "default": "default" }, - "cards": { "type": "boolean", "default": false }, - "frame": { "type": "boolean", "default": false } + "column": { + "type": "integer", + "minimum": 520, + "maximum": 820, + "default": 600 + }, + "sidebar": { + "type": "integer", + "minimum": 290, + "maximum": 400, + "default": 350 + }, + "density": { + "enum": [ + "compact", + "default", + "comfortable" + ], + "default": "default" + }, + "cards": { + "type": "boolean", + "default": false + }, + "frame": { + "type": "boolean", + "default": false + } } }, "background": { "oneOf": [ { "type": "object", - "required": ["kind"], - "additionalProperties": false, - "properties": { "kind": { "const": "none" } } - }, - { - "type": "object", - "required": ["kind", "from", "to"], + "required": [ + "kind" + ], "additionalProperties": false, "properties": { - "kind": { "const": "gradient" }, - "from": { "$ref": "#/$defs/hex" }, - "to": { "$ref": "#/$defs/hex" }, - "angle": { "type": "integer", "minimum": 0, "maximum": 360, "default": 180 }, - "glow": { "$ref": "#/$defs/hex" } + "kind": { + "const": "none" + } } }, { "type": "object", - "required": ["kind", "ink"], + "required": [ + "kind", + "from", + "to" + ], "additionalProperties": false, "properties": { - "kind": { "const": "pattern" }, - "pattern": { "enum": ["dots", "grid", "diagonal", "scanlines", "paper", "clouds"], "default": "dots" }, - "ink": { "$ref": "#/$defs/hex" }, - "opacity": { "type": "number", "minimum": 0, "maximum": 0.6, "default": 0.1 }, - "size": { "type": "integer", "minimum": 2, "maximum": 400, "default": 24 } + "kind": { + "const": "gradient" + }, + "from": { + "$ref": "#/$defs/hex" + }, + "to": { + "$ref": "#/$defs/hex" + }, + "angle": { + "type": "integer", + "minimum": 0, + "maximum": 360, + "default": 180 + }, + "glow": { + "$ref": "#/$defs/hex" + } } }, { "type": "object", - "required": ["kind", "url"], + "required": [ + "kind", + "ink" + ], "additionalProperties": false, "properties": { - "kind": { "const": "image" }, + "kind": { + "const": "pattern" + }, + "pattern": { + "enum": [ + "dots", + "grid", + "diagonal", + "scanlines", + "paper", + "clouds" + ], + "default": "dots" + }, + "ink": { + "$ref": "#/$defs/hex" + }, + "opacity": { + "type": "number", + "minimum": 0, + "maximum": 0.6, + "default": 0.1 + }, + "size": { + "type": "integer", + "minimum": 2, + "maximum": 400, + "default": 24 + } + } + }, + { + "type": "object", + "required": [ + "kind", + "url" + ], + "additionalProperties": false, + "properties": { + "kind": { + "const": "image" + }, "url": { "type": "string", "maxLength": 1100000, "pattern": "^data:image/(png|jpeg|webp|gif|avif);base64,[A-Za-z0-9+/]+={0,2}$", "description": "An embedded image (about 800 KB at most). Remote URLs are never loaded." }, - "fit": { "enum": ["cover", "tile"], "default": "cover" }, - "dim": { "type": "number", "minimum": 0.35, "maximum": 0.95, "default": 0.6 } + "fit": { + "enum": [ + "cover", + "tile" + ], + "default": "cover" + }, + "dim": { + "type": "number", + "minimum": 0.35, + "maximum": 0.95, + "default": 0.6 + } } } ] @@ -142,46 +389,3886 @@ "type": "object", "additionalProperties": false, "properties": { - "motion": { "type": "integer", "minimum": 0, "maximum": 400, "default": 0, "description": "Transition length in ms." }, - "hover": { "enum": ["none", "tint", "lift", "glow"], "default": "none" }, - "shadow": { "enum": ["none", "soft", "deep"], "default": "none" }, - "crt": { "type": "boolean", "default": false } + "motion": { + "type": "integer", + "minimum": 0, + "maximum": 400, + "default": 0, + "description": "Transition length in ms." + }, + "hover": { + "enum": [ + "none", + "tint", + "lift", + "glow" + ], + "default": "none" + }, + "shadow": { + "enum": [ + "none", + "soft", + "deep" + ], + "default": "none" + }, + "crt": { + "type": "boolean", + "default": false + } } }, "css": { "type": "string", "maxLength": 60000, "description": "Free-form CSS appended last. Same trust level as the owner's own Custom CSS; import dialogs say so." + }, + "components": { + "description": "How each piece of the site is built. Every token is optional; a missing token changes nothing.", + "type": "object", + "additionalProperties": false, + "properties": { + "nav": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fillGlassGradient" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/stateGlassGradient" + }, + "active": { + "$ref": "#/$defs/stateGlassGradient" + }, + "focus": { + "$ref": "#/$defs/stateGlassGradient" + }, + "width": { + "type": "number", + "minimum": 56, + "maximum": 320 + } + } + }, + "navItem": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "height": { + "type": "number", + "minimum": 36, + "maximum": 64 + }, + "fontSize": { + "type": "number", + "minimum": 12, + "maximum": 20 + }, + "font": { + "$ref": "#/$defs/fontRoleName" + }, + "weight": { + "type": "number", + "minimum": 100, + "maximum": 900 + }, + "case": { + "enum": [ + "none", + "upper", + "lower", + "capitalize", + "small-caps" + ] + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.2 + }, + "leading": { + "type": "number", + "minimum": 1.1, + "maximum": 2 + } + } + }, + "topBar": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fillGlassGradient" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/stateGlassGradient" + }, + "active": { + "$ref": "#/$defs/stateGlassGradient" + }, + "focus": { + "$ref": "#/$defs/stateGlassGradient" + }, + "height": { + "type": "number", + "minimum": 40, + "maximum": 64 + }, + "fontSize": { + "type": "number", + "minimum": 12, + "maximum": 20 + }, + "font": { + "$ref": "#/$defs/fontRoleName" + }, + "weight": { + "type": "number", + "minimum": 100, + "maximum": 900 + }, + "case": { + "enum": [ + "none", + "upper", + "lower", + "capitalize", + "small-caps" + ] + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.2 + }, + "leading": { + "type": "number", + "minimum": 1.1, + "maximum": 2 + } + } + }, + "tabs": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fillGradient" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/stateGradient" + }, + "active": { + "$ref": "#/$defs/stateGradient" + }, + "focus": { + "$ref": "#/$defs/stateGradient" + }, + "preset": { + "enum": [ + "underline", + "pills", + "folder", + "blocks" + ] + } + } + }, + "tab": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "preset": { + "enum": [ + "underline", + "pills", + "folder", + "blocks" + ] + }, + "height": { + "type": "number", + "minimum": 32, + "maximum": 56 + }, + "fontSize": { + "type": "number", + "minimum": 12, + "maximum": 20 + }, + "font": { + "$ref": "#/$defs/fontRoleName" + }, + "weight": { + "type": "number", + "minimum": 100, + "maximum": 900 + }, + "case": { + "enum": [ + "none", + "upper", + "lower", + "capitalize", + "small-caps" + ] + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.2 + }, + "leading": { + "type": "number", + "minimum": 1.1, + "maximum": 2 + } + } + }, + "post": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "preset": { + "enum": [ + "flat", + "card", + "bubble", + "window", + "ruled" + ] + }, + "corner": { + "enum": [ + "round", + "cut" + ] + } + } + }, + "avatar": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "size": { + "type": "number", + "minimum": 20, + "maximum": 64 + }, + "shape": { + "enum": [ + "circle", + "rounded", + "square", + "squircle", + "hexagon", + "octagon", + "diamond" + ] + }, + "visible": { + "type": "boolean" + } + } + }, + "displayName": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "fontSize": { + "type": "number", + "minimum": 12, + "maximum": 20 + }, + "font": { + "$ref": "#/$defs/fontRoleName" + }, + "weight": { + "type": "number", + "minimum": 100, + "maximum": 900 + }, + "case": { + "enum": [ + "none", + "upper", + "lower", + "capitalize", + "small-caps" + ] + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.2 + }, + "leading": { + "type": "number", + "minimum": 1.1, + "maximum": 2 + }, + "visible": { + "type": "boolean" + } + } + }, + "handle": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "fontSize": { + "type": "number", + "minimum": 11, + "maximum": 18 + }, + "font": { + "$ref": "#/$defs/fontRoleName" + }, + "weight": { + "type": "number", + "minimum": 100, + "maximum": 900 + }, + "case": { + "enum": [ + "none", + "upper", + "lower", + "capitalize", + "small-caps" + ] + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.2 + }, + "leading": { + "type": "number", + "minimum": 1.1, + "maximum": 2 + }, + "visible": { + "type": "boolean" + } + } + }, + "postText": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "fontSize": { + "type": "number", + "minimum": 13, + "maximum": 24 + }, + "font": { + "$ref": "#/$defs/fontRoleName" + }, + "weight": { + "type": "number", + "minimum": 100, + "maximum": 900 + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.2 + }, + "leading": { + "type": "number", + "minimum": 1.1, + "maximum": 2 + } + } + }, + "meta": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "fontSize": { + "type": "number", + "minimum": 11, + "maximum": 18 + }, + "font": { + "$ref": "#/$defs/fontRoleName" + }, + "weight": { + "type": "number", + "minimum": 100, + "maximum": 900 + }, + "case": { + "enum": [ + "none", + "upper", + "lower", + "capitalize", + "small-caps" + ] + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.2 + }, + "leading": { + "type": "number", + "minimum": 1.1, + "maximum": 2 + } + } + }, + "actionBar": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + } + } + }, + "action": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "size": { + "type": "number", + "minimum": 28, + "maximum": 44 + } + } + }, + "count": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "fontSize": { + "type": "number", + "minimum": 11, + "maximum": 18 + }, + "font": { + "$ref": "#/$defs/fontRoleName" + }, + "weight": { + "type": "number", + "minimum": 100, + "maximum": 900 + }, + "case": { + "enum": [ + "none", + "upper", + "lower", + "capitalize", + "small-caps" + ] + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.2 + }, + "leading": { + "type": "number", + "minimum": 1.1, + "maximum": 2 + }, + "visible": { + "type": "boolean" + } + } + }, + "media": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "maxHeight": { + "type": "number", + "minimum": 200, + "maximum": 700 + }, + "corner": { + "enum": [ + "round", + "cut" + ] + } + } + }, + "linkCard": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "corner": { + "enum": [ + "round", + "cut" + ] + } + } + }, + "quote": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + } + } + }, + "button": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fillGradient" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/stateGradient" + }, + "active": { + "$ref": "#/$defs/stateGradient" + }, + "focus": { + "$ref": "#/$defs/stateGradient" + }, + "preset": { + "enum": [ + "pill", + "soft", + "square", + "outline", + "bevel", + "gloss", + "flat-link" + ] + }, + "height": { + "type": "number", + "minimum": 24, + "maximum": 56 + }, + "fontSize": { + "type": "number", + "minimum": 12, + "maximum": 20 + }, + "font": { + "$ref": "#/$defs/fontRoleName" + }, + "weight": { + "type": "number", + "minimum": 100, + "maximum": 900 + }, + "case": { + "enum": [ + "none", + "upper", + "lower", + "capitalize", + "small-caps" + ] + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.2 + }, + "leading": { + "type": "number", + "minimum": 1.1, + "maximum": 2 + } + } + }, + "buttonPrimary": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fillGradient" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/stateGradient" + }, + "active": { + "$ref": "#/$defs/stateGradient" + }, + "focus": { + "$ref": "#/$defs/stateGradient" + }, + "preset": { + "enum": [ + "pill", + "soft", + "square", + "outline", + "bevel", + "gloss", + "flat-link" + ] + }, + "height": { + "type": "number", + "minimum": 24, + "maximum": 56 + }, + "fontSize": { + "type": "number", + "minimum": 12, + "maximum": 20 + }, + "font": { + "$ref": "#/$defs/fontRoleName" + }, + "weight": { + "type": "number", + "minimum": 100, + "maximum": 900 + }, + "case": { + "enum": [ + "none", + "upper", + "lower", + "capitalize", + "small-caps" + ] + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.2 + }, + "leading": { + "type": "number", + "minimum": 1.1, + "maximum": 2 + } + } + }, + "buttonSecondary": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fillGradient" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/stateGradient" + }, + "active": { + "$ref": "#/$defs/stateGradient" + }, + "focus": { + "$ref": "#/$defs/stateGradient" + }, + "preset": { + "enum": [ + "pill", + "soft", + "square", + "outline", + "bevel", + "gloss", + "flat-link" + ] + }, + "height": { + "type": "number", + "minimum": 24, + "maximum": 56 + }, + "fontSize": { + "type": "number", + "minimum": 12, + "maximum": 20 + }, + "font": { + "$ref": "#/$defs/fontRoleName" + }, + "weight": { + "type": "number", + "minimum": 100, + "maximum": 900 + }, + "case": { + "enum": [ + "none", + "upper", + "lower", + "capitalize", + "small-caps" + ] + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.2 + }, + "leading": { + "type": "number", + "minimum": 1.1, + "maximum": 2 + } + } + }, + "buttonGhost": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fillGradient" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/stateGradient" + }, + "active": { + "$ref": "#/$defs/stateGradient" + }, + "focus": { + "$ref": "#/$defs/stateGradient" + }, + "preset": { + "enum": [ + "pill", + "soft", + "square", + "outline", + "bevel", + "gloss", + "flat-link" + ] + }, + "height": { + "type": "number", + "minimum": 24, + "maximum": 56 + }, + "fontSize": { + "type": "number", + "minimum": 12, + "maximum": 20 + }, + "font": { + "$ref": "#/$defs/fontRoleName" + }, + "weight": { + "type": "number", + "minimum": 100, + "maximum": 900 + }, + "case": { + "enum": [ + "none", + "upper", + "lower", + "capitalize", + "small-caps" + ] + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.2 + }, + "leading": { + "type": "number", + "minimum": 1.1, + "maximum": 2 + } + } + }, + "input": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "preset": { + "enum": [ + "pill", + "underline", + "sunken", + "boxed" + ] + }, + "height": { + "type": "number", + "minimum": 32, + "maximum": 56 + }, + "fontSize": { + "type": "number", + "minimum": 12, + "maximum": 20 + }, + "font": { + "$ref": "#/$defs/fontRoleName" + }, + "weight": { + "type": "number", + "minimum": 100, + "maximum": 900 + }, + "case": { + "enum": [ + "none", + "upper", + "lower", + "capitalize", + "small-caps" + ] + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.2 + }, + "leading": { + "type": "number", + "minimum": 1.1, + "maximum": 2 + } + } + }, + "search": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "preset": { + "enum": [ + "pill", + "underline", + "sunken", + "boxed" + ] + }, + "height": { + "type": "number", + "minimum": 32, + "maximum": 56 + }, + "fontSize": { + "type": "number", + "minimum": 12, + "maximum": 20 + }, + "font": { + "$ref": "#/$defs/fontRoleName" + }, + "weight": { + "type": "number", + "minimum": 100, + "maximum": 900 + }, + "case": { + "enum": [ + "none", + "upper", + "lower", + "capitalize", + "small-caps" + ] + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.2 + }, + "leading": { + "type": "number", + "minimum": 1.1, + "maximum": 2 + } + } + }, + "composer": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "fontSize": { + "type": "number", + "minimum": 13, + "maximum": 24 + }, + "font": { + "$ref": "#/$defs/fontRoleName" + }, + "weight": { + "type": "number", + "minimum": 100, + "maximum": 900 + }, + "case": { + "enum": [ + "none", + "upper", + "lower", + "capitalize", + "small-caps" + ] + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.2 + }, + "leading": { + "type": "number", + "minimum": 1.1, + "maximum": 2 + } + } + }, + "composerTool": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "size": { + "type": "number", + "minimum": 28, + "maximum": 44 + } + } + }, + "panel": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fillGlass" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/stateGlass" + }, + "active": { + "$ref": "#/$defs/stateGlass" + }, + "focus": { + "$ref": "#/$defs/stateGlass" + }, + "preset": { + "enum": [ + "sheet", + "window", + "glass" + ] + } + } + }, + "menu": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fillGlass" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/stateGlass" + }, + "active": { + "$ref": "#/$defs/stateGlass" + }, + "focus": { + "$ref": "#/$defs/stateGlass" + }, + "preset": { + "enum": [ + "sheet", + "window", + "glass" + ] + } + } + }, + "dialog": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fillGlass" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/stateGlass" + }, + "active": { + "$ref": "#/$defs/stateGlass" + }, + "focus": { + "$ref": "#/$defs/stateGlass" + }, + "preset": { + "enum": [ + "sheet", + "window", + "glass" + ] + } + } + }, + "toast": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fillGlass" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/stateGlass" + }, + "active": { + "$ref": "#/$defs/stateGlass" + }, + "focus": { + "$ref": "#/$defs/stateGlass" + }, + "preset": { + "enum": [ + "sheet", + "window", + "glass" + ] + } + } + }, + "hoverCard": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fillGlass" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/stateGlass" + }, + "active": { + "$ref": "#/$defs/stateGlass" + }, + "focus": { + "$ref": "#/$defs/stateGlass" + }, + "preset": { + "enum": [ + "sheet", + "window", + "glass" + ] + } + } + }, + "sidebarCard": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fillGlass" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/stateGlass" + }, + "active": { + "$ref": "#/$defs/stateGlass" + }, + "focus": { + "$ref": "#/$defs/stateGlass" + }, + "preset": { + "enum": [ + "sheet", + "window", + "glass" + ] + }, + "corner": { + "enum": [ + "round", + "cut" + ] + } + } + }, + "badge": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "size": { + "type": "number", + "minimum": 14, + "maximum": 24 + }, + "fontSize": { + "type": "number", + "minimum": 11, + "maximum": 18 + }, + "font": { + "$ref": "#/$defs/fontRoleName" + }, + "weight": { + "type": "number", + "minimum": 100, + "maximum": 900 + }, + "case": { + "enum": [ + "none", + "upper", + "lower", + "capitalize", + "small-caps" + ] + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.2 + }, + "leading": { + "type": "number", + "minimum": 1.1, + "maximum": 2 + }, + "corner": { + "enum": [ + "round", + "cut" + ] + } + } + }, + "pill": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + }, + "fontSize": { + "type": "number", + "minimum": 11, + "maximum": 18 + }, + "font": { + "$ref": "#/$defs/fontRoleName" + }, + "weight": { + "type": "number", + "minimum": 100, + "maximum": 900 + }, + "case": { + "enum": [ + "none", + "upper", + "lower", + "capitalize", + "small-caps" + ] + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.2 + }, + "leading": { + "type": "number", + "minimum": 1.1, + "maximum": 2 + } + } + }, + "divider": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + } + } + }, + "scrollbar": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + } + } + }, + "profileHeader": { + "type": "object", + "additionalProperties": false, + "properties": { + "radius": { + "oneOf": [ + { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + { + "const": "pill" + } + ] + }, + "borderWidth": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "borderStyle": { + "enum": [ + "none", + "solid", + "dashed", + "dotted", + "double", + "bevel-out", + "bevel-in" + ] + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "padX": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "padY": { + "type": "number", + "minimum": 0, + "maximum": 32 + }, + "gap": { + "type": "number", + "minimum": 0, + "maximum": 24 + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "hover": { + "$ref": "#/$defs/state" + }, + "active": { + "$ref": "#/$defs/state" + }, + "focus": { + "$ref": "#/$defs/state" + } + } + } + } + }, + "variants": { + "description": "Structural choices. The first option of each axis is the site's own layout.", + "type": "object", + "additionalProperties": false, + "properties": { + "nav": { + "enum": [ + "labels", + "icons", + "top", + "bottom" + ] + }, + "post": { + "enum": [ + "default", + "cards", + "bubbles", + "compact", + "broadsheet" + ] + }, + "actions": { + "enum": [ + "icons", + "labels", + "quiet" + ] + }, + "header": { + "enum": [ + "default", + "solid", + "bar" + ] + }, + "sidebar": { + "enum": [ + "default", + "narrow", + "hidden" + ] + }, + "width": { + "enum": [ + "default", + "full" + ] + } + } + }, + "decor": { + "description": "Lines, bars, focus ring, selection, scrollbars, link underlines, motion.", + "type": "object", + "additionalProperties": false, + "properties": { + "dividers": { + "type": "object", + "additionalProperties": false, + "properties": { + "style": { + "enum": [ + "none", + "hairline", + "solid", + "dashed", + "dotted", + "double" + ] + }, + "color": { + "$ref": "#/$defs/role" + }, + "width": { + "type": "number", + "minimum": 0, + "maximum": 3 + } + }, + "required": [ + "style" + ] + }, + "chrome": { + "type": "object", + "additionalProperties": false, + "properties": { + "kind": { + "enum": [ + "none", + "titlebar", + "masthead", + "prompt" + ] + }, + "title": { + "type": "string", + "maxLength": 24 + } + }, + "required": [ + "kind" + ] + }, + "focusRing": { + "type": "object", + "additionalProperties": false, + "properties": { + "width": { + "type": "number", + "minimum": 2, + "maximum": 4 + }, + "style": { + "enum": [ + "solid", + "dashed", + "dotted", + "double" + ] + }, + "color": { + "$ref": "#/$defs/role" + }, + "offset": { + "type": "number", + "minimum": 0, + "maximum": 4 + } + } + }, + "selection": { + "type": "object", + "additionalProperties": false, + "properties": { + "fill": { + "$ref": "#/$defs/role" + }, + "text": { + "$ref": "#/$defs/role" + } + }, + "required": [ + "fill", + "text" + ] + }, + "scrollbar": { + "type": "object", + "additionalProperties": false, + "properties": { + "width": { + "enum": [ + "auto", + "thin" + ] + }, + "thumb": { + "$ref": "#/$defs/role" + }, + "track": { + "$ref": "#/$defs/role" + }, + "style": { + "enum": [ + "flat", + "classic" + ] + } + } + }, + "links": { + "type": "object", + "additionalProperties": false, + "properties": { + "underline": { + "enum": [ + "always", + "hover", + "never" + ] + } + }, + "required": [ + "underline" + ] + }, + "motion": { + "type": "object", + "additionalProperties": false, + "properties": { + "duration": { + "type": "number", + "minimum": 0, + "maximum": 400 + }, + "curve": { + "enum": [ + "standard", + "snappy", + "spring", + "linear", + "steps" + ] + }, + "press": { + "type": "number", + "minimum": 0.96, + "maximum": 1 + } + } + } + } + }, + "icons": { + "description": "The icon pack this theme suggests (by id), with small adjustments. A whole pack is its own document (icons.schema.json).", + "type": "object", + "additionalProperties": false, + "properties": { + "pack": { + "type": "string", + "pattern": "^[a-z0-9-]{1,40}$" + }, + "style": { + "type": "object", + "additionalProperties": false, + "properties": { + "stroke": { + "type": "number", + "minimum": 1, + "maximum": 2.5 + }, + "cap": { + "enum": [ + "round", + "square", + "butt" + ] + }, + "join": { + "enum": [ + "round", + "miter", + "bevel" + ] + }, + "scale": { + "type": "number", + "minimum": 0.8, + "maximum": 1.25 + } + } + }, + "overrides": { + "type": "object", + "additionalProperties": false, + "properties": { + "home": { + "$ref": "#/$defs/glyph" + }, + "home.active": { + "$ref": "#/$defs/glyph" + }, + "explore": { + "$ref": "#/$defs/glyph" + }, + "explore.active": { + "$ref": "#/$defs/glyph" + }, + "notifications": { + "$ref": "#/$defs/glyph" + }, + "notifications.active": { + "$ref": "#/$defs/glyph" + }, + "messages": { + "$ref": "#/$defs/glyph" + }, + "messages.active": { + "$ref": "#/$defs/glyph" + }, + "grok": { + "$ref": "#/$defs/glyph" + }, + "bookmarks": { + "$ref": "#/$defs/glyph" + }, + "bookmarks.active": { + "$ref": "#/$defs/glyph" + }, + "lists": { + "$ref": "#/$defs/glyph" + }, + "communities": { + "$ref": "#/$defs/glyph" + }, + "premium": { + "$ref": "#/$defs/glyph" + }, + "profile": { + "$ref": "#/$defs/glyph" + }, + "profile.active": { + "$ref": "#/$defs/glyph" + }, + "more": { + "$ref": "#/$defs/glyph" + }, + "compose": { + "$ref": "#/$defs/glyph" + }, + "reply": { + "$ref": "#/$defs/glyph" + }, + "repost": { + "$ref": "#/$defs/glyph" + }, + "repost.on": { + "$ref": "#/$defs/glyph" + }, + "like": { + "$ref": "#/$defs/glyph" + }, + "like.on": { + "$ref": "#/$defs/glyph" + }, + "views": { + "$ref": "#/$defs/glyph" + }, + "bookmark": { + "$ref": "#/$defs/glyph" + }, + "bookmark.on": { + "$ref": "#/$defs/glyph" + }, + "share": { + "$ref": "#/$defs/glyph" + }, + "verified": { + "$ref": "#/$defs/glyph" + }, + "logo": { + "$ref": "#/$defs/glyph" + }, + "caret": { + "$ref": "#/$defs/glyph" + }, + "back": { + "$ref": "#/$defs/glyph" + }, + "close": { + "$ref": "#/$defs/glyph" + }, + "search": { + "$ref": "#/$defs/glyph" + }, + "settings": { + "$ref": "#/$defs/glyph" + }, + "media": { + "$ref": "#/$defs/glyph" + }, + "gif": { + "$ref": "#/$defs/glyph" + }, + "poll": { + "$ref": "#/$defs/glyph" + }, + "emoji": { + "$ref": "#/$defs/glyph" + }, + "schedule": { + "$ref": "#/$defs/glyph" + }, + "location": { + "$ref": "#/$defs/glyph" + }, + "pinned": { + "$ref": "#/$defs/glyph" + }, + "repostContext": { + "$ref": "#/$defs/glyph" + }, + "lock": { + "$ref": "#/$defs/glyph" + } + }, + "maxProperties": 8 + }, + "symbols": { + "type": "object", + "additionalProperties": false, + "properties": { + "like": { + "enum": [ + "heart", + "star", + "custom" + ] + }, + "separator": { + "enum": [ + "dot", + "bullet", + "slash", + "dash", + "pipe", + "none" + ] + } + } + }, + "labels": { + "type": "object", + "additionalProperties": false, + "properties": { + "reply": { + "type": "string", + "minLength": 1, + "maxLength": 12, + "pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$" + }, + "repost": { + "type": "string", + "minLength": 1, + "maxLength": 12, + "pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$" + }, + "like": { + "type": "string", + "minLength": 1, + "maxLength": 12, + "pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$" + }, + "views": { + "type": "string", + "minLength": 1, + "maxLength": 12, + "pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$" + }, + "bookmark": { + "type": "string", + "minLength": 1, + "maxLength": 12, + "pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$" + }, + "share": { + "type": "string", + "minLength": 1, + "maxLength": 12, + "pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$" + } + } + } + } } }, "$defs": { - "hex": { "type": "string", "pattern": "^#[0-9a-fA-F]{6}$" }, - "source": { "const": "google", "description": "The first family is a Google Fonts family: apps download it (asking first for an imported theme) and load it from bytes." }, + "hex": { + "type": "string", + "pattern": "^#[0-9a-fA-F]{6}$" + }, + "source": { + "const": "google", + "description": "The first family is a Google Fonts family: apps download it (asking first for an imported theme) and load it from bytes." + }, "interfaceRole": { "oneOf": [ - { "const": "inherit" }, + { + "const": "inherit" + }, { "type": "object", - "required": ["family"], + "required": [ + "family" + ], "additionalProperties": false, - "properties": { "family": { "$ref": "#/$defs/fontStack" }, "source": { "$ref": "#/$defs/source" } } + "properties": { + "family": { + "$ref": "#/$defs/fontStack" + }, + "source": { + "$ref": "#/$defs/source" + } + } } ] }, "fontRole": { "oneOf": [ - { "const": "inherit" }, + { + "const": "inherit" + }, { "type": "object", - "required": ["family"], + "required": [ + "family" + ], "additionalProperties": false, "properties": { - "family": { "$ref": "#/$defs/fontStack", "description": "Empty keeps the inherited family and changes only the settings below." }, - "source": { "$ref": "#/$defs/source" }, - "weight": { "type": "integer", "minimum": 100, "maximum": 900 }, - "size": { "type": "number", "minimum": 0.75, "maximum": 1.5, "description": "Relative to the site's size." }, - "tracking": { "type": "number", "minimum": -0.05, "maximum": 0.1, "description": "Letter spacing in em." }, - "tabular": { "type": "boolean", "description": "Tabular (fixed-width) figures." } + "family": { + "$ref": "#/$defs/fontStack", + "description": "Empty keeps the inherited family and changes only the settings below." + }, + "source": { + "$ref": "#/$defs/source" + }, + "weight": { + "type": "integer", + "minimum": 100, + "maximum": 900 + }, + "size": { + "type": "number", + "minimum": 0.75, + "maximum": 1.5, + "description": "Relative to the site's size." + }, + "tracking": { + "type": "number", + "minimum": -0.05, + "maximum": 0.1, + "description": "Letter spacing in em." + }, + "tabular": { + "type": "boolean", + "description": "Tabular (fixed-width) figures." + } } } ] @@ -191,10 +4278,382 @@ "maxItems": 8, "items": { "anyOf": [ - { "enum": ["system-ui", "sans-serif", "serif", "monospace", "cursive", "ui-sans-serif", "ui-serif", "ui-monospace", "ui-rounded", "-apple-system", "BlinkMacSystemFont"] }, - { "type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9 .\\-]{0,47}$" } + { + "enum": [ + "system-ui", + "sans-serif", + "serif", + "monospace", + "cursive", + "ui-sans-serif", + "ui-serif", + "ui-monospace", + "ui-rounded", + "-apple-system", + "BlinkMacSystemFont" + ] + }, + { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9 .\\-]{0,47}$" + } ] } + }, + "role": { + "description": "A color role of the theme. Components never carry a color literal.", + "enum": [ + "bg", + "surface", + "elevated", + "page", + "border", + "text", + "muted", + "accent", + "onAccent", + "inverse", + "onInverse" + ] + }, + "fontRoleName": { + "enum": [ + "interface", + "post", + "heading", + "numbers", + "mono", + "chrome", + "dialog" + ] + }, + "pathData": { + "type": "string", + "minLength": 1, + "maxLength": 4000, + "pattern": "^[MmLlHhVvCcSsQqTtAaZz0-9eE\\s,.+-]+$" + }, + "glyph": { + "oneOf": [ + { + "type": "object", + "additionalProperties": false, + "properties": { + "d": { + "$ref": "#/$defs/pathData" + }, + "rule": { + "const": "evenodd" + }, + "stroke": { + "type": "boolean" + } + }, + "required": [ + "d" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "layers": { + "type": "array", + "minItems": 1, + "maxItems": 6, + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "d": { + "$ref": "#/$defs/pathData" + }, + "fill": { + "oneOf": [ + { + "$ref": "#/$defs/role" + }, + { + "$ref": "#/$defs/hex" + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "from": { + "$ref": "#/$defs/hex" + }, + "to": { + "$ref": "#/$defs/hex" + } + }, + "required": [ + "from", + "to" + ] + } + ] + }, + "opacity": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "rule": { + "const": "evenodd" + } + }, + "required": [ + "d", + "fill" + ] + } + } + }, + "required": [ + "layers" + ] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "png": { + "type": "string", + "maxLength": 6022, + "pattern": "^data:image/png;base64,[A-Za-z0-9+/]+={0,2}$" + }, + "pixel": { + "type": "boolean" + } + }, + "required": [ + "png" + ] + } + ] + }, + "shadow": { + "enum": [ + "none", + "soft", + "deep", + "hard", + "inset", + "glow" + ] + }, + "fill": { + "oneOf": [ + { + "$ref": "#/$defs/role" + }, + { + "const": "transparent" + } + ] + }, + "state": { + "type": "object", + "additionalProperties": false, + "properties": { + "fill": { + "$ref": "#/$defs/fill" + }, + "text": { + "$ref": "#/$defs/role" + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "lift": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "scale": { + "type": "number", + "minimum": 0.96, + "maximum": 1.04 + }, + "underline": { + "type": "boolean" + } + } + }, + "fillGlass": { + "oneOf": [ + { + "$ref": "#/$defs/role" + }, + { + "const": "transparent" + }, + { + "const": "glass" + } + ] + }, + "stateGlass": { + "type": "object", + "additionalProperties": false, + "properties": { + "fill": { + "$ref": "#/$defs/fillGlass" + }, + "text": { + "$ref": "#/$defs/role" + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "lift": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "scale": { + "type": "number", + "minimum": 0.96, + "maximum": 1.04 + }, + "underline": { + "type": "boolean" + } + } + }, + "fillGradient": { + "oneOf": [ + { + "$ref": "#/$defs/role" + }, + { + "const": "transparent" + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "from": { + "$ref": "#/$defs/role" + }, + "to": { + "$ref": "#/$defs/role" + }, + "angle": { + "type": "number", + "minimum": 0, + "maximum": 360 + } + }, + "required": [ + "from", + "to" + ] + } + ] + }, + "stateGradient": { + "type": "object", + "additionalProperties": false, + "properties": { + "fill": { + "$ref": "#/$defs/fillGradient" + }, + "text": { + "$ref": "#/$defs/role" + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "lift": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "scale": { + "type": "number", + "minimum": 0.96, + "maximum": 1.04 + }, + "underline": { + "type": "boolean" + } + } + }, + "fillGlassGradient": { + "oneOf": [ + { + "$ref": "#/$defs/role" + }, + { + "const": "transparent" + }, + { + "const": "glass" + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "from": { + "$ref": "#/$defs/role" + }, + "to": { + "$ref": "#/$defs/role" + }, + "angle": { + "type": "number", + "minimum": 0, + "maximum": 360 + } + }, + "required": [ + "from", + "to" + ] + } + ] + }, + "stateGlassGradient": { + "type": "object", + "additionalProperties": false, + "properties": { + "fill": { + "$ref": "#/$defs/fillGlassGradient" + }, + "text": { + "$ref": "#/$defs/role" + }, + "borderColor": { + "$ref": "#/$defs/role" + }, + "shadow": { + "$ref": "#/$defs/shadow" + }, + "lift": { + "type": "number", + "minimum": 0, + "maximum": 4 + }, + "scale": { + "type": "number", + "minimum": 0.96, + "maximum": 1.04 + }, + "underline": { + "type": "boolean" + } + } } } } From f8144a3bff8caf8f027492418ca5c9a693829bec Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 30 Sep 2026 23:23:43 +0700 Subject: [PATCH 25/72] Windows installer: an install made under the app's old name is older than any setup of the renamed app, whatever its version number (upgrade in place, data kept) The renamed app may start its numbering again. Told apart by DisplayName in the uninstall key (the old app wrote its old name there; this template writes the new one). Also exempt from the silent-downgrade abort. Compiled with and without a legacy name and run on the test variant. Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 4 ++- packages/waybetter/windows/installer.nsi | 33 ++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ad384d4..1eb1031 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -492,7 +492,9 @@ The npm package adds the app-side tooling: install the updater has moved on. `/FORCE` reinstalls the same version (repair), `/NORUN` does not open the app, `/UPDATE` is the updater's path and always installs. An app renamed after its first release keeps its registry keys by defining `WAYBETTER_LEGACY_NAME` in its installer hooks - (`bundle.windows.nsis.installerHooks`). + (`bundle.windows.nsis.installerHooks`). An install made under the old name (its `DisplayName` is + still that name) counts as older than any setup of the renamed app, whatever its version number: + the renamed app may start its numbering again and still upgrades such an install in place. ## Consuming it diff --git a/packages/waybetter/windows/installer.nsi b/packages/waybetter/windows/installer.nsi index 8330de1..86df64c 100644 --- a/packages/waybetter/windows/installer.nsi +++ b/packages/waybetter/windows/installer.nsi @@ -7,7 +7,9 @@ ; - the same or a newer version is installed: installs nothing, opens the installed app (its ; single-instance guard shows the running window) and exits 0. So an old setup left in ; Downloads can never replace, restart or downgrade an install the updater has moved on; -; - an older version is installed: upgrades in place (app data untouched), then opens the app. +; - an older version is installed: upgrades in place (app data untouched), then opens the app; +; - an install made under the app's old name (see WAYBETTER_LEGACY_NAME below) counts as older, +; whatever its version number says: it is upgraded in place, data kept. ; Flags: `/NORUN` never opens the app, `/FORCE` reinstalls the same version (repair; it still never ; downgrades), `/UPDATE` is the updater's path (tauri-plugin-updater: `/UPDATE /R /ARGS ...`), ; which always installs and is otherwise Tauri's. `/NS` (no shortcuts) and `/D=` as in Tauri. @@ -17,6 +19,9 @@ ; (`bundle.windows.nsis.installerHooks`), which are included before anything here reads it: ; !define WAYBETTER_LEGACY_NAME "Old Product Name" ; !define WAYBETTER_LEGACY_MANUFACTURER "Old Publisher" ; optional, defaults to the old name +; The renamed app may start its version numbers again (a 1.0.0 after an old 1.0.2): an install +; whose DisplayName is still the old name was written by the old app, and every setup of the +; renamed app is newer than it. Unicode true ManifestDPIAware true ; wayBetter: never show a wizard. @@ -111,6 +116,7 @@ Var ForceMode Var NoShortcutMode Var WixMode Var OldMainBinaryName +Var LegacyInstall Name "${PRODUCTNAME}" BrandingText "${COPYRIGHT}" @@ -330,10 +336,24 @@ Function .onInit ${EndIf} FunctionEnd +; wayBetter: $LegacyInstall = 1 when the install recorded in ${UNINSTKEY} was made by the app under +; its old name (its DisplayName is still ${LEGACYNAME}; this template writes ${PRODUCTNAME}), else 0. +; Such an install is older than this setup whatever its version number says. +!macro WaybetterLegacyInstall + StrCpy $LegacyInstall 0 + !ifdef LEGACYNAME + ReadRegStr $R6 SHCTX "${UNINSTKEY}" "DisplayName" + ${If} $R6 == "${LEGACYNAME}" + StrCpy $LegacyInstall 1 + ${EndIf} + !endif +!macroend + ; wayBetter: when the app is installed in $INSTDIR at this setup's version or a newer one, open it ; and quit with exit code 0: nothing is copied, no running app is closed, nothing is downgraded. ; Returns (and the install goes ahead) when nothing is installed, when the registry names an install -; whose exe is gone, when the installed version is older, or on /FORCE with the same version. +; whose exe is gone, when the installed version is older, when the install was made under the app's +; old name, or on /FORCE with the same version. Function OpenInstalledIfCurrent ; $R1 the installed exe's name, $R2 the installed version, $R3 this setup compared to it ReadRegStr $R1 SHCTX "${UNINSTKEY}" "MainBinaryName" @@ -344,6 +364,12 @@ Function OpenInstalledIfCurrent Return ${EndIf} + ; Installed under the old name: older, whatever its number (upgrade in place). + !insertmacro WaybetterLegacyInstall + ${If} $LegacyInstall = 1 + Return + ${EndIf} + ReadRegStr $R2 SHCTX "${UNINSTKEY}" "DisplayVersion" ${If} $R2 == "" ; No version in the registry: the exe's own file version, a.b.c.d -> a.b.c @@ -389,7 +415,10 @@ Section EarlyChecks ; If downgrading (wayBetter: there is no reinstall page to compare the versions, so here) StrCpy $R0 0 ReadRegStr $R2 SHCTX "${UNINSTKEY}" "DisplayVersion" + ; (An install made under the app's old name is never a downgrade target: it is older.) + !insertmacro WaybetterLegacyInstall ${If} $R2 != "" + ${AndIf} $LegacyInstall <> 1 nsis_tauri_utils::SemverCompare "${VERSION}" $R2 Pop $R0 ${EndIf} From 1b0a489b368564d6fc435587792d8f2506c04092 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 30 Sep 2026 23:24:04 +0700 Subject: [PATCH 26/72] waybetter release: builds of the committed state on a Mac over SSH and in WSL release macos --remote and release linux --wsl export HEAD plus each submodule at its recorded commit (git archive, never the working tree, nothing fetched from origin), build it path-free through build-env with unsigned bundles, bring the artifacts back and scan them here. release linux --appimage/--deb signs the AppImage (the Linux update payload) on the release machine and adds linux-x86_64 to latest.json. The remote script is low priority, never installs, quits or replaces an app on the Mac. Config: prepareCommand, exportExclude. Co-Authored-By: Claude Opus 5.5 --- packages/waybetter/bin/waybetter.mjs | 2 +- packages/waybetter/cli/release.mjs | 121 +++++++-- packages/waybetter/cli/remote.mjs | 256 +++++++++++++++++++ packages/waybetter/tests/remote-cli.test.mjs | 116 +++++++++ 4 files changed, 477 insertions(+), 18 deletions(-) create mode 100644 packages/waybetter/cli/remote.mjs create mode 100644 packages/waybetter/tests/remote-cli.test.mjs diff --git a/packages/waybetter/bin/waybetter.mjs b/packages/waybetter/bin/waybetter.mjs index 6d42ef9..aa6f353 100644 --- a/packages/waybetter/bin/waybetter.mjs +++ b/packages/waybetter/bin/waybetter.mjs @@ -1,6 +1,6 @@ #!/usr/bin/env node // The `waybetter` command: `waybetter store build|sign|verify` (cli/store.mjs), -// `waybetter release windows|macos` (cli/release.mjs), `waybetter i18n check|extract` +// `waybetter release windows|macos|linux` (cli/release.mjs), `waybetter i18n check|extract` // (cli/i18n.mjs), `waybetter privacy-scan` (cli/privacy.mjs) and `waybetter build-env` // (cli/buildenv.mjs), `waybetter dev` (cli/dev.mjs: watchers + tauri dev), `waybetter strings check` // (cli/strings.mjs). diff --git a/packages/waybetter/cli/release.mjs b/packages/waybetter/cli/release.mjs index 28c05fe..b70aff7 100644 --- a/packages/waybetter/cli/release.mjs +++ b/packages/waybetter/cli/release.mjs @@ -14,6 +14,8 @@ // "outDir": "releases", // releases/upload (files), releases/native/latest.json // "manifestValidator": { "module": "packages/contracts/dist/index.js", "export": "NativeRelease", // "hint": "build packages/contracts first" }, // optional, zod-like .parse +// "prepareCommand": "bun install --frozen-lockfile", // remote/WSL builds: runs first in the unpacked sources +// "exportExclude": ["verification"], // remote/WSL builds: app-repo paths left out of the upload // "forbiddenTerms": "~/.better-twttr-keys/forbidden-names.txt", // optional, outside the repo // "privacyAllowlist": "privacy-allowlist.txt" // optional, reviewed false positives // } @@ -34,6 +36,7 @@ import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; import { pathFreeBuildEnv } from './buildenv.mjs'; import { assertClean } from './privacy.mjs'; +import { buildLinuxWsl, buildMacRemote, scanBuilt } from './remote.mjs'; export const CONFIG_FILE = 'waybetter.release.json'; @@ -44,6 +47,19 @@ export const RELEASE_USAGE = `Usage: waybetter release macos --dmg --updater [--arch universal] [--config ] Signs the updater bundle of a universal macOS build here, copies both into /upload and adds darwin-aarch64 and darwin-x86_64 to latest.json (run the Windows step first). + waybetter release macos --remote [--ssh-key ] [--remote-dir ] [--build-only] + Builds the COMMITTED state (HEAD and the submodules at their recorded commits, exported with + git archive, never the working tree) on a Mac over SSH, universal and ad-hoc signed, without + a build path in it; brings the .dmg and .app.tar.gz to /build/macos, scans them here, + then (unless --build-only) continues as above. The built .app stays in the remote work + folder (/out); nothing is installed or replaced on the Mac. Env: WAYBETTER_MAC_SSH (user@host), WAYBETTER_MAC_SSH_KEY. + waybetter release linux --wsl [] [--remote-dir ] [--build-only] + Builds the committed state in WSL (default distro Ubuntu-22.04, or WAYBETTER_WSL_DISTRO): the + AppImage and the .deb in /build/linux, scanned here; then (unless --build-only) the + same as \`release linux --appimage\`. + waybetter release linux --appimage --deb [--config ] + Signs the AppImage (the Linux update payload) here, copies both into /upload and adds + linux-x86_64 to latest.json (run the Windows step first). Config: ${CONFIG_FILE} in the app's root (product, artifact, desktopDir, keysDir, keysDirEnv, cdnBase, apiBase, outDir, optional manifestValidator, forbiddenTerms, privacyAllowlist). Env: @@ -104,6 +120,8 @@ export function normalizeReleaseConfig(raw, root) { apiBase: url('apiBase'), outDir: at(text('outDir', 'releases')), buildCommand: text('buildCommand', 'bun run tauri build'), + prepareCommand: text('prepareCommand', 'bun install --frozen-lockfile'), + exportExclude: Array.isArray(raw.exportExclude) ? raw.exportExclude.map(String) : [], manifestValidator: validator && { module: at(validator.module), export: validator.export, hint: validator.hint }, forbiddenTerms: raw.forbiddenTerms === undefined ? undefined : at(home(text('forbiddenTerms'))), privacyAllowlist: raw.privacyAllowlist === undefined ? undefined : at(text('privacyAllowlist')), @@ -249,11 +267,39 @@ Nothing was uploaded. Run these steps yourself, in this order: return { version, manifestPath, files: [fileName, `${fileName}.sig`] }; } +/** Signs a copy in the upload folder (the signature's trusted comment names the file and binds the version). */ +function signFile(config, file, version, env) { + const key = keyPath(config, env); + if (!existsSync(key)) fail(`signing key not found at ${key}`); + const exe = process.platform === 'win32' ? 'tauri.exe' : 'tauri'; + const tauri = [join(config.desktopDir, 'node_modules', '.bin', exe), join(config.root, 'node_modules', '.bin', exe)].find(existsSync); + if (!tauri) fail('Tauri CLI not installed (bun install)'); + const signed = spawnSync(tauri, ['signer', 'sign', '-f', key, '-p', '', '--app-version', version, file], { + stdio: ['ignore', 'ignore', 'inherit'], // stdout would echo the signature; the .sig file holds it + }); + if (signed.status !== 0) fail(`tauri signer sign failed (exit ${signed.status})`); + const sigPath = `${file}.sig`; + if (!existsSync(sigPath)) fail(`signer wrote no ${sigPath}`); + return sigPath; +} + /** `waybetter release macos`: adds a universal macOS build (built unsigned on the Mac) to the release. */ export async function releaseMacos(config, args, { env = process.env, log = console.log } = {}) { const version = JSON.parse(readFileSync(join(config.root, 'package.json'), 'utf8')).version; - const dmg = option(args, '--dmg'); - const updater = option(args, '--updater'); + let dmg = option(args, '--dmg'); + let updater = option(args, '--updater'); + const target = option(args, '--remote') ?? (dmg ? undefined : env.WAYBETTER_MAC_SSH); + if (target) { + const built = buildMacRemote({ config, target, key: option(args, '--ssh-key') ?? env.WAYBETTER_MAC_SSH_KEY, remoteDir: option(args, '--remote-dir'), env, log }); + scanBuilt(config, [built.dmg, built.updater], { env, log }); + if (built.version !== version) fail(`the committed version is ${built.version} but the working tree says ${version}: commit or sync first`); + if (args.includes('--build-only')) { + log(`release-macos: built ${built.sha.slice(0, 12)} in ${relative(config.root, built.dir).replaceAll('\\', '/')} (scanned, not signed)`); + return { version, dir: built.dir, files: [built.dmg, built.updater] }; + } + dmg = built.dmg; + updater = built.updater; + } const arch = option(args, '--arch') ?? 'universal'; if (!dmg || !updater) fail('usage: --dmg --updater [--arch universal]'); if (arch !== 'universal') fail('only universal builds are supported (one file serves both darwin arches)'); @@ -268,18 +314,7 @@ export async function releaseMacos(config, args, { env = process.env, log = cons copyFileSync(dmg, join(uploadDir, dmgName)); copyFileSync(updater, join(uploadDir, updaterName)); - // Sign the copy (the signature's trusted comment names this file and binds the version). - const key = keyPath(config, env); - if (!existsSync(key)) fail(`signing key not found at ${key}`); - const exe = process.platform === 'win32' ? 'tauri.exe' : 'tauri'; - const tauri = [join(config.desktopDir, 'node_modules', '.bin', exe), join(config.root, 'node_modules', '.bin', exe)].find(existsSync); - if (!tauri) fail('Tauri CLI not installed (bun install)'); - const signed = spawnSync(tauri, ['signer', 'sign', '-f', key, '-p', '', '--app-version', version, join(uploadDir, updaterName)], { - stdio: ['ignore', 'ignore', 'inherit'], // stdout would echo the signature; the .sig file holds it - }); - if (signed.status !== 0) fail(`tauri signer sign failed (exit ${signed.status})`); - const sigPath = join(uploadDir, `${updaterName}.sig`); - if (!existsSync(sigPath)) fail(`signer wrote no ${sigPath}`); + const sigPath = signFile(config, join(uploadDir, updaterName), version, env); const manifestPath = join(config.outDir, 'native', 'latest.json'); if (!existsSync(manifestPath)) fail(`no ${relative(config.root, manifestPath)}: run \`waybetter release windows\` first`); @@ -301,14 +336,66 @@ then publish latest.json the same way (tmp file, then mv), and verify return { version, manifestPath, files: [dmgName, updaterName, `${updaterName}.sig`] }; } -/** `waybetter release ...` from the command line (or an app's wrapper script). */ +/** `waybetter release linux`: adds the AppImage (signed here: it is the update payload) and the .deb. */ +export async function releaseLinux(config, args, { env = process.env, log = console.log } = {}) { + const version = JSON.parse(readFileSync(join(config.root, 'package.json'), 'utf8')).version; + let appimage = option(args, '--appimage'); + let deb = option(args, '--deb'); + if (args.includes('--wsl')) { + const next = args[args.indexOf('--wsl') + 1]; + const distro = next && !next.startsWith('--') ? next : env.WAYBETTER_WSL_DISTRO; + const built = buildLinuxWsl({ config, distro, remoteDir: option(args, '--remote-dir'), env, log }); + scanBuilt(config, [built.appimage, built.deb], { env, log }); + if (built.version !== version) fail(`the committed version is ${built.version} but the working tree says ${version}: commit or sync first`); + if (args.includes('--build-only')) { + log(`release-linux: built ${built.sha.slice(0, 12)} in ${relative(config.root, built.dir).replaceAll('\\', '/')} (scanned, not signed)`); + return { version, dir: built.dir, files: [built.appimage, built.deb] }; + } + appimage = built.appimage; + deb = built.deb; + } + if (!appimage || !deb) fail('usage: --appimage --deb (or --wsl)'); + for (const file of [appimage, deb]) if (!existsSync(file)) fail(`not found: ${file}`); + if (!appimage.endsWith('.AppImage')) fail('--appimage must be the .AppImage Tauri wrote'); + if (!deb.endsWith('.deb')) fail('--deb must be the .deb Tauri wrote'); + gate(config, [resolve(appimage), resolve(deb)], env, log); + + const uploadDir = join(config.outDir, 'upload'); + mkdirSync(uploadDir, { recursive: true }); + const appimageName = `${config.artifact}_${version}_amd64.AppImage`; + const debName = `${config.artifact}_${version}_amd64.deb`; + copyFileSync(appimage, join(uploadDir, appimageName)); + copyFileSync(deb, join(uploadDir, debName)); + const sigPath = signFile(config, join(uploadDir, appimageName), version, env); + + const manifestPath = join(config.outDir, 'native', 'latest.json'); + if (!existsSync(manifestPath)) fail(`no ${relative(config.root, manifestPath)}: run \`waybetter release windows\` first`); + const current = JSON.parse(readFileSync(manifestPath, 'utf8')); + if (current.version !== version) fail(`latest.json is ${current.version}, this build is ${version}`); + const cdnBase = (env.CDN_BASE ?? config.cdnBase).replace(/\/+$/, ''); + const entry = { url: `${cdnBase}/${appimageName}`, signature: readFileSync(sigPath, 'utf8').trim() }; + const manifest = await validate(config, { ...current, platforms: { ...current.platforms, 'linux-x86_64': entry } }); + writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); + log(`release-linux: ${appimageName} (+ .sig), ${debName} in ${relative(config.root, uploadDir).replaceAll('\\', '/')}; latest.json now has ${Object.keys(manifest.platforms).join(', ')}`); + log(` +Nothing was uploaded. Upload the AppImage, its .sig and the .deb to the CDN next to the Windows +installer (same target and folder as \`waybetter release windows\` prints), check + curl -sSfI ${cdnBase}/${appimageName} +then publish latest.json the same way (tmp file, then mv), and verify + curl -sS ${config.apiBase}/v1/updates/linux/x86_64/0.0.0 +`); + return { version, manifestPath, files: [appimageName, `${appimageName}.sig`, debName] }; +} + +/** `waybetter release ...` from the command line (or an app's wrapper script). */ export async function releaseCommand(args, { cwd = process.cwd(), env = process.env, log = console.log } = {}) { const [platform, ...rest] = args; - if (platform !== 'windows' && platform !== 'macos') { + if (platform !== 'windows' && platform !== 'macos' && platform !== 'linux') { log(RELEASE_USAGE); if (platform && platform !== '--help' && platform !== '-h') fail(`unknown release target ${platform}`); return undefined; } const config = loadReleaseConfig(cwd, option(rest, '--config')); - return platform === 'windows' ? releaseWindows(config, rest, { env, log }) : releaseMacos(config, rest, { env, log }); + const release = { windows: releaseWindows, macos: releaseMacos, linux: releaseLinux }[platform]; + return release(config, rest, { env, log }); } diff --git a/packages/waybetter/cli/remote.mjs b/packages/waybetter/cli/remote.mjs new file mode 100644 index 0000000..06c23be --- /dev/null +++ b/packages/waybetter/cli/remote.mjs @@ -0,0 +1,256 @@ +// Remote and WSL builds for `waybetter release macos|linux`: the committed state of an app (its +// git HEAD plus every submodule at the commit the app records) is exported, sent to the machine +// that builds it, built there through `waybetter build-env` (no build path in the binary) and the +// artifacts come back to be scanned (`waybetter privacy-scan`) and, later, signed on this machine. +// Nothing here touches the working tree the developer has open, and no key ever leaves this +// machine: the remote build is unsigned (updater artifacts off), signing is `waybetter release`. +// +// The export is `git archive` of the app at HEAD plus `git archive` of each submodule at the commit +// HEAD points to, read from the local submodule repository. A submodule's newest commits do not +// have to be on any remote, so nothing is ever fetched from origin. +// +// Where it builds is never written down here: an SSH target (user@host, WAYBETTER_MAC_SSH or +// --remote), its key (WAYBETTER_MAC_SSH_KEY or --ssh-key) and a WSL distro (--wsl, +// WAYBETTER_WSL_DISTRO) come from the caller. The remote scripts use a login shell (macOS: bun, +// cargo and node exist only there) and a clean PATH (WSL: no Windows programs shadowing the +// Linux ones). +import { spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { basename, join, relative, resolve } from 'node:path'; +import { assertClean } from './privacy.mjs'; + +class RemoteError extends Error {} +const fail = message => { throw new RemoteError(message); }; + +/** Single-quotes a value for a POSIX shell. */ +export const shq = value => `'${String(value).replaceAll("'", `'\\''`)}'`; + +function run(command, args, options = {}) { + const result = spawnSync(command, args, { encoding: 'utf8', windowsHide: true, maxBuffer: 1 << 28, ...options }); + if (result.error) fail(`${command}: ${result.error.message}`); + return result; +} + +function git(root, args, options) { + const result = run('git', ['-C', root, ...args], options); + if (result.status !== 0) fail(`git ${args[0]} failed: ${(result.stderr || '').trim().split('\n')[0]}`); + return result.stdout ?? ''; +} + +/** A file of the committed state (`git show HEAD:`), for the version and product name. */ +export const committedFile = (root, path) => git(root, ['show', `HEAD:${path}`]); + +/** The submodules HEAD records: [{ path, sha }]. */ +export function committedSubmodules(root) { + return git(root, ['ls-tree', '-r', 'HEAD']) + .split('\n') + .map(line => /^160000 commit ([0-9a-f]{40})\t(.+)$/.exec(line)) + .filter(Boolean) + .map(([, sha, path]) => ({ path, sha })); +} + +/** + * Exports the committed state of `root` (HEAD, and each submodule at its recorded commit) to a + * `.tar.gz` at `file`. Returns `{ sha, submodules, file, bytes, dirty }`; `dirty` lists tracked + * files changed in the working tree, which the export ignores by design. + */ +export function exportCommitted({ root, file, exclude = [], log = () => {} }) { + const sha = git(root, ['rev-parse', 'HEAD']).trim(); + const submodules = committedSubmodules(root); + const dirty = git(root, ['status', '--porcelain', '--untracked-files=no']).split('\n').filter(Boolean).length; + const staging = mkdtempSync(join(tmpdir(), 'wb-export-')); + try { + const parts = [{ repo: root, ref: 'HEAD', prefix: '' }, ...submodules.map(({ path, sha: ref }) => ({ repo: join(root, path), ref, prefix: `${path}/`, path }))]; + for (const [index, part] of parts.entries()) { + if (part.path && !existsSync(join(part.repo, '.git'))) fail(`submodule ${part.path} is not checked out here (needed for commit ${part.ref.slice(0, 12)})`); + const tarName = `part-${index}.tar`; + // `exclude` (paths of the app repo the build never reads, e.g. screenshots) keeps the upload small. + const skip = part.path ? [] : ['--', '.', ...exclude.map(path => `:(exclude)${path}`)]; + const args = ['archive', '--format=tar', ...(part.prefix ? [`--prefix=${part.prefix}`] : []), '-o', join(staging, tarName), part.ref, ...skip]; + const archived = run('git', ['-C', part.repo, ...args]); + if (archived.status !== 0) fail(`git archive ${part.path ?? 'app'} at ${part.ref.slice(0, 12)} failed: ${(archived.stderr || '').trim().split('\n')[0]} (is that commit in the local repository?)`); + // Relative names and cwd: a drive letter in an argument reads as a remote host to GNU tar. + mkdirSync(join(staging, 'tree'), { recursive: true }); + const unpacked = run('tar', ['-xf', tarName, '-C', 'tree'], { cwd: staging }); + if (unpacked.status !== 0) fail(`tar -x failed: ${(unpacked.stderr || '').trim().split('\n')[0]}`); + rmSync(join(staging, tarName)); + } + mkdirSync(resolve(file, '..'), { recursive: true }); + const outName = 'export.tgz'; + const packed = run('tar', ['-czf', outName, '-C', 'tree', '.'], { cwd: staging }); + if (packed.status !== 0) fail(`tar -c failed: ${(packed.stderr || '').trim().split('\n')[0]}`); + writeFileSync(file, readFileSync(join(staging, outName))); + } finally { + rmSync(staging, { recursive: true, force: true }); + } + const bytes = statSync(file).size; + log(`export: ${sha.slice(0, 12)}${submodules.map(s => ` + ${s.path}@${s.sha.slice(0, 12)}`).join('')} -> ${(bytes / 1048576).toFixed(1)} MB${dirty ? ` (${dirty} tracked file(s) changed in the working tree are NOT included)` : ''}`); + return { sha, submodules, file, bytes, dirty }; +} + +/** Remote work folders are relative to the login home. */ +const workDirOf = (dir, artifact) => (dir ?? `waybetter-builds/${artifact}`).replace(/^~\//, '').replace(/^\/+/, '') || `waybetter-builds/${artifact}`; +const sha256Line = 'if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$@"; else sha256sum "$@"; fi'; + +/** + * The macOS build script (bash, run in a login shell on the Mac): unpack, install, universal + * ad-hoc-signed .app and .dmg through build-env, the updater bundle as a tar.gz of the .app; the + * dmg and the tar.gz under space-free names, and the .app itself, in `out/`. It never installs, + * quits or replaces an app on the Mac: whoever runs the app there swaps it in. + */ +export function macBuildScript({ workDir, sha, artifact, productName, version, desktopDir, prepareCommand }) { + const app = `${productName}.app`; + return `#!/bin/bash +set -eu +# Low priority: the Mac may be recording or running an app while this compiles. +renice -n 10 $$ >/dev/null 2>&1 || true +# rustup first: Homebrew's Rust has no x86_64 standard library, which a universal build needs. +export PATH="$HOME/.cargo/bin:$PATH" +WORK="$HOME/${workDir}" +SRC="$WORK/src" +OUT="$WORK/out" +cd "$WORK" +rm -rf "$SRC" "$OUT" +mkdir -p "$SRC" "$OUT" +tar -xzf "$WORK/source-${sha.slice(0, 12)}.tgz" -C "$SRC" +cd "$SRC" +rustup target add aarch64-apple-darwin x86_64-apple-darwin +${prepareCommand} +cd ${shq(desktopDir)} +# Ad-hoc signature (no Developer ID yet: Gatekeeper's "Open Anyway" path, not "is damaged"), no +# updater bundle from Tauri (it needs the signing key, which never leaves the release machine). +printf '%s' '{"bundle":{"createUpdaterArtifacts":false,"macOS":{"signingIdentity":"-"}}}' > "$WORK/override.json" +export CARGO_TARGET_DIR="$WORK/target" +bun "$SRC/waybetter/packages/waybetter/bin/waybetter.mjs" build-env -- bunx tauri build --target universal-apple-darwin --bundles app,dmg --ci --config "$WORK/override.json" +BUNDLE="$CARGO_TARGET_DIR/universal-apple-darwin/release/bundle" +DMG="$(ls "$BUNDLE"/dmg/*_${version}_universal.dmg | head -1)" +cp "$DMG" "$OUT/${artifact}_${version}_universal.dmg" +COPYFILE_DISABLE=1 tar -czf "$OUT/${artifact}_${version}_universal.app.tar.gz" -C "$BUNDLE/macos" ${shq(app)} +ditto "$BUNDLE/macos/"${shq(app)} "$OUT/"${shq(app)} +cd "$OUT" +set -- *.dmg *.tar.gz +${sha256Line} > SHA256SUMS +ls -l "$OUT" +echo "REMOTE_BUILD_OK ${sha.slice(0, 12)}" +`; +} + +/** + * The Linux build script (bash, run in WSL or on any Ubuntu 22.04): clean PATH, unpack, install, + * AppImage and .deb through build-env with Tauri's updater bundle off (on Linux the signed + * AppImage itself is the update payload), copied to `out/` under space-free names. + */ +export function linuxBuildScript({ workDir, sha, artifact, version, desktopDir, prepareCommand, tarball, outDir }) { + return `#!/bin/bash +set -eu +# A clean PATH: under WSL the Windows programs (a Windows bun, node, cargo) would shadow these. +export PATH="$HOME/.bun/bin:$HOME/.cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +export APPIMAGE_EXTRACT_AND_RUN=1 +WORK="$HOME/${workDir}" +SRC="$WORK/src" +cd "$HOME" +mkdir -p "$WORK" +rm -rf "$SRC" +mkdir -p "$SRC" +tar -xzf "$(wslpath -u ${shq(tarball)} 2>/dev/null || echo ${shq(tarball)})" -C "$SRC" +cd "$SRC" +${prepareCommand} +cd ${shq(desktopDir)} +printf '%s' '{"bundle":{"createUpdaterArtifacts":false}}' > "$WORK/override.json" +export CARGO_TARGET_DIR="$WORK/target" +bun "$SRC/waybetter/packages/waybetter/bin/waybetter.mjs" build-env -- bunx tauri build --bundles appimage,deb --ci --config "$WORK/override.json" +BUNDLE="$CARGO_TARGET_DIR/release/bundle" +OUTDIR="$(wslpath -u ${shq(outDir)} 2>/dev/null || echo ${shq(outDir)})" +mkdir -p "$OUTDIR" +cp "$(ls "$BUNDLE"/appimage/*_${version}_amd64.AppImage | head -1)" "$OUTDIR/${artifact}_${version}_amd64.AppImage" +cp "$(ls "$BUNDLE"/deb/*_${version}_amd64.deb | head -1)" "$OUTDIR/${artifact}_${version}_amd64.deb" +ls -l "$OUTDIR" +echo "REMOTE_BUILD_OK ${sha.slice(0, 12)}" +`; +} + +const sshOptions = ({ key }) => ['-o', 'BatchMode=yes', '-o', 'IdentitiesOnly=yes', '-o', 'ConnectTimeout=15', '-o', 'ServerAliveInterval=30', ...(key ? ['-i', key] : [])]; + +/** Runs a command and streams its output; the exit code decides. */ +function stream(command, args, { log, label }) { + log(`${label}: ${command} ${args.map(a => (/\s/.test(a) ? '"…"' : a)).join(' ').slice(0, 160)}`); + const result = spawnSync(command, args, { stdio: 'inherit', windowsHide: true }); + if (result.error) fail(`${command}: ${result.error.message}`); + if (result.status !== 0) fail(`${label} failed (exit ${result.status})`); +} + +/** + * Builds the committed state of the app on a Mac over SSH and brings the .dmg and the .app.tar.gz + * back to `/build/macos`. Returns `{ version, sha, dir, dmg, updater }`. + */ +export function buildMacRemote({ config, target, key, remoteDir, env = process.env, log = console.log }) { + if (!target || !/^[A-Za-z0-9._-]+@[A-Za-z0-9._:-]+$/.test(target)) fail('a Mac needs --remote user@host (or WAYBETTER_MAC_SSH)'); + const { root } = config; + const version = JSON.parse(committedFile(root, 'package.json')).version; + const productName = JSON.parse(committedFile(root, relTauri(config, 'tauri.conf.json'))).productName; + const workDir = workDirOf(remoteDir, config.artifact); + const dir = join(config.outDir, 'build', 'macos'); + mkdirSync(dir, { recursive: true }); + for (const name of readdirSync(dir)) rmSync(join(dir, name), { force: true, recursive: true }); + const scratch = mkdtempSync(join(tmpdir(), 'wb-mac-')); + try { + const exported = exportCommitted({ root, file: join(scratch, 'source.tgz'), exclude: config.exportExclude, log }); + const short = exported.sha.slice(0, 12); + const script = macBuildScript({ workDir, sha: exported.sha, artifact: config.artifact, productName, version, desktopDir: relative(root, config.desktopDir).replaceAll('\\', '/'), prepareCommand: config.prepareCommand }); + writeFileSync(join(scratch, 'build.sh'), script.replaceAll('\r\n', '\n')); + const ssh = sshOptions({ key }); + stream('ssh', [...ssh, target, `mkdir -p "$HOME/${workDir}" && find "$HOME/${workDir}" -maxdepth 1 -name 'source-*.tgz' -delete`], { log, label: 'mac: prepare' }); + stream('scp', [...ssh, join(scratch, 'source.tgz'), `${target}:${workDir}/source-${short}.tgz`], { log, label: 'mac: upload' }); + stream('scp', [...ssh, join(scratch, 'build.sh'), `${target}:${workDir}/build.sh`], { log, label: 'mac: upload script' }); + const started = Date.now(); + // A login shell: bun, cargo and node are set up in the Mac account's profile only. + stream('ssh', [...ssh, target, `zsh -lic "bash $HOME/${workDir}/build.sh"`], { log, label: 'mac: build' }); + log(`mac: build took ${Math.round((Date.now() - started) / 1000)} s`); + stream('scp', [...ssh, `${target}:${workDir}/out/${config.artifact}_${version}_universal.dmg`, `${target}:${workDir}/out/${config.artifact}_${version}_universal.app.tar.gz`, dir], { log, label: 'mac: fetch' }); + return { version, sha: exported.sha, dir, dmg: join(dir, `${config.artifact}_${version}_universal.dmg`), updater: join(dir, `${config.artifact}_${version}_universal.app.tar.gz`) }; + } finally { + rmSync(scratch, { recursive: true, force: true }); + } +} + +/** + * Builds the committed state of the app in a WSL distro (Ubuntu 22.04: the glibc floor) and puts + * the AppImage and the .deb in `/build/linux`. Returns `{ version, sha, dir, appimage, deb }`. + */ +export function buildLinuxWsl({ config, distro = 'Ubuntu-22.04', remoteDir, env = process.env, log = console.log }) { + if (process.platform !== 'win32') fail('--wsl runs from Windows; on Linux run the build on the machine itself'); + if (!/^[A-Za-z0-9._-]+$/.test(distro)) fail('bad WSL distro name'); + const { root } = config; + const version = JSON.parse(committedFile(root, 'package.json')).version; + const workDir = workDirOf(remoteDir, config.artifact); + const dir = join(config.outDir, 'build', 'linux'); + mkdirSync(dir, { recursive: true }); + for (const name of readdirSync(dir)) rmSync(join(dir, name), { force: true, recursive: true }); + const scratch = mkdtempSync(join(tmpdir(), 'wb-linux-')); + try { + const exported = exportCommitted({ root, file: join(scratch, 'source.tgz'), exclude: config.exportExclude, log }); + const script = linuxBuildScript({ workDir, sha: exported.sha, artifact: config.artifact, version, desktopDir: relative(root, config.desktopDir).replaceAll('\\', '/'), prepareCommand: config.prepareCommand, tarball: join(scratch, 'source.tgz'), outDir: dir }); + writeFileSync(join(scratch, 'build.sh'), script.replaceAll('\r\n', '\n')); + const started = Date.now(); + // MSYS_NO_PATHCONV: Git Bash must not rewrite the /mnt paths of the script. + const wslScript = `/mnt/${scratch[0].toLowerCase()}/${scratch.slice(3).replaceAll('\\', '/')}/build.sh`; + const result = spawnSync('wsl', ['-d', distro, '--', 'bash', wslScript], { stdio: 'inherit', windowsHide: true, env: { ...env, MSYS_NO_PATHCONV: '1' } }); + if (result.status !== 0) fail(`linux build in WSL ${distro} failed (exit ${result.status})`); + log(`linux: build took ${Math.round((Date.now() - started) / 1000)} s`); + return { version, sha: exported.sha, dir, appimage: join(dir, `${config.artifact}_${version}_amd64.AppImage`), deb: join(dir, `${config.artifact}_${version}_amd64.deb`) }; + } finally { + rmSync(scratch, { recursive: true, force: true }); + } +} + +const relTauri = (config, name) => `${relative(config.root, config.tauriDir).replaceAll('\\', '/')}/${name}`; + +/** Scans built artifacts here (the terms never leave this machine) and prints their sizes. */ +export function scanBuilt(config, files, { env = process.env, log = console.log } = {}) { + for (const file of files) { + if (!existsSync(file)) fail(`expected build output missing: ${file}`); + log(`built: ${basename(file)} ${(statSync(file).size / 1048576).toFixed(1)} MB`); + } + assertClean(files, { terms: config.forbiddenTerms, allowlist: config.privacyAllowlist, cwd: config.root, env, log, label: 'release: privacy-scan' }); +} diff --git a/packages/waybetter/tests/remote-cli.test.mjs b/packages/waybetter/tests/remote-cli.test.mjs new file mode 100644 index 0000000..83f5104 --- /dev/null +++ b/packages/waybetter/tests/remote-cli.test.mjs @@ -0,0 +1,116 @@ +// Remote and WSL builds: the export of the committed state and the scripts that build it. +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { committedSubmodules, exportCommitted, linuxBuildScript, macBuildScript, shq } from '../cli/remote.mjs'; +import { releaseCommand } from '../cli/release.mjs'; + +const git = (cwd, ...args) => execFileSync('git', ['-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=NUL', '-c', 'user.name=t', '-c', 'user.email=t@example.test', '-c', 'protocol.file.allow=always', ...args], { cwd, encoding: 'utf8', stdio: 'pipe' }).trim(); + +/** An app repo with a submodule whose recorded commit is NOT the submodule's newest one. */ +function repo() { + const root = mkdtempSync(join(tmpdir(), 'wb-remote-')); + const sub = join(root, 'fw'); + mkdirSync(sub); + git(sub, 'init', '-q'); + writeFileSync(join(sub, 'lib.txt'), 'framework at the pointer\n'); + git(sub, 'add', '.'); + git(sub, 'commit', '-q', '-m', 'one'); + const pointer = git(sub, 'rev-parse', 'HEAD'); + git(root, 'init', '-q'); + writeFileSync(join(root, 'app.txt'), 'committed app\n'); + writeFileSync(join(root, 'big.txt'), 'left out\n'); + mkdirSync(join(root, 'shots')); + writeFileSync(join(root, 'shots', 'a.png'), 'png'); + git(root, 'add', 'app.txt', 'big.txt', 'shots'); + git(root, 'update-index', '--add', '--cacheinfo', `160000,${pointer},fw`); + git(root, 'commit', '-q', '-m', 'app'); + // Work after the commit: none of it may reach the export. + writeFileSync(join(sub, 'lib.txt'), 'framework NEWER, uncommitted\n'); + writeFileSync(join(sub, 'later.txt'), 'later commit\n'); + git(sub, 'add', '.'); + git(sub, 'commit', '-q', '-m', 'two'); + writeFileSync(join(root, 'app.txt'), 'edited in the working tree\n'); + writeFileSync(join(root, 'untracked.txt'), 'x'); + return { root, pointer }; +} + +const list = file => execFileSync('tar', ['-tzf', 'x.tgz'], { cwd: join(file, '..'), encoding: 'utf8' }).split('\n').map(line => line.replace(/^\.\//, '')).filter(Boolean); +const extract = (file, path) => execFileSync('tar', ['-xzOf', 'x.tgz', `./${path}`], { cwd: join(file, '..'), encoding: 'utf8' }); + +test('export: HEAD and the submodule at its recorded commit, never the working tree, nothing from origin', () => { + const { root, pointer } = repo(); + assert.deepEqual(committedSubmodules(root), [{ path: 'fw', sha: pointer }]); + const file = join(root, '..', `x-${Date.now()}`, 'x.tgz'); + const logs = []; + const out = exportCommitted({ root, file, log: line => logs.push(line) }); + assert.ok(out.dirty >= 1); + assert.match(logs[0], /\d+ tracked file\(s\) changed in the working tree are NOT included/); + const names = list(file); + assert.ok(names.includes('app.txt') && names.includes('fw/lib.txt')); + assert.ok(!names.includes('untracked.txt') && !names.includes('fw/later.txt')); + assert.equal(extract(file, 'app.txt'), 'committed app\n'); + assert.equal(extract(file, 'fw/lib.txt'), 'framework at the pointer\n'); +}); + +test('export: excluded paths stay out of the upload', () => { + const { root } = repo(); + const file = join(root, '..', `x-${Date.now()}-b`, 'x.tgz'); + exportCommitted({ root, file, exclude: ['shots'] }); + const names = list(file); + assert.ok(names.includes('big.txt')); + assert.ok(!names.some(name => name.startsWith('shots'))); +}); + +test('export: a submodule commit missing locally is an error that says so', () => { + const { root } = repo(); + git(root, 'update-index', '--cacheinfo', `160000,${'1'.repeat(40)},fw`); + git(root, 'commit', '-q', '-m', 'bad pointer'); + assert.throws(() => exportCommitted({ root, file: join(root, '..', `x-${Date.now()}-c`, 'x.tgz') }), /local repository/); +}); + +const MAC = { workDir: 'waybetter-builds/App', sha: 'abcdef0123456789abcdef0123456789abcdef01', artifact: 'App', productName: 'My App', version: '1.2.3', desktopDir: 'apps/desktop', prepareCommand: 'bun install --frozen-lockfile' }; + +test('mac script: rustup first, ad-hoc universal build through build-env, updater bundle off, artifacts named', () => { + const script = macBuildScript(MAC); + assert.match(script, /export PATH="\$HOME\/\.cargo\/bin:\$PATH"/); + assert.match(script, /renice -n 10/); + assert.match(script, /rustup target add aarch64-apple-darwin x86_64-apple-darwin/); + assert.match(script, /waybetter\.mjs" build-env -- bunx tauri build --target universal-apple-darwin --bundles app,dmg --ci/); + assert.match(script, /"createUpdaterArtifacts":false/); + assert.match(script, /source-abcdef012345\.tgz/); + assert.match(script, /App_1\.2\.3_universal\.dmg/); + assert.match(script, /COPYFILE_DISABLE=1 tar -czf "\$OUT\/App_1\.2\.3_universal\.app\.tar\.gz" -C "\$BUNDLE\/macos" 'My App\.app'/); + assert.ok(script.includes('ditto "$BUNDLE/macos/"\'My App.app\' "$OUT/"\'My App.app\'')); + assert.doesNotMatch(script, /pkill|Applications|osascript/); + assert.doesNotMatch(script, /TAURI_SIGNING_PRIVATE_KEY/); +}); + +test('linux script: clean PATH (no Windows programs), AppImage and deb through build-env', () => { + const script = linuxBuildScript({ ...MAC, tarball: 'C:\\t\\source.tgz', outDir: 'C:\\o\\linux' }); + assert.match(script, /export PATH="\$HOME\/\.bun\/bin:\$HOME\/\.cargo\/bin:\/usr\/local\/sbin/); + assert.doesNotMatch(script, /\/mnt\/c/); + assert.match(script, /--bundles appimage,deb --ci/); + assert.match(script, /App_1\.2\.3_amd64\.AppImage/); + assert.match(script, /wslpath -u 'C:\\t\\source\.tgz'/); +}); + +test('shq quotes single quotes', () => { + assert.equal(shq("it's"), `'it'\\''s'`); +}); + +test('linux release: usage errors and the missing-manifest order', async () => { + const root = mkdtempSync(join(tmpdir(), 'wb-linux-')); + const tauri = join(root, 'apps/desktop/src-tauri'); + mkdirSync(tauri, { recursive: true }); + writeFileSync(join(root, 'waybetter.release.json'), JSON.stringify({ product: 'P', artifact: 'P', desktopDir: 'apps/desktop', keysDir: 'nokeys', cdnBase: 'https://c.example.test', apiBase: 'https://a.example.test' })); + writeFileSync(join(root, 'package.json'), JSON.stringify({ version: '1.0.0' })); + await assert.rejects(releaseCommand(['linux'], { cwd: root, log: () => {} }), /usage: --appimage/); + writeFileSync(join(root, 'a.AppImage'), 'x'); + writeFileSync(join(root, 'a.zip'), 'x'); + await assert.rejects(releaseCommand(['linux', '--appimage', join(root, 'a.AppImage'), '--deb', join(root, 'a.zip')], { cwd: root, log: () => {} }), /\.deb/); + assert.ok(!existsSync(join(root, 'releases'))); +}); From 7c683598a40f1ecc9c53d2112ee214fa3d562cd8 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 30 Sep 2026 23:25:13 +0700 Subject: [PATCH 27/72] Report a problem: a diagnostic summary with no personal data, shown as it would be shared, with Copy and the issue page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The app menu's "Report a problem…" opens a small dialog with the summary (reportModel.ts, English on purpose: the people who read reports do): the app and framework versions, the system and webview (coarse, from the user agent), the language and how it was chosen, the mode, the theme and icon pack ids, the file names of the plugins that are on, what paused itself (the panel's `reportDetails`), and safe mode. The model has no field for an account, a handle, an address, a tab or a path, and a value that is not made of id characters is left out rather than trimmed into shape, so nothing of that kind can ride along (tested with hostile input). The dialog sends nothing: Copy puts the text on the clipboard, and "Open the issue page" opens `ShellSite.menu.report.issueUrl` bare in the system browser (the summary is never put in a URL). Without an issue page the button is off and the dialog says so. Co-Authored-By: Claude Opus 5.5 --- packages/shell/src/frame/AppMenu.tsx | 4 + packages/shell/src/frame/ReportDialog.tsx | 102 ++++++++++++++ packages/shell/src/frame/appMenu.css | 17 +++ packages/shell/src/frame/icons.tsx | 1 + packages/shell/src/frame/index.ts | 2 +- packages/shell/src/frame/menuMessages.en.json | 7 +- packages/shell/src/frame/menuModel.ts | 14 +- packages/shell/src/frame/reportModel.ts | 126 ++++++++++++++++++ packages/shell/src/panel/PluginFeatures.tsx | 9 ++ packages/shell/src/panel/index.ts | 2 +- packages/shell/tests/menu.test.ts | 8 +- packages/shell/tests/report.test.ts | 113 ++++++++++++++++ 12 files changed, 396 insertions(+), 9 deletions(-) create mode 100644 packages/shell/src/frame/ReportDialog.tsx create mode 100644 packages/shell/src/frame/reportModel.ts create mode 100644 packages/shell/tests/report.test.ts diff --git a/packages/shell/src/frame/AppMenu.tsx b/packages/shell/src/frame/AppMenu.tsx index 734cfe6..509a74b 100644 --- a/packages/shell/src/frame/AppMenu.tsx +++ b/packages/shell/src/frame/AppMenu.tsx @@ -24,6 +24,7 @@ import { DEFAULT_MENU, ZOOM_MAX, ZOOM_MIN, findSpec, joinGroups, languageChoice, languageRows, menuText, moveStop, planMenu, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, updateRow, type BuiltinMenuItem, type MenuEnv, type MenuItemRow, type MenuRow, } from './menuModel.ts'; +import { ReportDialog } from './ReportDialog.tsx'; import { safe, setSafeMode } from './safeStore.ts'; import { hasFeature, site } from './site.ts'; import { isWeb, setOverlay, shell, type TabParams } from './state.ts'; @@ -81,6 +82,7 @@ export function AppMenu() { const [version, setVersion] = useState(''); const [update, setUpdate] = useState({ state: 'idle' }); const [askedUpdate, setAskedUpdate] = useState(false); + const [reporting, setReporting] = useState(false); const [error, setError] = useState(''); const [, tick] = useReducer((n: number) => n + 1, 0); const button = useRef(null); @@ -306,6 +308,7 @@ export function AppMenu() { case 'safe-mode': return safe.active ? item(id, menuText('safeLeave'), 'shield', { run: () => setSafeMode(false) }) : item(id, menuText('safeRestart'), 'shield', { submenu: true }); + case 'report': return item(id, menuText('report'), 'flag', { run: () => setReporting(true) }); case 'about': return item(id, menuText('about', { product: config.product }), 'info', { run: () => shell.openPanelSection('home') }); case 'settings': return item(id, section(t('wb.panel.section.settings')), 'settings', { run: () => shell.openPanelSection('settings') }); } @@ -523,6 +526,7 @@ export function AppMenu() { {renderMenus()} , document.body)} + {reporting && setReporting(false)}/>} ; } diff --git a/packages/shell/src/frame/ReportDialog.tsx b/packages/shell/src/frame/ReportDialog.tsx new file mode 100644 index 0000000..2ccf796 --- /dev/null +++ b/packages/shell/src/frame/ReportDialog.tsx @@ -0,0 +1,102 @@ +// "Report a problem": a small dialog that shows the diagnostic summary (reportModel.ts) exactly as +// it would be shared, with Copy and a button that opens the project's new-issue page in the system +// browser. The app sends nothing itself: no request, and the summary is never put in a URL (the +// issue page opens bare; the owner pastes what they copied). Without a configured issue page the +// button is off and says why. + +import { useEffect, useRef, useState } from 'react'; +import { createPortal } from 'react-dom'; +import { invoke } from './bridge.ts'; +import { useT } from './hooks.ts'; +import { textLocale } from './i18n.ts'; +import { Icon } from './icons.tsx'; +import { menuText } from './menuModel.ts'; +import { buildReport, systemFromUserAgent, webviewFromUserAgent, type ReportInfo } from './reportModel.ts'; +import { safe } from './safeStore.ts'; +import { site } from './site.ts'; +import { setOverlay } from './state.ts'; + +type Hints = { platformVersion?: string; architecture?: string; bitness?: string }; + +/** What the engine says about the system when asked (Chromium webviews; others have the user agent only). */ +async function systemHints(): Promise { + try { + const data = (navigator as Navigator & { userAgentData?: { getHighEntropyValues(hints: string[]): Promise } }).userAgentData; + return data ? await data.getHighEntropyValues(['platformVersion', 'architecture', 'bitness']) : {}; + } catch { return {}; } +} + +/** Gathers the facts a report may say: from the app's config and the shell's own state, nothing about the person. */ +async function collect(): Promise { + const config = site(); + const menu = config.menu ?? {}; + const themes = config.themes; + const [appVersion, hints, mode, plugins, details] = await Promise.all([ + menu.version ? menu.version().catch(() => '') : Promise.resolve(''), + systemHints(), + menu.modes ? menu.modes.current().catch(() => null) : Promise.resolve(undefined), + invoke>('plugins_list').then(list => list.filter(plugin => plugin.enabled === true).map(plugin => String(plugin.file ?? '')), () => null), + menu.report?.details ? Promise.resolve(menu.report.details()).catch(() => []) : Promise.resolve([]), + ]); + if (themes) await themes.loadThemes().catch(() => {}); + const choice = themes?.current().choice; + const theme = themes ? themes.adapter.resolve(choice) as { id?: unknown; icons?: { pack?: unknown } } : null; + return { + product: config.product, + appVersion, + system: systemFromUserAgent(navigator.userAgent, hints), + webview: webviewFromUserAgent(navigator.userAgent), + language: menu.languages?.state().locale ?? textLocale(), + languageChoice: menu.languages?.state().preference ?? 'fixed', + mode, + theme: themes ? themes.adapter.preset(choice) : undefined, + iconPack: theme ? (typeof theme.icons?.pack === 'string' ? theme.icons.pack : '') : undefined, + plugins, + details, + safeMode: safe.active, + }; +} + +export function ReportDialog({ onClose }: { onClose(): void }) { + const t = useT(); + const [text, setText] = useState(null); + const [copied, setCopied] = useState(false); + const dialog = useRef(null); + const issueUrl = site().menu?.report?.issueUrl; + const canOpen = typeof issueUrl === 'string' && /^https:\/\//.test(issueUrl); + + useEffect(() => { + setOverlay(1); + invoke('shell_focus').catch(() => {}); + let live = true; + collect().then(info => { if (live) setText(buildReport(info)); }, () => { if (live) setText(''); }); + dialog.current?.focus(); + return () => { live = false; setOverlay(-1); }; + }, []); + + const copy = async () => { + if (!text) return; + try { await navigator.clipboard.writeText(text); setCopied(true); setTimeout(() => setCopied(false), 2200); } + catch { dialog.current?.querySelector('textarea')?.select(); } + }; + + return createPortal(
+
event.stopPropagation()} onKeyDown={event => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); onClose(); } }}> +
+

{menuText('reportTitle')}

+ +
+

{menuText('reportLede')}

+