diff --git a/README.md b/README.md index 533cfa3..62a9419 100644 --- a/README.md +++ b/README.md @@ -1,56 +1,290 @@ # waybetter -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. +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 # page runtime, shell, CLI tools -npm create waybetter # scaffold a plugin, a theme or a whole app +npm install waybetter ``` -Links: [source](https://git.crt.fyi/CRT/waybetter) · [npm](https://www.npmjs.com/package/waybetter) · [waybetter.fyi](https://waybetter.fyi) +[npm](https://www.npmjs.com/package/waybetter) · [waybetter.fyi](https://waybetter.fyi) -## The three layers +A wayBetter app is one native window (Tauri 2, multiwebview) with: -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. +- 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. -| Layer | Where | What it does | +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 | | --- | --- | --- | -| 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). | +| [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. | -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). +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. -## A minimal adapter +## Build your own -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). +```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 +``` -**1. Native: which webviews are site tabs, and what an account looks like** (`src-tauri/src/site.rs`) +`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 + 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}; -pub fn valid_handle(handle: &str) -> bool { - (3..=25).contains(&handle.len()) && handle.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') +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): the only definition of a site tab - runtime_global: "WayBetterForKick", // window. of the page runtime + hosts: &["kick.com"], // exact https origin(s) of site tabs + runtime_global: "WayBetterKick", // window. of the page runtime accounts: AccountRules { - valid_handle, + valid_handle: kick_handle, avatar_prefixes: &["https://files.kick.com/"], max_name_chars: 50, max_avatar_len: 512, @@ -58,149 +292,240 @@ pub static SITE: SiteSpec = SiteSpec { }; ``` -**2. Page: what the runtime needs to know about the markup** (`src/site.ts`, shortened) +`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 type { SiteAdapter } from 'waybetter/runtime/site'; +import { configureRuntime, type SiteAdapter } from 'waybetter/packages/runtime/src/site.ts'; -export const SITE: SiteAdapter = { +export const KICK: SiteAdapter = { product: 'wayBetter for Kick', hosts: ['kick.com'], - runtimeGlobal: 'WayBetterForKick', - heavyPath: null, - apiMarks: ['/api/'], // request URLs the net hub may inspect + runtimeGlobal: 'WayBetterKick', + heavyPath: null, // pages where offOnHeavy DOM features pause + apiMarks: ['/api/'], // request URLs the net hub stages may see xhrMarks: [], - plugins: { name: 'WayBetterForKick', product: 'wayBetter for Kick', storagePrefix: 'wb-kick-plugin:', - styleDataKey: 'wbKickPlugin', toastId: 'wb-kick-ui', toastBackground: '#53fc18', + plugins: { name: 'WayBetterKick', product: 'wayBetter for Kick', storagePrefix: 'wbk-plugin:', + styleDataKey: 'wbkPlugin', toastId: 'wbk-toast', toastBackground: '#53fc18', itemSelector: '[data-chat-entry]', chordKeys: [] }, - account: { read: readAccount, signedOut: root => !!root.querySelector('button[data-testid="login"]') }, - links: { configKey: 'site', clickedUrl }, + 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); ``` -**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: +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-site-ready", "allow-open-panel"] } + "permissions": ["allow-open-panel"] } ``` -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. +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`). -## Start a project +`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): + `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 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. + +## Scripts (no CI) ```sh -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 +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 ``` -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). +`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 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. - -## Optional command groups - -Beyond the commands every app gets, the host serves groups of shell-only commands that an app turns -on in its `AppConfig` (or, for the state-free ones, simply grants in its shell capability). Each -group is a list in `waybetter_host::commands`, each wrapper checks its caller first, and -`waybetter_host::testkit` asserts both in your `tests/security.rs`. - -| Group | Turn on with | What it serves | What the app supplies | -| --- | --- | --- | --- | -| `STORE` | `AppConfig::with_store(&STORE)` | install links, dropped files, the signed Store, the install screen | its `StoreConfig` (app id, hosts, public keys) | -| `MEDIA` | `with_media()` | gallery folders, previews, the opt-in clipboard history and its watcher | attaching an image to the site's composer, if it has one (`media_commands::gallery_file` and `clip_image` give it the checked bytes) | -| `GFONTS` | `with_fonts()` | Google Fonts install, remove, preview (needs the `net` feature) | `SiteHooks::fonts_changed` (give the tabs their theme again) | -| `UPDATE` | `with_updates(&UpdaterConfig)` | update status, check now, apply, the update loop and the hotfix channel | the channel, its key and the download page | -| `SYNC` | `with_sync()` | encrypted folder sync | `SiteHooks::backup_sections` and `backup_section_names` | -| `DEV` | `with_dev()` | developer mode: live reload of plugins, custom CSS and a theme file | `SiteHooks::dev_theme_apply` and `dev_theme_end` | -| `WORKSPACES`, `BACKUP` | always served | saved layouts; settings backup (collect, export, open, apply) | for backup: `backup_drafts` and `backup_apply` (how each imported section is applied) | - -What is still the app's to write today: keyword alerts' commands around `waybetter_host::alerts`, -the theme commands around `waybetter_host::theme` (wayBetter for X names them `x_*`), a -popover webview and anything else that is specific to the site. They are on the list to move. - -## 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. | +Requires Bun 1.4.2+, Node 24+ and Rust 1.88+. diff --git a/crates/waybetter-host/Cargo.toml b/crates/waybetter-host/Cargo.toml index f203e14..bee6c18 100644 --- a/crates/waybetter-host/Cargo.toml +++ b/crates/waybetter-host/Cargo.toml @@ -64,7 +64,7 @@ reqwest = { version = "0.13", default-features = false, features = ["rustls-no-p rustls = { version = "0.23", default-features = false, features = ["ring"], optional = true } [target.'cfg(windows)'.dependencies] -windows = { version = "0.62", features = ["Win32_Foundation", "Win32_System_Com", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"], optional = true } +windows = { version = "0.62", features = ["Win32_Foundation", "Win32_System_Com", "Win32_System_Threading", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"], optional = true } # The WebView2 COM interfaces wry already links (hidden tabs: low memory target). webview2-com = { version = "0.39", optional = true } # Clipboard sequence number (skip unchanged polls) and password-manager exclusion formats. diff --git a/crates/waybetter-host/src/app.rs b/crates/waybetter-host/src/app.rs index f6a380a..a0ffc15 100644 --- a/crates/waybetter-host/src/app.rs +++ b/crates/waybetter-host/src/app.rs @@ -22,7 +22,6 @@ 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}, @@ -80,26 +79,6 @@ pub struct AppConfig { pub plugins: &'static PluginHost, /// The home page before the owner sets one (default: the site's first origin). pub home_url: Option<&'static str>, - /// The store this app installs themes and plugins from (`waybetter://install` links, dropped - /// files, the signed catalog): serves [`commands::STORE`]. Needs `deep_link` for the links and - /// the `net` feature for downloads. - pub store: Option<&'static crate::store::StoreConfig>, - /// The shell's media panel (gallery folders, the clipboard history): serves [`commands::MEDIA`]. - pub media: bool, - /// Google Fonts (install, remove, preview; the cache in app data): serves [`commands::GFONTS`] - /// and calls [`SiteHooks::fonts_changed`]. Needs the `net` feature. - pub fonts: bool, - /// Encrypted folder sync of the settings backup: serves [`commands::SYNC`] and needs - /// [`SiteHooks::backup_sections`]. ([`commands::WORKSPACES`] is served for every app.) - pub sync: bool, - /// Developer mode (live reload of plugins, custom CSS and a theme file): serves - /// [`commands::DEV`] and runs the watcher while it is on; the theme file is the app's - /// ([`SiteHooks::dev_theme_apply`]). - pub dev: bool, - /// Native updates and the hotfix channel: serves [`commands::UPDATE`] and runs the update loop. - /// Needs `updater` (the plugin) and the `net` feature. - #[cfg(feature = "net")] - pub updates: Option<&'static crate::updater::UpdaterConfig>, } impl AppConfig { @@ -121,53 +100,9 @@ impl AppConfig { page_string_prefixes: &["kit.", "plugin."], plugins, home_url: None, - store: None, - media: false, - fonts: false, - sync: false, - dev: false, - #[cfg(feature = "net")] - updates: None, } } - /// Serves the update commands ([`commands::UPDATE`]) and runs the update loop. - #[cfg(feature = "net")] - pub const fn with_updates(mut self, updates: &'static crate::updater::UpdaterConfig) -> Self { - self.updates = Some(updates); - self - } - - /// Serves the developer-mode commands ([`commands::DEV`]). - pub const fn with_dev(mut self) -> Self { - self.dev = true; - self - } - - /// Serves the sync commands ([`commands::SYNC`]). - pub const fn with_sync(mut self) -> Self { - self.sync = true; - self - } - - /// Serves the Google Fonts commands ([`commands::GFONTS`]). - pub const fn with_fonts(mut self) -> Self { - self.fonts = true; - self - } - - /// Serves the media panel's commands ([`commands::MEDIA`]). - pub const fn with_media(mut self) -> Self { - self.media = true; - self - } - - /// Serves the store's commands ([`commands::STORE`]) with this configuration. - pub const fn with_store(mut self, store: &'static crate::store::StoreConfig) -> Self { - self.store = Some(store); - self - } - /// The home page before the owner sets one. pub fn home(&self) -> String { self.home_url.map(str::to_owned).unwrap_or_else(|| format!("{}/", self.site.primary_origin())) @@ -201,13 +136,6 @@ pub trait SiteHooks: Send + Sync + 'static { /// (`waybetter_host::bridge`), then the app's page runtime. fn init_scripts(&self, app: &AppHandle, tab: &NewTab) -> Vec; - /// The document-start scripts of a tab in safe mode ([`crate::safe`]) instead of - /// [`Self::init_scripts`]: by default the host's tab bridge alone, so nothing of the app's page - /// layers runs. An app returns more here only for a layer it wants to survive safe mode. - fn safe_init_scripts(&self, _app: &AppHandle, _tab: &NewTab) -> Vec { - vec![crate::bridge::SOURCE.to_owned()] - } - /// The new tab webview's background until the page paints. fn tab_background(&self, _app: &AppHandle, _label: &str) -> Option { None @@ -246,44 +174,6 @@ pub trait SiteHooks: Send + Sync + 'static { /// A tab webview was created. fn tab_created(&self, _app: &AppHandle) {} - /// A Google font was installed or removed ([`commands::GFONTS`]): give the site tabs their - /// theme, and the font bytes, again. - fn fonts_changed(&self, _app: &AppHandle) {} - - /// The app's native settings as backup sections (themes, plugins, tweaks, ... keyed by section - /// name, from app data): what a backup and [`commands::SYNC`] carry besides the shell's own - /// storage. By default none. - fn backup_sections(&self, _app: &AppHandle) -> Result, String> { - Ok(serde_json::Map::new()) - } - - /// The names of the sections an import may carry (others are dropped). By default none. - fn backup_section_names(&self) -> &'static [&'static str] { - &[] - } - - /// The `drafts` backup section (only when the owner ticks "include drafts"), or none. By default none. - fn backup_drafts(&self, _app: &AppHandle) -> Result, String> { - Ok(None) - } - - /// Applies the sections of an import the owner chose ([`commands::BACKUP`]): check each the way - /// its own setter does, write nothing if any is bad, and return what was applied and notes for - /// the owner (`{ applied: [..], notes: [..] }`). By default importing is not supported. - fn backup_apply(&self, _app: &AppHandle, _sections: &serde_json::Map) -> Result { - Err("UNAVAILABLE: this app cannot import a backup".into()) - } - - /// Developer mode: show the theme file the owner picked (read `path`, make it the theme preview - /// in every site tab). An error is shown with its file and line. By default themes are not - /// supported and this does nothing. - fn dev_theme_apply(&self, _app: &AppHandle, _path: &std::path::Path) -> Result<(), crate::devmode::DevError> { - Ok(()) - } - - /// Developer mode ended (or the theme file was cleared): end the preview [`Self::dev_theme_apply`] made. - fn dev_theme_end(&self, _app: &AppHandle) {} - /// `tab` was laid out for `item` (existing or new), before it is placed. fn tab_placed(&self, _app: &AppHandle, _tab: &Webview, _item: &TabLayout) {} @@ -313,8 +203,6 @@ 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); @@ -330,20 +218,7 @@ fn host_state(app: &AppHandle) -> tauri::State<'_, Host> { app.state::() } -/// The app's site hooks ([`run_app`] must be running). -pub(crate) fn hooks(app: &AppHandle) -> Arc { - host_state(app).hooks.clone() -} - /// The app's config ([`run_app`] must be running). -/// The document-start script that gives a new site tab the current string packs (none when the -/// shell never applied any, or the app has no store). Part of the normal page layers, so safe mode -/// leaves it out. -fn strings_layer(app: &AppHandle) -> Option { - let stored = app.try_state::()?.strings().delivery()?; - Some(crate::store::delivery_script(config(app).site.hosts, &stored, false)) -} - pub fn config(app: &AppHandle) -> AppConfig { host_state(app).config } @@ -394,10 +269,6 @@ impl PageScripts { /// The page state as scripts for a site document that just loaded (evaluate them natively, so the /// page's CSP cannot block them). An app with scripts of its own places them between these. pub fn page_scripts(app: &AppHandle) -> Result { - // Safe mode: a site page gets none of them. - if crate::safe::active() { - return Ok(PageScripts { features: String::new(), links: String::new(), css: None, plugins: Vec::new() }); - } let site = config(app).site; let page = page(app)?; let css = page.plugins.css(); @@ -530,10 +401,8 @@ fn in_site(site: &SiteSpec, hooks: &dyn SiteHooks, url: &Url) -> bool { /// Reconciles native tab webviews with the shell's panes: creates missing ones, positions and /// shows/hides all of them, and closes webviews whose tab no longer exists. #[tauri::command] -pub(crate) async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec, viewport: Option<[f64; 2]>) -> Result<(), String> { +async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec, viewport: Option<[f64; 2]>) -> Result<(), String> { shell_only(&webview)?; - #[cfg(debug_assertions)] - crate::devloop::remember_layout(&items, viewport); let hooks = host_state(&app).hooks.clone(); let window = webview.window(); // Kept current by the window's resize events (host::follow_window_resizes): no blocking @@ -610,7 +479,7 @@ pub(crate) async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec builder.background_color(color), None => builder, }; @@ -621,8 +490,6 @@ pub(crate) async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec { @@ -632,9 +499,7 @@ pub(crate) async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec) -> Result { - shell_only(&webview)?; - host::tab_zoom(&app, &id, factor) -} - -/// Find in page for tab `id` (the shell's find bar): `start` with a query, `next`, `previous`, `stop`. -/// The engine's own find where this build can drive it (counts arrive as `tab-find` events), else the -/// evaluated `window.find`. The query is one typed line (validated) and is kept nowhere. -#[tauri::command] -async fn tab_find(webview: Webview, app: AppHandle, id: String, action: String, query: Option) -> Result<(), String> { - shell_only(&webview)?; - host::tab_find(&app, &id, &action, query.as_deref()) -} - -/// Whether safe mode is on ([`crate::safe`]): the shell shows it in the titlebar and drops its chrome theme. -#[tauri::command] -async fn safe_mode_get(webview: Webview) -> Result { - shell_only(&webview)?; - Ok(crate::safe::state()) -} - -/// Switches safe mode for this run (memory only, never saved) and rebuilds every tab webview, so -/// each page starts again with or without the app's page layers. The app menu's "Restart in safe -/// mode" and the titlebar's "Leave". -#[tauri::command] -async fn safe_mode_set(webview: Webview, app: AppHandle, on: bool) -> Result { - shell_only(&webview)?; - if crate::safe::set(on) { - emit_shell(&app, crate::safe::EVENT, crate::safe::state()); - rebuild_tabs(&app); - } - Ok(crate::safe::state()) -} - -/// Every tab webview is built again on the shell's next layout: their recorded profiles are marked -/// stale (`tabs_sync` then closes and recreates each one with the document-start scripts of the -/// moment) and the shell is asked to send its layout. -pub fn rebuild_tabs(app: &AppHandle) { - if let Ok(mut data) = profiles(app) { - for profile in data.tab_profiles.values_mut() { - *profile = crate::safe::STALE_PROFILE.to_owned(); - } - } - emit_shell(app, crate::safe::EVENT_REBUILD, ()); -} - /// Gives keyboard focus back to the shell (e.g. Ctrl+L pressed inside a tab). #[tauri::command] async fn shell_focus(webview: Webview) -> Result<(), String> { shell_only(&webview)?; - let result = webview.set_focus().map_err(|error| format!("FOCUS: {error}")); - crate::diag::log("host", &format!("shell_focus -> {}", if result.is_ok() { "ok" } else { "error" })); - result + webview.set_focus().map_err(|error| format!("FOCUS: {error}")) } /// The shell calls this after its first DOM commit, so startup never exposes an empty webview. @@ -766,24 +578,7 @@ async fn shell_raise(webview: Webview, app: AppHandle, on: bool) -> Result supported={supported}")); - Ok(supported) -} - -/// Whether focus and layering diagnostics are on for this run ([`crate::diag`]). -#[tauri::command] -async fn diag_get(webview: Webview) -> Result { - shell_only(&webview)?; - Ok(crate::diag::active()) -} - -/// One diagnostic line from the shell (plain short text; nothing is written unless diagnostics are on). -#[tauri::command] -async fn diag_log(webview: Webview, line: String) -> Result<(), String> { - shell_only(&webview)?; - crate::diag::log("shell", &line); - Ok(()) + Ok(host::raise_shell(&webview, on)) } #[tauri::command] @@ -920,27 +715,6 @@ 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), that the first-run screen was answered, and what the -/// mode's preset was when it was applied (`preset`, flag names to on/off: data for the shell's -/// "custom" and "this mode has new features" notes). 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, preset: Option>) -> Result { - shell_only(&webview)?; - let next = page(&app)?.modes.chosen(mode, onboarded, preset)?; - 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)?; @@ -1029,10 +803,7 @@ fn tab_builder(app: &AppHandle, hooks: &Arc, tab: &NewTab, url: U builder = builder.data_store_identifier(profiles::store_identifier(tab.profile)); } } - // Safe mode: the safe set (the tab bridge) instead of the app's page layers. - // The string packs' delivery goes first, before the page runtime reads it (not in safe mode). - let layers = || strings_layer(app).into_iter().chain(hooks.init_scripts(app, tab)).collect::>(); - for script in crate::safe::layer(crate::safe::active(), layers, || hooks.safe_init_scripts(app, tab)) { + for script in hooks.init_scripts(app, tab) { builder = builder.initialization_script(script); } builder @@ -1107,11 +878,9 @@ fn tab_builder(app: &AppHandle, hooks: &Arc, tab: &NewTab, url: U let finished = matches!(payload.event(), PageLoadEvent::Finished); if !finished { load_hooks.page_started(app, &tab); - // An engine that resets page zoom on navigation still shows this tab's. - host::restore_tab_zoom(app, &tab); } emit_tab_state(app, TabState { id: load_id.clone(), url: Some(payload.url().to_string()), loading: Some(!finished), ..Default::default() }); - if finished && site.is_origin(payload.url()) && !crate::safe::active() { + if finished && site.is_origin(payload.url()) { load_hooks.site_page_loaded(app, &tab, payload.url()); } }) @@ -1166,12 +935,6 @@ fn host_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 's tabs_sync, tab_navigate, tab_action, - tab_zoom, - tab_find, - safe_mode_get, - safe_mode_set, - diag_get, - diag_log, open_external_url, shell_focus, shell_ready, @@ -1189,8 +952,6 @@ 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, @@ -1199,59 +960,6 @@ fn host_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 's ] } -/// The store's commands ([`commands::STORE`]): with the `net` feature (downloads) only. -#[cfg(feature = "net")] -fn store_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { - crate::store_commands::handler() -} - -#[cfg(not(feature = "net"))] -fn store_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { - |_| false -} - -/// The backup commands ([`commands::BACKUP`]). -fn backup_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { - crate::backup_commands::handler() -} - -/// The developer-mode commands ([`commands::DEV`]). -fn dev_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { - crate::dev_commands::handler() -} - -/// The workspaces and sync commands ([`commands::WORKSPACES`], [`commands::SYNC`]). -fn sync_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { - crate::sync_commands::handler() -} - -/// The update commands ([`commands::UPDATE`]): with the `net` feature only. -#[cfg(feature = "net")] -fn update_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { - crate::update_commands::handler() -} - -#[cfg(not(feature = "net"))] -fn update_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { - |_| false -} - -/// The Google Fonts commands ([`commands::GFONTS`]): with the `net` feature (downloads) only. -#[cfg(feature = "net")] -fn fonts_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { - crate::fonts_commands::handler() -} - -#[cfg(not(feature = "net"))] -fn fonts_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { - |_| false -} - -/// The media panel's commands ([`commands::MEDIA`]). -fn media_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { - crate::media_commands::handler() -} - type Setup = Box Result<(), Box> + Send>; /// The app builder: config, site hooks, the app's own setup, then [`App::run`]. @@ -1282,13 +990,6 @@ impl App { { let App { config, hooks, setup } = self; let host_handler = host_handler(); - let store_handler = store_handler(); - let media_handler = media_handler(); - let fonts_handler = fonts_handler(); - let update_handler = update_handler(); - let sync_handler = sync_handler(); - let dev_handler = dev_handler(); - let backup_handler = backup_handler(); let builder = tauri::Builder::::default() // Must be first: a second launch focuses the running window instead of fighting over // the app's data and WebView profile (and hands over its link). @@ -1318,8 +1019,6 @@ 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; @@ -1343,67 +1042,18 @@ 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 mut features = read_json::(&handle, FEATURES_FILE) + let features = read_json::(&handle, FEATURES_FILE) .filter(serde_json::Value::is_object) .unwrap_or_else(|| serde_json::json!({})); - // 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(Page(Mutex::new(PageState { plugins, features, settings }))); tauri_app.manage(Host { config, hooks }); - #[cfg(feature = "net")] - crate::store_commands::init(&handle, &config); - crate::media_commands::init(&handle); - crate::sync_commands::init(&handle); - crate::dev_commands::init(&handle); - #[cfg(feature = "net")] - crate::fonts_commands::init(&handle); - #[cfg(feature = "net")] - crate::update_commands::init(&handle); - // Safe mode for this run: the launch argument, or Shift held while starting (Windows). - crate::safe::set(crate::safe::at_launch(std::env::args(), host::shift_held())); - // Focus and layering diagnostics for this run: `--diag` or WAYBETTER_DIAG=1 (app log folder, diag.log). - if crate::diag::asked(std::env::args(), std::env::var(crate::diag::ENV).ok().as_deref()) { - crate::diag::start(handle.path().app_log_dir().ok()); - } - #[cfg(debug_assertions)] - crate::devloop::start(&handle); if let Some(setup) = setup { setup(&handle)?; } open_window(tauri_app, &config) }) .invoke_handler(move |invoke| { - if commands::STORE.contains(&invoke.message.command()) { - store_handler(invoke) - } else if commands::MEDIA.contains(&invoke.message.command()) { - media_handler(invoke) - } else if commands::GFONTS.contains(&invoke.message.command()) { - fonts_handler(invoke) - } else if commands::UPDATE.contains(&invoke.message.command()) { - update_handler(invoke) - } else if commands::WORKSPACES.contains(&invoke.message.command()) || commands::SYNC.contains(&invoke.message.command()) { - sync_handler(invoke) - } else if commands::DEV.contains(&invoke.message.command()) { - dev_handler(invoke) - } else if commands::BACKUP.contains(&invoke.message.command()) { - backup_handler(invoke) - } else if commands::is_host(invoke.message.command()) { + if commands::is_host(invoke.message.command()) { host_handler(invoke) } else { handler(invoke) diff --git a/crates/waybetter-host/src/backup_commands.rs b/crates/waybetter-host/src/backup_commands.rs deleted file mode 100644 index 749d8ab..0000000 --- a/crates/waybetter-host/src/backup_commands.rs +++ /dev/null @@ -1,147 +0,0 @@ -//! Settings backup, native side ([`crate::commands::BACKUP`], served for every app; an app that -//! does not use them grants them to no one): everything the owner set up in one versioned `.waybetter` file. -//! Every command is shell-only. The envelope, the secret scrubbing and the validation are -//! [`crate::backup`]'s; this module asks for what to save and writes the file. -//! -//! What a backup carries is the app's: its native sections -//! ([`crate::app::SiteHooks::backup_sections`]), its drafts only when the owner ticks "include -//! drafts" ([`crate::app::SiteHooks::backup_drafts`]) and the shell's own storage (`decks`, -//! `shell`). Importing shows the sections for a preview first (nothing is applied); the app applies -//! the ones the owner chose ([`crate::app::SiteHooks::backup_apply`]), each checked as its own -//! setter checks it. Never included: cookies, WebView profile folders, the session database, -//! tokens, signing keys, the sync key, update state, font files, gallery and clipboard data. - -use crate::app::{config, hooks, tr}; -use crate::backup; -use crate::host::shell_only; -use serde::Serialize; -use serde_json::{json, Map, Value}; -use tauri::{AppHandle, Webview}; -use tauri_plugin_dialog::DialogExt; - -/// The app's native sections (plus drafts when asked) and `extra` sections from the shell -/// (`decks`), secret-looking keys removed. -fn collect(app: &AppHandle, include_drafts: bool, extra: Option>) -> Result, String> { - let hooks = hooks(app); - let mut sections = hooks.backup_sections(app)?; - if include_drafts { - if let Some(drafts) = hooks.backup_drafts(app)? { - sections.insert("drafts".into(), drafts); - } - } - for (key, value) in extra.unwrap_or_default() { - // The shell only adds its own storage; it cannot replace a native section or add drafts. - if (key == "decks" || key == "shell") && value.is_object() { - sections.insert(key, value); - } - } - let mut value = Value::Object(sections); - backup::strip_secrets(&mut value); - Ok(match value { - Value::Object(map) => map, - _ => Map::new(), - }) -} - -fn envelope(app: &AppHandle, sections: Map) -> Value { - json!({ - "format": backup::FORMAT, - "version": backup::VERSION, - "app": config(app).title, - "appVersion": app.package_info().version.to_string(), - "createdAt": chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true), - "includesDrafts": sections.contains_key("drafts"), - "sections": sections, - }) -} - -/// The current settings as a backup would carry them (for the import preview's diff). -#[tauri::command] -pub(crate) async fn backup_collect(webview: Webview, app: AppHandle, include_drafts: bool) -> Result, String> { - shell_only(&webview)?; - collect(&app, include_drafts, None) -} - -/// Asks where to save and writes the `.waybetter` file. Returns the path, or None when cancelled. -#[tauri::command] -pub(crate) async fn backup_export_file( - webview: Webview, - app: AppHandle, - include_drafts: bool, - extra: Option>, -) -> Result, String> { - shell_only(&webview)?; - let sections = collect(&app, include_drafts, extra)?; - let bytes = serde_json::to_vec_pretty(&envelope(&app, sections)).map_err(|_| "BACKUP: serialization failed")?; - let today = chrono::Utc::now().format("%Y-%m-%d"); - let name = format!("wayBetter-settings-{today}.{}", backup::EXTENSION); - let picked = app - .dialog() - .file() - .set_parent(&webview.window()) - .set_title(tr(&app, "native.dialog.saveBackup", "Save wayBetter settings")) - .set_file_name(&name) - .add_filter(tr(&app, "native.dialog.backupFilter", "wayBetter settings"), &[backup::EXTENSION]) - .blocking_save_file(); - let Some(picked) = picked else { return Ok(None) }; - let mut path = picked.into_path().map_err(|_| "BACKUP: not a local file")?; - if path.extension().and_then(|ext| ext.to_str()) != Some(backup::EXTENSION) { - path.set_extension(backup::EXTENSION); - } - backup::write_atomic(&path, &bytes)?; - Ok(Some(path.to_string_lossy().into_owned())) -} - -#[derive(Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct OpenedBackup { - file: String, - created_at: Option, - app_version: Option, - sections: Map, -} - -/// Asks for a `.waybetter` file and returns its sections for the preview (nothing applied yet). -#[tauri::command] -pub(crate) async fn backup_open_file(webview: Webview, app: AppHandle) -> Result, String> { - shell_only(&webview)?; - let picked = app - .dialog() - .file() - .set_parent(&webview.window()) - .set_title(tr(&app, "native.dialog.importBackup", "Import wayBetter settings")) - .add_filter(tr(&app, "native.dialog.backupFilter", "wayBetter settings"), &[backup::EXTENSION, "json"]) - .blocking_pick_file(); - let Some(picked) = picked else { return Ok(None) }; - let path = picked.into_path().map_err(|_| "BACKUP: not a local file")?; - let meta = std::fs::metadata(&path).map_err(|_| "BACKUP: file not found")?; - if meta.len() as usize > backup::MAX_BACKUP_BYTES { - return Err("BACKUP: the file is larger than 32 MB".into()); - } - let bytes = std::fs::read(&path).map_err(|error| format!("BACKUP: {error}"))?; - let sections = backup::parse_backup(&bytes, hooks(&app).backup_section_names())?; - let head: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null); - Ok(Some(OpenedBackup { - file: path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(), - created_at: head.get("createdAt").and_then(Value::as_str).map(str::to_owned), - app_version: head.get("appVersion").and_then(Value::as_str).map(str::to_owned), - sections, - })) -} - -/// Applies the sections the owner chose (the shell applies `decks` itself): secret-looking keys -/// are removed first, then the app checks and applies each section -/// ([`crate::app::SiteHooks::backup_apply`]). Returns what was applied and notes for the owner. -#[tauri::command] -pub(crate) async fn backup_apply(webview: Webview, app: AppHandle, sections: Map) -> Result { - shell_only(&webview)?; - let mut sections = Value::Object(sections); - backup::strip_secrets(&mut sections); - let sections = sections.as_object().cloned().unwrap_or_default(); - hooks(&app).backup_apply(&app, §ions) -} - -/// The backup commands ([`crate::commands::BACKUP`]). -pub(crate) fn handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { - tauri::generate_handler![backup_collect, backup_export_file, backup_open_file, backup_apply] -} diff --git a/crates/waybetter-host/src/bridge.rs b/crates/waybetter-host/src/bridge.rs index 9e4fa4c..9b74f74 100644 --- a/crates/waybetter-host/src/bridge.rs +++ b/crates/waybetter-host/src/bridge.rs @@ -12,7 +12,7 @@ const DEFAULT_OPTIONS: &str = "const options = { shortcuts: true, linkDrags: tru /// not handle it: a forwarded shortcut is taken from the page (`preventDefault`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct BridgeOptions { - /// Browser shortcuts (new/close/reopen tab, reload, back/forward, split, palette, the app menu, zoom, deck keys). + /// Browser shortcuts (new/close/reopen tab, reload, back/forward, split, palette, deck keys). pub shortcuts: bool, /// Link drags out of (or into) the page, for the shell's split/tab drop zones. pub link_drags: bool, @@ -58,7 +58,7 @@ mod tests { fn forwarded_shortcuts_are_ones_the_host_accepts() { for name in ["deck-toggle", "deck-compose", "column-page-prev", "column-page-next", "column-prev", "column-next", "reopen-tab", "new-tab", "open-panel", "close-tab", "focus-address", "command-palette", "prev-tab", "next-tab", "hard-reload", "reload", "split-down", - "split-right", "back", "forward", "app-menu", "zoom-in", "zoom-out", "zoom-reset", "find"] { + "split-right", "back", "forward"] { assert!(SOURCE.contains(&format!("'{name}'")), "{name} is not in the bridge"); assert!(crate::tabs::valid_shortcut(name), "{name} would be refused"); } diff --git a/crates/waybetter-host/src/commands.rs b/crates/waybetter-host/src/commands.rs index b3927d2..7cfbf5a 100644 --- a/crates/waybetter-host/src/commands.rs +++ b/crates/waybetter-host/src/commands.rs @@ -11,12 +11,6 @@ pub const SHELL: &[&str] = &[ "tabs_sync", "tab_navigate", "tab_action", - "tab_zoom", - "tab_find", - "safe_mode_get", - "safe_mode_set", - "diag_get", - "diag_log", "open_external_url", "shell_focus", "shell_ready", @@ -34,8 +28,6 @@ pub const SHELL: &[&str] = &[ "custom_css_set", "features_get", "features_set", - "mode_get", - "mode_set", "settings_get", "settings_set", ]; @@ -47,80 +39,9 @@ pub const TAB: &[&str] = &["tab_shortcut", "tab_link_drag"]; /// the shell to open the app's panel). Grant these in a capability limited to the site's URLs. pub const SITE: &[&str] = &["open_panel"]; -/// Shell-only, optional: the store's commands (install links, dropped files, the signed Store and -/// the install screen), served when the app sets `AppConfig::store`. An app that uses the store -/// grants these to the shell (`testkit::Capabilities::assert_shell_only_group`). -pub const STORE: &[&str] = &[ - "install_pending", - "install_stage_link", - "install_stage_file", - "install_cancel", - "install_commit", - "plugin_remove", - "install_records", - "install_forget", - "store_catalog", - "store_stage", - "strings_list", - "strings_read", - "strings_set", - "strings_remove", - "strings_apply", -]; - -/// Shell-only, optional: the media panel's commands (gallery folders, previews, the clipboard -/// history), served when the app sets `AppConfig::media`. An app that uses them grants these to the -/// shell (`testkit::Capabilities::assert_shell_only_group`). -pub const MEDIA: &[&str] = &[ - "media_get", - "media_set", - "gallery_add_folder", - "gallery_list", - "gallery_thumb", - "clip_list", - "clip_thumb", - "clip_remove", -]; - -/// Shell-only, optional: Google Fonts (what is installed, install, remove, the faces of a family and -/// a preview), served when the app sets `AppConfig::fonts`; needs the `net` feature. -pub const GFONTS: &[&str] = &["gfonts_installed", "gfonts_install", "gfonts_remove", "gfonts_faces", "gfonts_preview"]; - -/// Shell-only, optional: native updates (status, check now, apply, the shell reached a working -/// state), served when the app sets `AppConfig::updates`; needs the `net` feature. -pub const UPDATE: &[&str] = &["update_status", "update_check", "apply_update", "app_ready"]; - -/// Shell-only, optional: saved workspaces (named tab, pane and deck layouts). State-free: served -/// for every app; an app that uses them grants them to the shell. -pub const WORKSPACES: &[&str] = &["workspaces_get", "workspaces_set"]; - -/// Shell-only, optional: encrypted folder sync of the settings backup, served when the app sets -/// `AppConfig::sync`. -pub const SYNC: &[&str] = &[ - "sync_status", - "sync_choose_folder", - "sync_unlock", - "sync_lock", - "sync_disable", - "sync_configure", - "sync_push", - "sync_check", - "sync_open", - "sync_mark_pulled", -]; - -/// Shell-only, optional: developer mode (live reload of plugins, custom CSS and one theme file), -/// served when the app sets `AppConfig::dev`. -pub const DEV: &[&str] = &["dev_get", "dev_set", "dev_pick_theme", "dev_clear_theme", "dev_reload_plugin", "dev_report_error"]; - -/// Shell-only, optional: the settings backup (collect, export to a file, open a file for the preview, -/// apply chosen sections). State-free: served for every app; what a backup carries is the app's -/// (`SiteHooks::backup_sections`, `backup_drafts`, `backup_apply`). -pub const BACKUP: &[&str] = &["backup_collect", "backup_export_file", "backup_open_file", "backup_apply"]; - /// Whether `command` is one of the host's (dispatched to the host, never to the app's handler). pub fn is_host(command: &str) -> bool { - SHELL.contains(&command) || TAB.contains(&command) || SITE.contains(&command) || STORE.contains(&command) || MEDIA.contains(&command) || GFONTS.contains(&command) || UPDATE.contains(&command) || WORKSPACES.contains(&command) || SYNC.contains(&command) || DEV.contains(&command) || BACKUP.contains(&command) + SHELL.contains(&command) || TAB.contains(&command) || SITE.contains(&command) } /// The capability permission tauri-build generates for `command` (`tabs_sync` → `allow-tabs-sync`). @@ -135,8 +56,8 @@ pub fn permission(command: &str) -> String { /// tauri_build::AppManifest::new().commands(waybetter_host::commands::manifest(&["draft_list"])) /// ``` pub fn manifest(app: &[&'static str]) -> &'static [&'static str] { - let mut all: Vec<&'static str> = Vec::with_capacity(app.len() + SHELL.len() + TAB.len() + SITE.len() + STORE.len() + MEDIA.len() + GFONTS.len() + UPDATE.len() + WORKSPACES.len() + SYNC.len() + DEV.len() + BACKUP.len()); - for command in app.iter().chain(SHELL).chain(TAB).chain(SITE).chain(STORE).chain(MEDIA).chain(GFONTS).chain(UPDATE).chain(WORKSPACES).chain(SYNC).chain(DEV).chain(BACKUP) { + let mut all: Vec<&'static str> = Vec::with_capacity(app.len() + SHELL.len() + TAB.len() + SITE.len()); + for command in app.iter().chain(SHELL).chain(TAB).chain(SITE) { if !all.contains(command) { all.push(command); } @@ -153,7 +74,7 @@ mod tests { let all = manifest(&["draft_list", "tabs_sync"]); assert_eq!(all[0], "draft_list"); assert_eq!(all.iter().filter(|c| **c == "tabs_sync").count(), 1); - for command in SHELL.iter().chain(TAB).chain(SITE).chain(STORE).chain(MEDIA).chain(GFONTS).chain(UPDATE).chain(WORKSPACES).chain(SYNC).chain(DEV).chain(BACKUP) { + for command in SHELL.iter().chain(TAB).chain(SITE) { assert!(all.contains(command), "{command}"); assert!(is_host(command)); } @@ -163,7 +84,7 @@ mod tests { #[test] fn shell_and_tab_commands_do_not_overlap() { - assert!(!SHELL.iter().any(|command| TAB.contains(command) || SITE.contains(command) || STORE.contains(command) || MEDIA.contains(command) || GFONTS.contains(command) || UPDATE.contains(command) || WORKSPACES.contains(command) || SYNC.contains(command) || DEV.contains(command) || BACKUP.contains(command))); + assert!(!SHELL.iter().any(|command| TAB.contains(command) || SITE.contains(command))); assert!(!TAB.iter().any(|command| SITE.contains(command))); } } diff --git a/crates/waybetter-host/src/dev_commands.rs b/crates/waybetter-host/src/dev_commands.rs deleted file mode 100644 index f5206da..0000000 --- a/crates/waybetter-host/src/dev_commands.rs +++ /dev/null @@ -1,346 +0,0 @@ -//! Developer mode (live reload), native side, for every app that sets -//! [`crate::app::AppConfig::dev`] ([`crate::commands::DEV`]). Off by default. While on, a polling -//! watcher ([`crate::devmode`]) sees the plugins folder, `custom.css` and one theme file the owner -//! picked, and reloads what changed in every site tab: the same plugin start and stop scripts, the -//! same custom-CSS script and the app's own theme preview the settings use. Syntax and start -//! errors are kept (and shown as a toast in the site tabs) with the file and line. -//! -//! Every command is shell-only; site tabs gain no command, they only receive scripts native code -//! already evaluates. The theme file is the app's ([`crate::app::SiteHooks::dev_theme_apply`]). - -use crate::app::{config, hooks, page, tr}; -use crate::devmode::{self, DevError}; -use crate::host::{emit_shell, eval_in_site_tabs, read_json, shell_only, write_json}; -use crate::plugins; -use serde::Serialize; -use std::collections::VecDeque; -use std::path::Path; -use std::sync::Mutex; -use tauri::{AppHandle, Manager, Webview}; -use tauri_plugin_dialog::DialogExt; - -const MAX_DEV_ERRORS: usize = 20; - -#[derive(Default)] -pub(crate) struct DevState { - inner: Mutex, -} - -#[derive(Default)] -struct DevInner { - settings: devmode::DevSettings, - errors: VecDeque, - /// The theme preview in every site tab is developer mode's (so turning it off ends it). - owns_preview: bool, - /// Bumped when what is watched changes; the watcher then takes a new baseline. - generation: u64, -} - -#[derive(Clone, Serialize)] -#[serde(rename_all = "camelCase")] -struct DevErrorEntry { - #[serde(flatten)] - error: DevError, - at: String, -} - -#[derive(Clone, Serialize)] -#[serde(rename_all = "camelCase", tag = "kind")] -enum DevEvent { - /// A plugin file changed; the shell checks its syntax, then asks `dev_reload_plugin`. - Check { file: String, source: String }, - Reloaded { target: String, file: Option }, - Error { error: DevError }, - Changed, -} - -#[derive(Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct DevStatus { - enabled: bool, - theme_file: Option, - plugins_folder: String, - errors: Vec, -} - -fn dev_state(app: &AppHandle) -> Result, String> { - app.try_state::().ok_or_else(|| "UNAVAILABLE: this app has no developer mode".to_owned()) -} - -fn now() -> String { - chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true) -} - -fn eval_in_site(app: &AppHandle, script: &str) { - eval_in_site_tabs(app, config(app).site, script); -} - -fn dev_status(app: &AppHandle) -> Result { - let dev = dev_state(app)?; - let inner = dev.inner.lock().map_err(|_| "DEV: busy")?; - let folder = page(app)?.plugins.dir().to_string_lossy().into_owned(); - Ok(DevStatus { enabled: inner.settings.enabled, theme_file: inner.settings.theme_file.clone(), plugins_folder: folder, errors: inner.errors.iter().cloned().collect() }) -} - -/// A danger toast through the plugin UI kit of the page runtime, in the top frame of a site tab. -fn toast_script(app: &AppHandle, message: &str) -> String { - let site = config(app).site; - let message = serde_json::to_string(message).unwrap_or_else(|_| "\"\"".into()); - let origin = serde_json::to_string(&site.primary_origin()).unwrap_or_else(|_| "\"\"".into()); - format!( - "(()=>{{if(window.top!==window||location.origin!=={origin})return;const W=window.{};\ -try{{W&&W.api&&W.api.ui&&W.api.ui.toast({message},{{tone:'danger',duration:12000}});}}catch(e){{}}}})();", - site.runtime_global - ) -} - -fn record_error(app: &AppHandle, error: DevError) { - let where_ = match (error.line, error.column) { - (Some(line), Some(column)) => format!("{}:{line}:{column}", error.file), - (Some(line), None) => format!("{}:{line}", error.file), - _ => error.file.clone(), - }; - eval_in_site(app, &toast_script(app, &format!("{where_} — {}", error.message))); - if let Ok(dev) = dev_state(app) { - if let Ok(mut inner) = dev.inner.lock() { - inner.errors.push_front(DevErrorEntry { error: error.clone(), at: now() }); - inner.errors.truncate(MAX_DEV_ERRORS); - } - } - emit_shell(app, devmode::EVENT, DevEvent::Error { error }); -} - -fn clear_errors_for(app: &AppHandle, file: &str) { - if let Ok(dev) = dev_state(app) { - if let Ok(mut inner) = dev.inner.lock() { - inner.errors.retain(|entry| entry.error.file != file); - } - } -} - -/// Loads the saved settings and starts the watcher (idle until developer mode is turned on). Does -/// nothing unless the app set [`crate::app::AppConfig::dev`]. -pub(crate) fn init(app: &AppHandle) { - if !config(app).dev { - return; - } - let settings = read_json::(app, devmode::FILE).and_then(|settings| settings.validated().ok()).unwrap_or_default(); - app.manage(DevState { inner: Mutex::new(DevInner { settings, ..Default::default() }) }); - let handle = app.clone(); - std::thread::Builder::new().name("wb-dev-watch".into()).spawn(move || watch_loop(handle)).ok(); -} - -fn watch_loop(app: AppHandle) { - let mut watcher = devmode::Watcher::new(); - let mut generation = u64::MAX; - loop { - std::thread::sleep(devmode::POLL); - let Ok(dev) = dev_state(&app) else { return }; - let (enabled, theme_file, current) = match dev.inner.lock() { - Ok(inner) => (inner.settings.enabled, inner.settings.theme_file.clone(), inner.generation), - Err(_) => continue, - }; - drop(dev); - if !enabled { - generation = u64::MAX; - std::thread::sleep(std::time::Duration::from_millis(800)); - continue; - } - if current != generation { - watcher.reset(); - generation = current; - } - let Ok(plugins_dir) = page(&app).map(|page| page.plugins.dir().to_path_buf()) else { continue }; - let scan = devmode::scan(&plugins_dir, theme_file.as_deref().map(Path::new)); - for change in watcher.observe(std::time::Instant::now(), scan) { - handle_change(&app, &change, theme_file.as_deref()); - } - } -} - -fn apply_dev_theme(app: &AppHandle, path: &str) { - match hooks(app).dev_theme_apply(app, Path::new(path)) { - Ok(()) => { - if let Ok(dev) = dev_state(app) { - if let Ok(mut inner) = dev.inner.lock() { - inner.owns_preview = true; - } - } - let file = Path::new(path).file_name().map(|name| name.to_string_lossy().into_owned()); - if let Some(file) = &file { - clear_errors_for(app, file); - } - emit_shell(app, devmode::EVENT, DevEvent::Reloaded { target: "theme".into(), file }); - } - Err(error) => record_error(app, error), - } -} - -fn handle_change(app: &AppHandle, change: &devmode::Change, theme_file: Option<&str>) { - use devmode::{Change, Target}; - let plugins = config(app).plugins; - match change { - Change::Changed(Target::Theme) => { - if let Some(path) = theme_file { - apply_dev_theme(app, path); - } - } - Change::Removed(Target::Theme) => { - let file = theme_file.and_then(|path| Path::new(path).file_name()).map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(); - record_error(app, DevError { file, line: None, column: None, message: "The theme file was deleted or renamed.".into() }); - } - Change::Changed(Target::Css) | Change::Removed(Target::Css) => { - let css = page(app).map(|page| page.plugins.css()).unwrap_or_default(); - if let Ok(script) = plugins::css_script(plugins, &css) { - eval_in_site(app, &script); - } - emit_shell(app, devmode::EVENT, DevEvent::Reloaded { target: "css".into(), file: Some("custom.css".into()) }); - } - Change::Changed(Target::Plugin(file)) => { - let (enabled, source) = match page(app) { - Ok(page) => { - let enabled = page.plugins.list().map(|list| list.iter().any(|plugin| &plugin.file == file && plugin.enabled)).unwrap_or(false); - (enabled, std::fs::read_to_string(page.plugins.dir().join(file)).ok()) - } - Err(_) => return, - }; - match (enabled, source) { - (true, Some(source)) if source.len() as u64 <= plugins::MAX_PLUGIN_BYTES => { - emit_shell(app, devmode::EVENT, DevEvent::Check { file: file.clone(), source }); - } - (true, _) => record_error(app, DevError { file: file.clone(), line: None, column: None, message: "Not readable as UTF-8 text under 2 MiB.".into() }), - (false, _) => emit_shell(app, devmode::EVENT, DevEvent::Changed), - } - } - Change::Removed(Target::Plugin(file)) => { - if let Ok(script) = plugins::stop_script(plugins, file) { - eval_in_site(app, &script); - } - emit_shell(app, devmode::EVENT, DevEvent::Changed); - } - } -} - -fn save_dev(app: &AppHandle, settings: &devmode::DevSettings) -> Result<(), String> { - write_json(app, devmode::FILE, settings) -} - -fn end_dev_preview(app: &AppHandle) { - let owned = dev_state(app).ok().and_then(|dev| dev.inner.lock().ok().map(|mut inner| std::mem::take(&mut inner.owns_preview))).unwrap_or(false); - if owned { - hooks(app).dev_theme_end(app); - } -} - -#[tauri::command] -pub(crate) async fn dev_get(webview: Webview, app: AppHandle) -> Result { - shell_only(&webview)?; - dev_status(&app) -} - -/// Turns developer mode on or off. Off ends the watched theme's preview. -#[tauri::command] -pub(crate) async fn dev_set(webview: Webview, app: AppHandle, enabled: bool) -> Result { - shell_only(&webview)?; - let (settings, theme_file) = { - let dev = dev_state(&app)?; - let mut inner = dev.inner.lock().map_err(|_| "DEV: busy")?; - inner.settings.enabled = enabled; - inner.generation = inner.generation.wrapping_add(1); - (inner.settings.clone(), inner.settings.theme_file.clone()) - }; - save_dev(&app, &settings)?; - emit_shell(&app, devmode::EVENT, DevEvent::Changed); - if enabled { - if let Some(path) = theme_file { - apply_dev_theme(&app, &path); - } - } else { - end_dev_preview(&app); - } - dev_status(&app) -} - -/// Picks the theme JSON file to live-apply (shown in every site tab while developer mode is on). -#[tauri::command] -pub(crate) async fn dev_pick_theme(webview: Webview, app: AppHandle) -> Result { - shell_only(&webview)?; - let title = tr(&app, "native.dialog.themeFile", "Choose a theme file to live-reload"); - let filter = tr(&app, "native.dialog.themeFilter", "Theme"); - let picked = app.dialog().file().set_parent(&webview.window()).set_title(title).add_filter(filter, &["json"]).blocking_pick_file(); - let Some(picked) = picked else { return dev_status(&app) }; - let path = picked.into_path().map_err(|_| "DEV: not a local file")?; - let settings = { - let dev = dev_state(&app)?; - let mut inner = dev.inner.lock().map_err(|_| "DEV: busy")?; - let next = devmode::DevSettings { theme_file: Some(path.to_string_lossy().into_owned()), ..inner.settings.clone() }.validated()?; - inner.settings = next.clone(); - inner.generation = inner.generation.wrapping_add(1); - next - }; - save_dev(&app, &settings)?; - if settings.enabled { - apply_dev_theme(&app, settings.theme_file.as_deref().unwrap_or_default()); - } - dev_status(&app) -} - -#[tauri::command] -pub(crate) async fn dev_clear_theme(webview: Webview, app: AppHandle) -> Result { - shell_only(&webview)?; - let settings = { - let dev = dev_state(&app)?; - let mut inner = dev.inner.lock().map_err(|_| "DEV: busy")?; - inner.settings.theme_file = None; - inner.generation = inner.generation.wrapping_add(1); - inner.settings.clone() - }; - save_dev(&app, &settings)?; - end_dev_preview(&app); - dev_status(&app) -} - -/// Reloads plugin `file` in every site tab after the shell checked its syntax: stop, then start the -/// new version (evaluated with a sourceURL so errors name the file and line). Developer mode only. -#[tauri::command] -pub(crate) async fn dev_reload_plugin(webview: Webview, app: AppHandle, file: String) -> Result<(), String> { - shell_only(&webview)?; - if !dev_state(&app)?.inner.lock().map(|inner| inner.settings.enabled).unwrap_or(false) { - return Err("DEV: developer mode is off".into()); - } - let host = config(&app).plugins; - let (stop, start) = { - let page = page(&app)?; - let enabled = page.plugins.list()?.iter().any(|plugin| plugin.file == file && plugin.enabled); - if !enabled { - return Err("DEV: that plugin is not enabled".into()); - } - let source = std::fs::read_to_string(page.plugins.dir().join(&file)).map_err(|_| "DEV: plugin file not readable")?; - (plugins::stop_script(host, &file)?, plugins::dev_start_script(host, &file, &source, devmode::SOURCE_PREFIX)?) - }; - // The old version is stopped, then the new one starts, evaluated on its own so its sourceURL - // line numbers are the file's. Scripts run in order in each tab. - eval_in_site(&app, &stop); - eval_in_site(&app, &start); - clear_errors_for(&app, &file); - emit_shell(&app, devmode::EVENT, DevEvent::Reloaded { target: "plugin".into(), file: Some(file) }); - Ok(()) -} - -/// The shell found a syntax error in a changed plugin (it was not reloaded): recorded, and shown -/// as a toast in the site tabs. -#[tauri::command] -pub(crate) async fn dev_report_error(webview: Webview, app: AppHandle, file: String, line: Option, column: Option, message: String) -> Result<(), String> { - shell_only(&webview)?; - if !plugins::valid_file_name(&file) { - return Err("VALIDATION: invalid plugin file name".into()); - } - let message: String = message.chars().filter(|ch| !ch.is_control()).take(300).collect(); - record_error(&app, DevError { file, line, column, message }); - Ok(()) -} - -/// The developer-mode commands ([`crate::commands::DEV`]). -pub(crate) fn handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { - tauri::generate_handler![dev_get, dev_set, dev_pick_theme, dev_clear_theme, dev_reload_plugin, dev_report_error] -} diff --git a/crates/waybetter-host/src/devloop.rs b/crates/waybetter-host/src/devloop.rs deleted file mode 100644 index 2b2fdf0..0000000 --- a/crates/waybetter-host/src/devloop.rs +++ /dev/null @@ -1,116 +0,0 @@ -//! The debug dev loop: an app's page scripts are read from disk whenever a tab's init scripts are -//! built, and when one of those files changes every tab webview is rebuilt on its current URL, so -//! the new script is injected within a second or two without restarting the app. -//! -//! This module exists only in debug builds (`cfg(debug_assertions)`, see `lib.rs`); release builds -//! contain no file read, no path string and no watcher. An app names its files with -//! [`page_script!`](crate::page_script) in `SiteHooks::init_scripts`; the files it names are the ones -//! watched. Change detection is `devmode`'s debounced signature watcher (a file must keep its -//! size and modification time for `DEBOUNCE`, so a half-written bundle never loads). -//! -//! Why the tabs are rebuilt rather than reloaded: a webview's document-start scripts are fixed at -//! creation, so a plain reload would run the old copy. The rebuild reuses `tabs_sync`'s -//! profile-change path (close, then create with the current init scripts) on the shell's last -//! layout, with each tab's live URL, so route and layout are kept (scroll position is not). - -use crate::app::{self, tabs_sync}; -use crate::devmode::{self, Watcher}; -use crate::{host, policy, tabs::TabLayout}; -use std::collections::{BTreeMap, BTreeSet}; -use std::path::PathBuf; -use std::sync::Mutex; -use std::time::Instant; -use tauri::{AppHandle, Manager}; - -/// Marks a tab's recorded profile as stale so `tabs_sync` rebuilds its webview. -const STALE: &str = "\u{0}dev-reload"; - -static FILES: Mutex> = Mutex::new(BTreeSet::new()); -static LAYOUT: Mutex, Option<[f64; 2]>)>> = Mutex::new(None); - -/// `path` read from disk (and watched from now on), or `embedded` when it is missing or empty. -pub fn from_disk(path: &str, embedded: &str) -> String { - let path = PathBuf::from(path); - let read = std::fs::read_to_string(&path).ok().filter(|text| !text.trim().is_empty()); - if let Ok(mut files) = FILES.lock() { - files.insert(path); - } - read.unwrap_or_else(|| embedded.to_owned()) -} - -/// The shell's latest layout (from `tabs_sync`), to rebuild the tabs from. -pub(crate) fn remember_layout(items: &[TabLayout], viewport: Option<[f64; 2]>) { - if let Ok(mut layout) = LAYOUT.lock() { - *layout = Some((items.to_vec(), viewport)); - } -} - -/// Starts the watcher thread (debug builds, from the host's setup). -pub(crate) fn start(app: &AppHandle) { - let app = app.clone(); - std::thread::Builder::new().name("wb-dev-loop".into()).spawn(move || watch_loop(app)).ok(); -} - -fn scan() -> BTreeMap { - let files = FILES.lock().map(|files| files.clone()).unwrap_or_default(); - files.into_iter().filter_map(|path| devmode::signature(&path).map(|sig| (path, sig))).collect() -} - -fn watch_loop(app: AppHandle) { - let mut watcher: Watcher = Watcher::new(); - let mut known = 0; - loop { - std::thread::sleep(devmode::POLL); - let current = scan(); - // A newly named file (the first tab just built its scripts) becomes part of the baseline. - if current.len() != known { - known = current.len(); - watcher.reset(); - } - let changes = watcher.observe(Instant::now(), current); - if !changes.is_empty() { - let names: Vec = changes.iter().filter_map(|change| change.target().file_name()).map(|name| name.to_string_lossy().into_owned()).collect(); - let started = Instant::now(); - reload_tabs(&app); - eprintln!("[wayBetter dev] {} changed: tabs rebuilt in {} ms", names.join(", "), started.elapsed().as_millis()); - } - } -} - -/// Rebuilds every tab webview (fresh init scripts) on its current URL. -fn reload_tabs(app: &AppHandle) { - let Some((mut items, viewport)) = LAYOUT.lock().ok().and_then(|layout| layout.clone()) else { return }; - let Some(shell) = app.get_webview(policy::SHELL_LABEL) else { return }; - for item in &mut items { - let Some(tab) = host::tab_webview(app, &item.id) else { continue }; - if let Ok(url) = tab.url() { - if matches!(url.scheme(), "http" | "https") { - item.url = url.to_string(); - } - } - if let Ok(mut data) = app::profiles(app) { - data.tab_profiles.insert(policy::tab_label(&item.id), STALE.to_owned()); - } - } - if let Err(error) = tauri::async_runtime::block_on(tabs_sync(shell, app.clone(), items, viewport)) { - eprintln!("[wayBetter dev] tab rebuild failed: {error}"); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn from_disk_reads_the_file_and_falls_back_to_the_embedded_copy() { - let dir = tempfile::tempdir().unwrap(); - let file = dir.path().join("runtime.js"); - let path = file.to_str().unwrap(); - assert_eq!(from_disk(path, "embedded"), "embedded", "missing file"); - std::fs::write(&file, " \n").unwrap(); - assert_eq!(from_disk(path, "embedded"), "embedded", "empty file"); - std::fs::write(&file, "fresh();").unwrap(); - assert_eq!(from_disk(path, "embedded"), "fresh();"); - assert!(scan().contains_key(&file), "a named file is watched"); - } -} diff --git a/crates/waybetter-host/src/devmode.rs b/crates/waybetter-host/src/devmode.rs index e94e1db..5dcdeea 100644 --- a/crates/waybetter-host/src/devmode.rs +++ b/crates/waybetter-host/src/devmode.rs @@ -61,23 +61,21 @@ pub struct Signature { pub modified: Option, } -/// A stable change of one watched key (a [`Target`] for developer mode; the debug page-script -/// reload keys its files by path). #[derive(Clone, Debug, PartialEq, Eq)] -pub enum Change { - Changed(K), - Removed(K), +pub enum Change { + Changed(Target), + Removed(Target), } -impl Change { - pub fn target(&self) -> &K { +impl Change { + pub fn target(&self) -> &Target { match self { Change::Changed(target) | Change::Removed(target) => target, } } } -pub fn signature(path: &Path) -> Option { +fn signature(path: &Path) -> Option { let meta = fs::metadata(path).ok()?; meta.is_file().then(|| Signature { len: meta.len(), modified: meta.modified().ok() }) } @@ -105,30 +103,25 @@ pub fn scan(plugins_dir: &Path, theme_file: Option<&Path>) -> BTreeMap { - known: Option>, +#[derive(Default)] +pub struct Watcher { + known: Option>, /// Target → (signature seen, since when), for changes not yet stable. - pending: BTreeMap, Instant)>, + pending: BTreeMap, Instant)>, } -impl Default for Watcher { - fn default() -> Self { - Self { known: None, pending: BTreeMap::new() } - } -} - -impl Watcher { +impl Watcher { pub fn new() -> Self { Self::default() } /// Feeds one scan; returns the changes that became stable, in reload order. - pub fn observe(&mut self, now: Instant, scan: BTreeMap) -> Vec> { + pub fn observe(&mut self, now: Instant, scan: BTreeMap) -> Vec { let Some(known) = self.known.as_mut() else { self.known = Some(scan); return Vec::new(); }; - let mut targets: Vec = known.keys().cloned().collect(); + let mut targets: Vec = known.keys().cloned().collect(); for target in scan.keys() { if !known.contains_key(target) { targets.push(target.clone()); @@ -148,7 +141,7 @@ impl Watcher { } } let mut ready = Vec::new(); - let stable: Vec = self + let stable: Vec = self .pending .iter() .filter(|(_, (_, since))| now.duration_since(*since) >= DEBOUNCE) @@ -178,7 +171,7 @@ impl Watcher { } /// Theme first (so plugins read the new `--wb-*` values), then custom CSS, then plugins by name. -pub fn reload_order(mut changes: Vec>) -> Vec> { +pub fn reload_order(mut changes: Vec) -> Vec { changes.sort_by(|a, b| a.target().cmp(b.target())); changes } diff --git a/crates/waybetter-host/src/diag.rs b/crates/waybetter-host/src/diag.rs deleted file mode 100644 index 642ecc5..0000000 --- a/crates/waybetter-host/src/diag.rs +++ /dev/null @@ -1,89 +0,0 @@ -//! Focus and layering diagnostics, off unless asked for at launch (`--diag` or the environment -//! variable `WAYBETTER_DIAG=1`). While on, native code and the shell append one timestamped line per -//! event to `diag.log` in the app's log folder: menu open requests and every close with its reason, -//! overlays and `shell_raise` calls with their results, native focus calls, and the shell document's -//! focus, blur and visibility changes. A line is an event name and a few words: never a URL, a -//! query, page text or anything about an account ([`clean`] keeps plain printable ASCII only and -//! caps the length). The file is truncated at each launch with diagnostics on. - -use std::io::Write; -use std::path::PathBuf; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Mutex; -use std::time::Instant; - -pub const ARG: &str = "--diag"; -pub const ENV: &str = "WAYBETTER_DIAG"; -pub const FILE: &str = "diag.log"; -const MAX_LINE: usize = 300; - -static ON: AtomicBool = AtomicBool::new(false); -static SINK: Mutex> = Mutex::new(None); - -/// Whether this launch asks for diagnostics (the first argument is the program itself). -pub fn asked(args: I, env: Option<&str>) -> bool -where - I: IntoIterator, - S: AsRef, -{ - env.is_some_and(|value| value == "1") || args.into_iter().skip(1).any(|arg| arg.as_ref() == ARG) -} - -/// A line as it is written: printable ASCII only (anything else becomes `?`), one line, capped. -pub fn clean(line: &str) -> String { - line.chars().take(MAX_LINE).map(|ch| if (' '..='~').contains(&ch) { ch } else { '?' }).collect() -} - -/// Starts writing to `dir/diag.log` (created, truncated). Nothing happens without a folder. -pub fn start(dir: Option) { - let Some(dir) = dir else { return }; - let _ = std::fs::create_dir_all(&dir); - if let Ok(file) = std::fs::File::create(dir.join(FILE)) { - if let Ok(mut sink) = SINK.lock() { - *sink = Some((file, Instant::now())); - ON.store(true, Ordering::SeqCst); - } - } - log("host", "diagnostics on"); -} - -pub fn active() -> bool { - ON.load(Ordering::SeqCst) -} - -/// One event from `source` (`host` or `shell`), with milliseconds since the start. -pub fn log(source: &str, line: &str) { - if !active() { - return; - } - if let Ok(mut sink) = SINK.lock() { - if let Some((file, started)) = sink.as_mut() { - let _ = writeln!(file, "{:>9} {:<5} {}", started.elapsed().as_millis(), clean(source), clean(line)); - let _ = file.flush(); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn asked_by_the_argument_or_the_environment_only() { - assert!(asked(["app", "--diag"], None)); - assert!(asked(["app"], Some("1"))); - assert!(!asked(["app"], Some("yes"))); - assert!(!asked(["--diag"], None), "the first argument is the program"); - assert!(!asked(["app", "--diag=1", "diag"], None)); - } - - #[test] - fn a_line_is_plain_short_ascii() { - assert_eq!(clean("menu close: blur (hasFocus=false)"), "menu close: blur (hasFocus=false)"); - assert_eq!(clean("two\nlines\ttab é"), "two?lines?tab ?"); - assert_eq!(clean(&"x".repeat(1000)).len(), MAX_LINE); - // Off by default: nothing is written. - assert!(!active()); - log("shell", "ignored"); - } -} diff --git a/crates/waybetter-host/src/find.rs b/crates/waybetter-host/src/find.rs deleted file mode 100644 index 9c648eb..0000000 --- a/crates/waybetter-host/src/find.rs +++ /dev/null @@ -1,160 +0,0 @@ -//! Find in page. The shell owns the find bar; a tab's page is searched natively through the -//! shell-only `tab_find {id, action, query}`: `start` (a new query), `next`, `previous`, `stop` -//! (the bar closed: highlights go). -//! -//! The engine's own find is used where this build can drive it: WebView2's `ICoreWebView2Find` -//! (Windows, WebView2 Runtime with `ICoreWebView2_28`; its own find bar suppressed), which also -//! reports the match count and the active match (`tab-find` events to the shell). Everywhere else -//! (macOS, Linux, an older WebView2 Runtime) native code evaluates [`fallback_script`] in the tab: -//! the engine's `window.find`, which selects the next match and scrolls to it but counts nothing. -//! -//! The query is data: it goes from the shell to the engine and is kept nowhere (no file, no log, -//! no state in this crate). Tabs gain no command; a tab may only forward the key name `find` -//! through `tab_shortcut`. Only what the page has rendered can be found, as in a browser. - -use serde::Serialize; - -/// The shell event with the engine's counts for a tab's find session. -pub const EVENT_TAB_FIND: &str = "tab-find"; -/// A query is one line of text a person typed. -pub const MAX_QUERY: usize = 256; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum FindAction { - Start, - Next, - Previous, - Stop, -} - -impl FindAction { - pub fn parse(action: &str) -> Result { - match action { - "start" => Ok(Self::Start), - "next" => Ok(Self::Next), - "previous" => Ok(Self::Previous), - "stop" => Ok(Self::Stop), - _ => Err("VALIDATION: unknown find action".into()), - } - } -} - -/// What the engine reported for a tab's find session: how many matches and which one is active -/// (0-based; -1 for none). -#[derive(Clone, Debug, PartialEq, Eq, Serialize)] -pub struct FindState { - pub id: String, - pub count: i32, - pub index: i32, -} - -impl FindState { - /// From WebView2's counts: its `ActiveMatchIndex` starts at 1 (and is -1 without an active match); - /// the shell's is 0-based. A negative count is none. - pub fn from_webview2(id: &str, count: i32, active_one_based: i32) -> Self { - let count = count.max(0); - let index = if (1..=count).contains(&active_one_based) { active_one_based - 1 } else { -1 }; - Self { id: id.to_owned(), count, index } - } -} - -/// A request as native code runs it: `start` carries the query, the others none. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct FindRequest { - pub action: FindAction, - pub query: Option, -} - -/// Validates a `tab_find` call: a known action; for `start` a query of 1..=256 characters with no -/// control characters (one typed line). `next`/`previous` repeat the last query the shell sent for -/// the fallback (the engine's own find keeps its session), so they may carry it too. -pub fn request(action: &str, query: Option<&str>) -> Result { - let action = FindAction::parse(action)?; - let query = match query { - Some(text) => { - let count = text.chars().count(); - if count == 0 || count > MAX_QUERY || text.chars().any(char::is_control) { - return Err("VALIDATION: invalid find query".into()); - } - Some(text.to_owned()) - } - None => None, - }; - if action == FindAction::Start && query.is_none() { - return Err("VALIDATION: find needs a query".into()); - } - Ok(FindRequest { action, query: if action == FindAction::Stop { None } else { query } }) -} - -/// The script native code evaluates where the engine's find cannot be driven natively: the -/// engine's `window.find` (case-insensitive, wrapping), or clearing the selection for `stop`. -/// The query appears only as a JSON string literal; nothing is sent anywhere or stored in the page. -pub fn fallback_script(request: &FindRequest) -> String { - match (&request.action, &request.query) { - (FindAction::Stop, _) | (_, None) => { - "(()=>{try{const s=getSelection();if(s)s.removeAllRanges();}catch(e){}})();".to_owned() - } - (action, Some(query)) => { - let text = serde_json::to_string(query).unwrap_or_else(|_| "\"\"".into()); - // A new query starts from the top of the page; next/previous continue from the selection. - let restart = if *action == FindAction::Start { "const s=getSelection();if(s)s.removeAllRanges();" } else { "" }; - let backwards = *action == FindAction::Previous; - format!("(()=>{{try{{{restart}if(typeof window.find==='function')window.find({text},false,{backwards},true,false,false,false);}}catch(e){{}}}})();") - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_request_is_a_known_action_and_one_typed_line() { - assert_eq!(request("start", Some("tauri")).unwrap(), FindRequest { action: FindAction::Start, query: Some("tauri".into()) }); - assert_eq!(request("next", None).unwrap().action, FindAction::Next); - assert_eq!(request("previous", Some("x")).unwrap().query.as_deref(), Some("x")); - assert_eq!(request("stop", Some("left over")).unwrap(), FindRequest { action: FindAction::Stop, query: None }, "stop carries nothing"); - assert!(request("start", None).is_err(), "start needs a query"); - assert!(request("start", Some("")).is_err()); - assert!(request("eval", Some("x")).is_err()); - assert!(request("start", Some("two\nlines")).is_err()); - assert!(request("start", Some("nul\0")).is_err()); - assert!(request("start", Some(&"a".repeat(MAX_QUERY))).is_ok()); - assert!(request("start", Some(&"a".repeat(MAX_QUERY + 1))).is_err()); - assert!(request("start", Some(&"ş".repeat(MAX_QUERY))).is_ok(), "characters, not bytes"); - } - - #[test] - fn the_fallback_script_carries_the_query_only_as_a_string_literal() { - let script = fallback_script(&request("start", Some("it's \"quoted\" \\ ${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}"#); - // WebView2 counts its active match from 1 (seen live: "2/2" for the first of two). - assert_eq!(FindState::from_webview2("t1", 2, 1), FindState { id: "t1".into(), count: 2, index: 0 }); - assert_eq!(FindState::from_webview2("t1", 2, 2).index, 1); - assert_eq!(FindState::from_webview2("t1", 2, -1).index, -1, "no active match"); - assert_eq!(FindState::from_webview2("t1", 2, 3).index, -1, "out of range"); - assert_eq!(FindState::from_webview2("t1", 0, 0), FindState { id: "t1".into(), count: 0, index: -1 }); - assert_eq!(FindState::from_webview2("t1", -5, 1).count, 0); - } -} diff --git a/crates/waybetter-host/src/fonts_commands.rs b/crates/waybetter-host/src/fonts_commands.rs deleted file mode 100644 index c1423db..0000000 --- a/crates/waybetter-host/src/fonts_commands.rs +++ /dev/null @@ -1,66 +0,0 @@ -//! Google Fonts, native side, for every app that sets [`crate::app::AppConfig::fonts`]: the -//! shell-only `gfonts_*` commands ([`crate::commands::GFONTS`]) over [`crate::fonts`]'s downloads -//! and cache (`fonts.googleapis.com` and `fonts.gstatic.com` only, app-data `fonts/`). Site tabs -//! never request fonts and gain no command: native code hands them cached bytes -//! ([`crate::fonts::page_script_for`]). -//! -//! When a font is installed or removed the app's [`crate::app::SiteHooks::fonts_changed`] runs, so -//! it can give every site tab its theme (and the font bytes) again. - -use crate::fonts::{self, InstalledFont}; -use crate::gfonts::Weights; -use crate::host::shell_only; -use tauri::{AppHandle, Manager, Webview}; - -/// Opens the font cache in app data. Does nothing unless the app set [`crate::app::AppConfig::fonts`]. -pub(crate) fn init(app: &AppHandle) { - if !crate::app::config(app).fonts { - return; - } - if let Ok(dir) = app.path().app_data_dir() { - fonts::init(&dir); - } -} - -fn changed(app: &AppHandle) { - crate::app::hooks(app).fonts_changed(app); -} - -#[tauri::command] -pub(crate) async fn gfonts_installed(webview: Webview) -> Result, String> { - shell_only(&webview)?; - fonts::installed() -} - -#[tauri::command] -pub(crate) async fn gfonts_install(webview: Webview, app: AppHandle, family: String, weights: Weights) -> Result { - shell_only(&webview)?; - let installed = fonts::install(family, weights).await?; - changed(&app); - Ok(installed) -} - -#[tauri::command] -pub(crate) async fn gfonts_remove(webview: Webview, app: AppHandle, family: String) -> Result<(), String> { - shell_only(&webview)?; - fonts::remove(&family)?; - changed(&app); - Ok(()) -} - -#[tauri::command] -pub(crate) async fn gfonts_faces(webview: Webview, family: String) -> Result { - shell_only(&webview)?; - fonts::faces(&family) -} - -#[tauri::command] -pub(crate) async fn gfonts_preview(webview: Webview, family: String, weights: Weights, text: String) -> Result, String> { - shell_only(&webview)?; - fonts::preview(family, weights, text).await -} - -/// The fonts commands ([`crate::commands::GFONTS`]). -pub(crate) fn handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { - tauri::generate_handler![gfonts_installed, gfonts_install, gfonts_remove, gfonts_faces, gfonts_preview] -} diff --git a/crates/waybetter-host/src/host.rs b/crates/waybetter-host/src/host.rs index 489556a..a070b88 100644 --- a/crates/waybetter-host/src/host.rs +++ b/crates/waybetter-host/src/host.rs @@ -48,10 +48,6 @@ pub fn tab_webview(app: &AppHandle, id: &str) -> Option(app: &AppHandle, site: &SiteSpec, script: &str) { - // Safe mode: site pages run none of the app's layers, so nothing is pushed into them either. - if crate::safe::active() { - return; - } for (label, webview) in app.webviews() { if policy::tab_id(&label).is_some() && webview.url().is_ok_and(|url| site.is_origin(&url)) { let _ = webview.eval(script); @@ -93,186 +89,6 @@ pub fn tab_action(app: &AppHandle, id: &str, action: &str) -> Res result.map_err(|error| format!("TAB: {error}")) } -/// Whether Shift is held right now (asked once while the app starts: safe mode). Windows only; -/// elsewhere the launch argument is the way in. -pub fn shift_held() -> bool { - #[cfg(windows)] - { - use windows::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_SHIFT}; - // SAFETY: a plain Win32 key-state read. The high bit means the key is down. - unsafe { GetAsyncKeyState(i32::from(VK_SHIFT.0)) < 0 } - } - #[cfg(not(windows))] - { - false - } -} - -/// The remembered page zoom per tab ([`crate::zoom`], app data `zoom.json`), read once. -fn zooms(app: &AppHandle) -> std::sync::MutexGuard<'static, crate::zoom::ZoomMap> { - use std::sync::{Mutex, OnceLock}; - static ZOOMS: OnceLock> = OnceLock::new(); - ZOOMS - .get_or_init(|| Mutex::new(read_json::(app, crate::zoom::ZOOM_FILE).unwrap_or_default().validated())) - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) -} - -/// `tab_zoom`: sets tab `id`'s page zoom to `factor` (clamped to 25%..500%, the engine's own page -/// zoom) and remembers it for that tab; without a factor only reads it. Returns the factor in effect. -pub fn tab_zoom(app: &AppHandle, id: &str, factor: Option) -> Result { - if !policy::valid_tab_id(id) { - return Err("VALIDATION: invalid tab id".into()); - } - let Some(factor) = factor else { return Ok(zooms(app).get(id)) }; - let tab = tab_webview(app, id).ok_or("TAB: not found")?; - let (before, factor, saved) = { - let mut map = zooms(app); - let before = map.get(id); - let factor = map.set(id, factor)?; - (before, factor, map.clone()) - }; - if let Err(error) = tab.set_zoom(factor) { - // Not applied: what is remembered stays what the tab shows. - let _ = zooms(app).set(id, before); - return Err(format!("TAB: {error}")); - } - if factor != before { - write_json(app, crate::zoom::ZOOM_FILE, &saved)?; - } - Ok(factor) -} - -/// A tab webview that was just created, or loads a page: it shows its remembered zoom (a new -/// webview starts at 100%). Tabs at 100% are left alone. -pub fn restore_tab_zoom(app: &AppHandle, tab: &Webview) { - let Some(id) = policy::tab_id(tab.label()) else { return }; - let factor = zooms(app).get(id); - if factor != crate::zoom::DEFAULT { - let _ = tab.set_zoom(factor); - } -} - -/// A closed tab's zoom is forgotten (a tab that comes back under the same id starts at 100%). -pub fn forget_tab_zoom(app: &AppHandle, id: &str) { - let saved = { - let mut map = zooms(app); - map.forget(id).then(|| map.clone()) - }; - if let Some(map) = saved { - let _ = write_json(app, crate::zoom::ZOOM_FILE, &map); - } -} - -/// `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::from_webview2(id, 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) { @@ -931,11 +747,6 @@ 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/src/lib.rs b/crates/waybetter-host/src/lib.rs index de90492..b940963 100644 --- a/crates/waybetter-host/src/lib.rs +++ b/crates/waybetter-host/src/lib.rs @@ -10,7 +10,6 @@ //! - [`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. @@ -24,14 +23,8 @@ //! shows, its page color and delivery script) over a site's built-in themes. //! - [`workspaces`]: saved tab/pane/deck layouts, bounded and well-formed (never evaluated). //! - [`devmode`]: developer mode's debounced watcher of plugins, custom CSS and a theme file. -//! - `devloop` (debug builds with `app` only): page scripts read from disk and every tab rebuilt when -//! one changes; an app names its files with [`page_script!`]. //! - [`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). -//! - [`zoom`]: page zoom per tab (a clamped factor the shell sets, remembered in `zoom.json`). -//! - [`safe`]: safe mode for one run (a flag in memory: site tabs get the tab bridge and nothing else). -//! - [`find`]: find in page (the request the shell sends, the fallback script; the query is kept nowhere). //! - [`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,8 +47,6 @@ pub mod backup; pub mod bridge; pub mod commands; pub mod devmode; -pub mod diag; -pub mod find; #[cfg(feature = "net")] pub mod fonts; pub mod gfonts; @@ -63,11 +54,9 @@ pub mod hotfix; pub mod i18n; pub mod layout; pub mod media; -pub mod modes; pub mod plugins; pub mod policy; pub mod profiles; -pub mod safe; pub mod settings; pub mod site; pub mod store; @@ -77,74 +66,10 @@ pub mod testkit; pub mod theme; pub mod update; pub mod workspaces; -pub mod zoom; #[cfg(feature = "app")] pub mod app; -#[cfg(all(feature = "app", feature = "net"))] -mod store_commands; -#[cfg(feature = "app")] -pub mod media_commands; -#[cfg(feature = "app")] -mod sync_commands; -#[cfg(feature = "app")] -mod dev_commands; -#[cfg(feature = "app")] -mod backup_commands; -#[cfg(all(feature = "app", feature = "net"))] -mod fonts_commands; -#[cfg(all(feature = "app", feature = "net"))] -mod update_commands; -#[cfg(all(feature = "app", debug_assertions))] -pub mod devloop; #[cfg(feature = "tauri")] pub mod host; #[cfg(all(feature = "tauri", feature = "net"))] pub mod updater; - -/// An app's page script for `SiteHooks::init_scripts`: `$embedded` (an `include_str!`) in every -/// build, except that a debug build reads `$file` (relative to the app crate's manifest directory) -/// from disk each time and falls back to the embedded copy when it is missing. The files named -/// this way are watched: a change rebuilds every tab (`devloop`). In a release build the disk arm -/// is not compiled at all: the expansion is `$embedded.to_owned()`, `$file` appears nowhere. -#[macro_export] -macro_rules! page_script { - ($embedded:expr, $file:literal) => {{ - #[cfg(debug_assertions)] - { - $crate::devloop::from_disk(concat!(env!("CARGO_MANIFEST_DIR"), "/", $file), $embedded) - } - #[cfg(not(debug_assertions))] - { - ($embedded).to_owned() - } - }}; -} - -#[cfg(test)] -mod release_guard { - /// Release builds must not contain the dev loop: every mention of it in this crate is behind - /// `cfg(debug_assertions)` (checked on the source, so it also holds when only debug is built). - #[test] - fn every_devloop_mention_is_debug_only() { - for (file, source) in [("lib.rs", include_str!("lib.rs")), ("app.rs", include_str!("app.rs"))] { - // This test module itself talks about the dev loop; only the code before it counts. - let lines: Vec<&str> = source.split("mod release_guard").next().unwrap_or(source).lines().collect(); - for (index, line) in lines.iter().enumerate() { - let code = line.trim_start(); - if code.starts_with("//") || !(code.contains("devloop::") || code.starts_with("pub mod devloop")) || code.contains("$crate::devloop") { - continue; - } - let gated = (index.saturating_sub(2)..index).any(|before| lines[before].contains("debug_assertions")); - assert!(gated, "{file}:{}: devloop used outside cfg(debug_assertions)", index + 1); - } - } - } - - /// `cargo test --release`: the macro is just the embedded text. - #[cfg(not(debug_assertions))] - #[test] - fn release_page_script_is_the_embedded_copy() { - assert_eq!(crate::page_script!("embedded", "no/such/file.js"), "embedded"); - } -} diff --git a/crates/waybetter-host/src/media_commands.rs b/crates/waybetter-host/src/media_commands.rs deleted file mode 100644 index a8db652..0000000 --- a/crates/waybetter-host/src/media_commands.rs +++ /dev/null @@ -1,264 +0,0 @@ -//! The shell's Media panel, native side, for every app that sets [`crate::app::AppConfig::media`]: -//! gallery folders picked through the native dialog, image previews read only from inside those -//! folders, and the opt-in local clipboard history ([`crate::commands::MEDIA`]). Every command is -//! shell-only; site tabs get nothing. The rules (path containment, size caps, the private-copy -//! rule of the clipboard watcher) are [`crate::media`]'s; this module keeps the state, the files -//! and the polling thread. -//! -//! Attaching an image to a site's composer is the app's (it knows the site's composer); it reads -//! the bytes through [`gallery_file`] and [`clip_image`], which apply the same checks. - -use crate::app::{config, tr}; -use crate::host::{data_file, emit_shell, read_json, shell_only, write_json}; -use crate::media::clipboard::{self, Seen}; -use crate::media::{self, ClipHistory, ClipItem, ImageEntry, MediaSettings}; -use sha2::{Digest, Sha256}; -use std::path::PathBuf; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Mutex, MutexGuard}; -use std::time::Duration; -use tauri::{AppHandle, Manager, State, Webview}; -use tauri_plugin_dialog::DialogExt; - -const MEDIA_FILE: &str = "media.json"; -const CLIP_DIR: &str = "clipboard"; -const POLL: Duration = Duration::from_millis(1_000); - -struct MediaData { - settings: MediaSettings, - history: ClipHistory, -} - -pub(crate) struct MediaState(Mutex); - -fn lock(state: &MediaState) -> Result, String> { - state.0.lock().map_err(|_| "STATE: media state poisoned".to_string()) -} - -fn media_state(app: &AppHandle) -> Result, String> { - app.try_state::().ok_or_else(|| "UNAVAILABLE: this app has no media panel".to_owned()) -} - -fn clip_dir(app: &AppHandle) -> Option { - data_file(app, CLIP_DIR) -} - -fn load_history(app: &AppHandle) -> ClipHistory { - clip_dir(app).map(|dir| media::load_history(&dir)).unwrap_or_default() -} - -fn save_history(app: &AppHandle, history: &ClipHistory) -> Result<(), String> { - media::save_history(&clip_dir(app).ok_or("STORAGE: no application data directory")?, history) -} - -fn delete_files(app: &AppHandle, items: &[ClipItem]) { - if let Some(dir) = clip_dir(app) { - media::delete_files(&dir, items); - } -} - -/// Loads the settings and the history and starts the clipboard watcher (idle until the owner turns -/// the history on). Does nothing unless the app set [`crate::app::AppConfig::media`]. -pub(crate) fn init(app: &AppHandle) { - if !config(app).media { - return; - } - let settings = read_json::(app, MEDIA_FILE) - .and_then(|settings| settings.validated().ok()) - .unwrap_or_default(); - let history = load_history(app); - app.manage(MediaState(Mutex::new(MediaData { settings, history }))); - let handle = app.clone(); - std::thread::spawn(move || poll_clipboard(handle)); -} - -// --------------------------------------------------------------------------------------------- -// Clipboard polling (opt-in; the watcher never reads a copy marked private) - -fn poll_clipboard(app: AppHandle) { - let enabled = || { - app.try_state::() - .and_then(|state| lock(&state).ok().map(|data| data.settings.clipboard_enabled)) - .unwrap_or(false) - }; - let title = config(&app).title; - clipboard::watch(POLL, enabled, |seen| { - if let Err(error) = record(&app, seen) { - eprintln!("{title}: clipboard history: {error}"); - } - }); -} - -/// 32 hex characters (what [`media::valid_clip_id`] accepts): not a secret, only unique. -fn new_clip_id(hash: &str) -> String { - static COUNTER: AtomicU64 = AtomicU64::new(0); - let nanos = chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default(); - let digest = Sha256::digest(format!("{nanos}:{}:{hash}", COUNTER.fetch_add(1, Ordering::Relaxed))); - digest.iter().take(16).map(|byte| format!("{byte:02x}")).collect() -} - -fn record(app: &AppHandle, seen: Seen) -> Result<(), String> { - let at = chrono::Utc::now().timestamp_millis(); - let item = match seen { - Seen::Text(hash, text) => ClipItem { id: new_clip_id(&hash), kind: "text".into(), text: Some(text), file: None, hash, at }, - Seen::Image(hash, width, height, rgba) => { - let id = new_clip_id(&hash); - let state = media_state(app)?; - if lock(&state)?.history.has_hash(&hash) { - // Already stored: just move it to the front, no new file. - ClipItem { id, kind: "image".into(), text: None, file: None, hash, at } - } else { - let png = media::encode_png(width, height, rgba).ok_or("image encoding failed")?; - let dir = clip_dir(app).ok_or("STORAGE: no application data directory")?; - std::fs::create_dir_all(&dir).map_err(|error| format!("STORAGE: {error}"))?; - let file = format!("{id}.png"); - std::fs::write(dir.join(&file), png).map_err(|error| format!("STORAGE: {error}"))?; - ClipItem { id, kind: "image".into(), text: None, file: Some(file), hash, at } - } - } - }; - let state = media_state(app)?; - let evicted = { - let mut data = lock(&state)?; - let max = data.settings.clipboard_max; - let evicted = data.history.push(item, max); - save_history(app, &data.history)?; - evicted - }; - delete_files(app, &evicted); - emit_shell(app, "clipboard-changed", ()); - Ok(()) -} - -// --------------------------------------------------------------------------------------------- -// What an app needs to attach an image - -/// The bytes of a gallery image, only from inside a gallery folder the owner added (symlinks and -/// `..` cannot leave it), with its resolved path (for the name and the type). -pub fn gallery_file(app: &AppHandle, path: &str) -> Result<(PathBuf, Vec), String> { - let state = media_state(app)?; - let folders = lock(&state)?.settings.folders.clone(); - let real = media::resolve_in_folders(&folders, path)?; - let bytes = std::fs::read(&real).map_err(|error| format!("STORAGE: {error}"))?; - Ok((real, bytes)) -} - -/// The PNG of a clipboard-history image. -pub fn clip_image(app: &AppHandle, id: &str) -> Result, String> { - if !media::valid_clip_id(id) { - return Err("VALIDATION: invalid clipboard item".into()); - } - let state = media_state(app)?; - let file = lock(&state)? - .history - .items - .iter() - .find(|item| item.id == id) - .and_then(|item| item.file.clone()) - .ok_or("CLIPBOARD: image not found")?; - let dir = clip_dir(app).ok_or("STORAGE: no application data directory")?; - std::fs::read(dir.join(file)).map_err(|error| format!("STORAGE: {error}")) -} - -// --------------------------------------------------------------------------------------------- -// Commands (shell only) - -#[tauri::command] -pub(crate) async fn media_get(webview: Webview, app: AppHandle) -> Result { - shell_only(&webview)?; - let state = media_state(&app)?; - let settings = lock(&state)?.settings.clone(); - Ok(settings) -} - -/// Changes the clipboard options and removes folders. New folders are only added through the -/// native dialog (`gallery_add_folder`), so the shell cannot widen the file scope by itself. -#[tauri::command] -pub(crate) async fn media_set(webview: Webview, app: AppHandle, settings: MediaSettings) -> Result { - shell_only(&webview)?; - let state = media_state(&app)?; - let settings = settings.validated()?; - let evicted = { - let mut data = lock(&state)?; - if settings.folders.iter().any(|f| !data.settings.folders.contains(f)) { - return Err("FORBIDDEN: add gallery folders with the folder picker".into()); - } - write_json(&app, MEDIA_FILE, &settings)?; - data.settings = settings.clone(); - let evicted = data.history.trim(settings.clipboard_max); - if !evicted.is_empty() { - save_history(&app, &data.history)?; - } - evicted - }; - delete_files(&app, &evicted); - Ok(settings) -} - -#[tauri::command] -pub(crate) async fn gallery_add_folder(webview: Webview, app: AppHandle) -> Result { - shell_only(&webview)?; - let state = media_state(&app)?; - let title = tr(&app, "native.dialog.galleryFolder", "Add a gallery folder"); - let picked = app.dialog().file().set_parent(&webview.window()).set_title(title).blocking_pick_folder(); - let Some(picked) = picked else { return Ok(lock(&state)?.settings.clone()) }; - let path = picked.into_path().map_err(|_| "VALIDATION: not a local folder")?; - let mut data = lock(&state)?; - let mut next = data.settings.clone(); - if next.add_folder(&path)? { - write_json(&app, MEDIA_FILE, &next)?; - data.settings = next; - } - Ok(data.settings.clone()) -} - -#[tauri::command] -pub(crate) async fn gallery_list(webview: Webview, app: AppHandle, limit: Option) -> Result, String> { - shell_only(&webview)?; - let state = media_state(&app)?; - let folders = lock(&state)?.settings.folders.clone(); - Ok(media::list_recent(&folders, limit.unwrap_or(60))) -} - -#[tauri::command] -pub(crate) async fn gallery_thumb(webview: Webview, app: AppHandle, path: String) -> Result { - shell_only(&webview)?; - let (real, bytes) = gallery_file(&app, &path)?; - Ok(media::data_url(media::mime_for(&real), &bytes)) -} - -#[tauri::command] -pub(crate) async fn clip_list(webview: Webview, app: AppHandle) -> Result, String> { - shell_only(&webview)?; - let state = media_state(&app)?; - let items = lock(&state)?.history.items.clone(); - Ok(items) -} - -#[tauri::command] -pub(crate) async fn clip_thumb(webview: Webview, app: AppHandle, id: String) -> Result { - shell_only(&webview)?; - Ok(media::data_url("image/png", &clip_image(&app, &id)?)) -} - -#[tauri::command] -pub(crate) async fn clip_remove(webview: Webview, app: AppHandle, id: Option) -> Result, String> { - shell_only(&webview)?; - let state = media_state(&app)?; - let (removed, items) = { - let mut data = lock(&state)?; - let removed = match id { - Some(id) => data.history.remove(&id).into_iter().collect(), - None => std::mem::take(&mut data.history.items), - }; - save_history(&app, &data.history)?; - (removed, data.history.items.clone()) - }; - delete_files(&app, &removed); - Ok(items) -} - -/// The media commands ([`crate::commands::MEDIA`]). -pub(crate) fn handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { - tauri::generate_handler![media_get, media_set, gallery_add_folder, gallery_list, gallery_thumb, clip_list, clip_thumb, clip_remove] -} diff --git a/crates/waybetter-host/src/modes.rs b/crates/waybetter-host/src/modes.rs deleted file mode 100644 index a97f7d0..0000000 --- a/crates/waybetter-host/src/modes.rs +++ /dev/null @@ -1,132 +0,0 @@ -//! 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. -//! With the choice it keeps what the preset was at that moment (`preset`: flag names and on/off, -//! data the shell hands over), so the shell can tell "the owner changed features" from "an update -//! made the preset larger" later. Native code never reads it and never applies anything. -//! -//! `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 std::collections::BTreeMap; - -use serde::{Deserialize, Serialize}; - -pub const MODES_FILE: &str = "modes.json"; -const MAX_MODE_ID: usize = 32; -const MAX_PRESET_FLAGS: usize = 512; -const MAX_FLAG_NAME: usize = 64; - -#[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, - /// The chosen mode's preset as it was when it was applied (flag name to on/off). `None`: not - /// known (no mode, or a choice made by a version that did not keep it). - #[serde(skip_serializing_if = "Option::is_none")] - pub preset: Option>, -} - -/// A flag name: letters, digits, `.`, `-` and `_`, at most 64 characters. -fn valid_flag(name: &str) -> bool { - !name.is_empty() && name.len() <= MAX_FLAG_NAME && name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_')) -} - -/// 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, preset: None } - } - - pub fn validated(self) -> Result { - if self.mode.as_deref().is_some_and(|mode| !valid_mode(mode)) { - return Err("VALIDATION: invalid mode".into()); - } - if let Some(preset) = &self.preset { - if self.mode.is_none() || preset.len() > MAX_PRESET_FLAGS || !preset.keys().all(|name| valid_flag(name)) { - return Err("VALIDATION: invalid mode preset".into()); - } - } - Ok(self) - } - - /// What the shell may change: the chosen mode, that the screen was answered, and the preset - /// the mode had when it was applied. Without `preset` the stored one stays while the mode - /// stays, and is forgotten when the mode changes. `existing` stays what native code decided. - pub fn chosen(&self, mode: Option, onboarded: bool, preset: Option>) -> Result { - let preset = match preset { - Some(preset) => Some(preset), - None if mode == self.mode => self.preset.clone(), - None => None, - }; - Self { mode, onboarded, existing: self.existing, preset }.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, preset: None }); - let existing = ModeState::first_run(true); - let dismissed = existing.chosen(None, true, None).unwrap(); - assert_eq!(dismissed, ModeState { mode: None, onboarded: true, existing: true, preset: None }, "dismissed without choosing: nothing else changes"); - let chosen = dismissed.chosen(Some("power".into()), true, None).unwrap(); - assert_eq!(chosen.mode.as_deref(), Some("power")); - assert!(chosen.existing); - assert!(existing.chosen(Some(""]}"#, true); - assert!(script.contains(r#"!["x.com"].includes(location.host)"#), "{script}"); - assert!(script.contains("if (held >= 12) return;") && script.contains("sessionStorage.setItem(\"wayBetter.stringPacks\", \"{\\\"rev\\\":12")); - assert!(script.contains("location.reload();")); - assert!(!delivery_script(&["x.com"], r#"{"rev":1}"#, false).contains("reload")); - let _ = std::fs::remove_dir_all(&dir); - } -} diff --git a/crates/waybetter-host/src/store_commands.rs b/crates/waybetter-host/src/store_commands.rs deleted file mode 100644 index 8eae406..0000000 --- a/crates/waybetter-host/src/store_commands.rs +++ /dev/null @@ -1,205 +0,0 @@ -//! The store's Tauri commands for every app that sets [`crate::app::AppConfig::store`]: the -//! `waybetter://install` deep link, dropped files, the signed wayBetter Store and the install -//! screen's commands ([`crate::commands::STORE`]). Every command is shell-only; site tabs and web -//! pages have no way to install anything. A deep link only *proposes* an install: the shell shows -//! the confirmation screen and nothing is written until the owner confirms there. -//! -//! The rules, the catalog format and the install state are [`crate::store`]'s; this module only -//! wraps them. An app without a store configuration registers nothing and every command here -//! answers that it is not available. - -use crate::app::AppConfig; -use crate::host::{emit_shell, eval_in_site_tabs, shell_only}; -use crate::plugins::ScriptPlugin; -use crate::policy; -use crate::store::{delivery_script, InstallOutcome, InstallPreview, InstallRecords, LinkEvent, Store, StoreItemRef, StoreView, StringsList, EVENT_LINK}; -use tauri::{AppHandle, Manager, State, Webview}; -use tauri_plugin_deep_link::DeepLinkExt; - -/// Makes the [`Store`] for the app's configuration and listens for install links (launch argument, -/// open-URL event, a second launch forwarded by single-instance). -pub(crate) fn init(app: &AppHandle, config: &AppConfig) { - let Some(store) = config.store else { return }; - let dir = app.path().app_data_dir().unwrap_or_default(); - app.manage(Store::new(store, config.plugins, dir)); - // Windows installs register the scheme in the NSIS installer and macOS in Info.plist; a Linux - // AppImage and a Windows development build register it here (HKCU / xdg, current user only). - #[cfg(any(target_os = "linux", all(windows, debug_assertions)))] - if let Err(error) = app.deep_link().register_all() { - eprintln!("{}: deep link registration failed: {error}", config.title); - } - let handle = app.clone(); - app.deep_link().on_open_url(move |event| { - for url in event.urls() { - received(&handle, url.as_str()); - } - }); - // Launched by a link (Windows/Linux pass it as an argument; macOS as an open-URL event). - if let Ok(Some(urls)) = app.deep_link().get_current() { - for url in urls { - received(app, url.as_str()); - } - } -} - -/// A `waybetter://` link reached the app: validate it, queue it for the shell and bring the window -/// forward. Nothing is downloaded or installed until the shell's screen asks for it. -fn received(app: &AppHandle, raw: &str) { - let Some(store) = app.try_state::() else { return }; - emit_shell(app, EVENT_LINK, store.receive_link(raw)); - if let Some(window) = app.get_window(policy::MAIN_LABEL) { - let _ = window.unminimize(); - let _ = window.show(); - let _ = window.set_focus(); - } -} - -fn store(app: &AppHandle) -> Result, String> { - app.try_state::().ok_or_else(|| "UNAVAILABLE: this app has no store".to_owned()) -} - -fn eval_in_site(app: &AppHandle, script: &str) { - eval_in_site_tabs(app, crate::app::config(app).site, script); -} - -/// Links that arrived before the shell listened (drained). -#[tauri::command] -pub(crate) async fn install_pending(webview: Webview, app: AppHandle) -> Result, String> { - shell_only(&webview)?; - Ok(store(&app)?.take_pending()) -} - -/// Downloads what a validated install link points at and stages it for the confirmation screen. -#[tauri::command] -pub(crate) async fn install_stage_link(webview: Webview, app: AppHandle, kind: String, url: String) -> Result { - shell_only(&webview)?; - store(&app)?.stage_link(&kind, &url).await -} - -/// A file dropped on the window (the shell read it with the File API; native code validates it). -#[tauri::command] -pub(crate) async fn install_stage_file(webview: Webview, app: AppHandle, name: String, text: String) -> Result { - shell_only(&webview)?; - store(&app)?.stage_file(&name, text) -} - -#[tauri::command] -pub(crate) async fn install_cancel(webview: Webview, app: AppHandle, token: String) -> Result<(), String> { - shell_only(&webview)?; - store(&app)?.cancel(&token); - Ok(()) -} - -/// The owner confirmed the screen for `token`. Plugins are written (validated again) and, when -/// `enable` (or they were enabled before an update), started in every site tab. Themes are handed -/// back for the shell to add under `theme_id`. -#[tauri::command] -pub(crate) async fn install_commit( - webview: Webview, - app: AppHandle, - token: String, - enable: bool, - theme_id: Option, -) -> Result { - shell_only(&webview)?; - store(&app)?.commit(&token, enable, theme_id, |script| eval_in_site(&app, script)) -} - -/// Deletes a plugin (stopped in every site tab first). Shell-only, like every plugin command. -#[tauri::command] -pub(crate) async fn plugin_remove(webview: Webview, app: AppHandle, file: String) -> Result, String> { - shell_only(&webview)?; - store(&app)?.remove_plugin(&file, |script| eval_in_site(&app, script)) -} - -/// Where installed plugins and themes came from (for badges and update checks). -#[tauri::command] -pub(crate) async fn install_records(webview: Webview, app: AppHandle) -> Result { - shell_only(&webview)?; - Ok(store(&app)?.records()) -} - -/// A theme was removed in Appearance: forget where it came from. -#[tauri::command] -pub(crate) async fn install_forget(webview: Webview, app: AppHandle, kind: String, name: String) -> Result<(), String> { - shell_only(&webview)?; - store(&app)?.forget(&kind, &name) -} - -/// The signed catalog, this app's items only (fetched at most every 10 minutes unless `refresh`), -/// with what is installed. -#[tauri::command] -pub(crate) async fn store_catalog(webview: Webview, app: AppHandle, refresh: bool) -> Result { - shell_only(&webview)?; - Ok(store(&app)?.catalog(refresh).await) -} - -/// Downloads a store item, checks it against the signed catalog (size + sha256) and stages it. -#[tauri::command] -pub(crate) async fn store_stage(webview: Webview, app: AppHandle, item: StoreItemRef) -> Result { - shell_only(&webview)?; - store(&app)?.stage_item(&item).await -} - -/// Installed string packs, in application order, with which are on. -#[tauri::command] -pub(crate) async fn strings_list(webview: Webview, app: AppHandle) -> Result { - shell_only(&webview)?; - Ok(store(&app)?.strings().list()) -} - -/// One installed string pack's JSON (the shell checks it against the site's inventory). -#[tauri::command] -pub(crate) async fn strings_read(webview: Webview, app: AppHandle, id: String) -> Result { - shell_only(&webview)?; - let bytes = store(&app)?.strings().read(&id).ok_or("STRINGS: no such string pack")?; - String::from_utf8(bytes).map_err(|_| "STRINGS: not UTF-8".to_owned()) -} - -/// Sets the order of the installed string packs and which are on (at most 8). -#[tauri::command] -pub(crate) async fn strings_set(webview: Webview, app: AppHandle, order: Vec, enabled: Vec) -> Result { - shell_only(&webview)?; - store(&app)?.strings().set(&order, &enabled) -} - -/// Removes an installed string pack. -#[tauri::command] -pub(crate) async fn strings_remove(webview: Webview, app: AppHandle, id: String) -> Result { - shell_only(&webview)?; - store(&app)?.remove_strings(&id) -} - -/// The shell computed what site tabs get (the packs that are on, in order, with the slice of the -/// site's inventory their keys need; `None`: no pack on). It is kept for new tabs, and every site -/// tab gets it in its session storage and reloads, so X registers its strings through it from the -/// start. Data only; a site tab gains no command. -#[tauri::command] -pub(crate) async fn strings_apply(webview: Webview, app: AppHandle, delivery: Option) -> Result<(), String> { - shell_only(&webview)?; - let rev = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0); - let stored = store(&app)?.strings().set_delivery(delivery.as_deref(), rev)?; - eval_in_site(&app, &delivery_script(crate::app::config(&app).site.hosts, &stored, true)); - Ok(()) -} - -/// The store's commands ([`crate::commands::STORE`]). -pub(crate) fn handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { - tauri::generate_handler![ - install_pending, - install_stage_link, - install_stage_file, - install_cancel, - install_commit, - plugin_remove, - install_records, - install_forget, - store_catalog, - store_stage, - strings_list, - strings_read, - strings_set, - strings_remove, - strings_apply - ] -} diff --git a/crates/waybetter-host/src/sync_commands.rs b/crates/waybetter-host/src/sync_commands.rs deleted file mode 100644 index 640ed53..0000000 --- a/crates/waybetter-host/src/sync_commands.rs +++ /dev/null @@ -1,369 +0,0 @@ -//! Saved workspaces and encrypted folder sync, native side ([`crate::commands::WORKSPACES`], -//! [`crate::commands::SYNC`]). Every command is shell-only. The format, the crypto and the -//! validation are [`crate::workspaces`]' and [`crate::sync`]'s (Argon2id + XChaCha20-Poly1305 -//! snapshots of the settings backup in a folder the owner picks); this module keeps the local -//! state (which folder, this device, the remembered key) and the dialogs. -//! -//! The synced settings are the app's own backup sections -//! ([`crate::app::SiteHooks::backup_sections`]) plus the shell's own storage (`decks`, `shell`), -//! never drafts, with secret-looking keys removed. The sync key lives in memory, or in app data -//! `sync-key.json` when the owner ticks "remember on this computer"; it is never part of a backup -//! or a snapshot. - -use crate::app::{hooks, tr}; -use crate::backup; -use crate::host::{data_file, read_json, shell_only, write_json}; -use crate::sync::{self, Key, SnapshotInfo}; -use crate::workspaces::{self, WorkspaceStore}; -use serde::{Deserialize, Serialize}; -use serde_json::{json, Map, Value}; -use sha2::{Digest, Sha256}; -use std::path::{Path, PathBuf}; -use std::sync::Mutex; -use tauri::{AppHandle, Manager, Webview}; -use tauri_plugin_dialog::DialogExt; - -const SYNC_FILE: &str = "sync.json"; -/// The remembered sync key. Never part of a backup or a snapshot. -const SYNC_KEY_FILE: &str = "sync-key.json"; - -/// The sync state (the unlocked key, and a lock that serializes pushes, pulls and unlocks). -#[derive(Default)] -pub(crate) struct SyncState { - key: Mutex>, - /// Serializes pushes, pulls and unlocks (file writes in the folder). - busy: Mutex<()>, -} - -/// Does nothing unless the app set [`crate::app::AppConfig::sync`]. -pub(crate) fn init(app: &AppHandle) { - if crate::app::config(app).sync { - app.manage(SyncState::default()); - } -} - -fn sync_state(app: &AppHandle) -> Result, String> { - app.try_state::().ok_or_else(|| "UNAVAILABLE: this app has no sync".to_owned()) -} - -// --------------------------------------------------------------------------------------------- -// Workspaces - -#[tauri::command] -pub(crate) async fn workspaces_get(webview: Webview, app: AppHandle) -> Result { - shell_only(&webview)?; - Ok(read_json::(&app, workspaces::FILE).and_then(|store| store.validated().ok()).unwrap_or_default()) -} - -#[tauri::command] -pub(crate) async fn workspaces_set(webview: Webview, app: AppHandle, store: WorkspaceStore) -> Result { - shell_only(&webview)?; - let store = store.validated()?; - write_json(&app, workspaces::FILE, &store)?; - Ok(store) -} - -// --------------------------------------------------------------------------------------------- -// Sync - -#[derive(Clone, Debug, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", default)] -struct SyncLocal { - /// The folder the owner picked (the snapshots live in `/wayBetter Sync`). - folder: Option, - device: String, - device_name: String, - /// Push automatically when settings change. - auto_push: bool, - /// Newest snapshot of another device that was pulled (or found equal to ours), ms. - last_pulled: u64, - /// sha256 of the settings last pushed (skip unchanged pushes). - last_pushed_hash: String, - last_pushed_at: u64, -} - -fn load_sync(app: &AppHandle) -> Result { - let mut local = read_json::(app, SYNC_FILE).unwrap_or_default(); - if !sync::valid_device(&local.device) { - local.device = sync::new_device_id()?; - local.device_name = std::env::var("COMPUTERNAME").or_else(|_| std::env::var("HOSTNAME")).unwrap_or_else(|_| "This computer".into()); - local.auto_push = true; - write_json(app, SYNC_FILE, &local)?; - } - Ok(local) -} - -fn sync_folder(local: &SyncLocal) -> Option { - local.folder.as_deref().map(|folder| sync::sync_dir(Path::new(folder))) -} - -fn current_key(app: &AppHandle, local: &SyncLocal) -> Option { - let state = sync_state(app).ok()?; - let mut key = state.key.lock().ok()?; - if key.is_none() { - // A remembered key, if it still opens this folder. - let remembered = read_json::(app, SYNC_KEY_FILE).and_then(|value| value.get("key").and_then(Value::as_str).and_then(Key::from_base64)); - if let (Some(remembered), Some(dir)) = (remembered, sync_folder(local)) { - if sync::key_matches(&dir, &remembered) { - *key = Some(remembered); - } - } - } - key.clone() -} - -#[derive(Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct SyncStatus { - folder: Option, - device: String, - device_name: String, - auto_push: bool, - /// The folder already holds a sync setup (unlock with its passphrase) or not (choose one). - initialized: bool, - unlocked: bool, - remembered: bool, - last_pushed_at: u64, - last_pulled: u64, - snapshots: Vec, - error: Option, -} - -fn status(app: &AppHandle) -> Result { - let local = load_sync(app)?; - let dir = sync_folder(&local); - let (initialized, error) = match &dir { - Some(dir) => match sync::read_meta(dir) { - Ok(meta) => (meta.is_some(), None), - Err(error) => (false, Some(error)), - }, - None => (false, None), - }; - let unlocked = dir.is_some() && current_key(app, &local).is_some(); - Ok(SyncStatus { - folder: local.folder.clone(), - device: local.device.clone(), - device_name: local.device_name.clone(), - auto_push: local.auto_push, - initialized, - unlocked, - remembered: data_file(app, SYNC_KEY_FILE).is_some_and(|path| path.exists()), - last_pushed_at: local.last_pushed_at, - last_pulled: local.last_pulled, - snapshots: dir.map(|dir| sync::list(&dir).into_iter().take(20).collect()).unwrap_or_default(), - error, - }) -} - -fn forget_key(app: &AppHandle) { - if let Ok(state) = sync_state(app) { - if let Ok(mut key) = state.key.lock() { - *key = None; - } - } - if let Some(path) = data_file(app, SYNC_KEY_FILE) { - let _ = std::fs::remove_file(path); - } -} - -/// The app's backup sections plus the shell's own storage (`decks`, `shell`), never drafts, -/// secret-looking keys removed: what sync carries. -fn collect(app: &AppHandle, extra: Option>) -> Result, String> { - let mut sections = hooks(app).backup_sections(app)?; - for (key, value) in extra.unwrap_or_default() { - // The shell only adds its own storage; it cannot replace a native section or add drafts. - if (key == "decks" || key == "shell") && value.is_object() { - sections.insert(key, value); - } - } - let mut value = Value::Object(sections); - backup::strip_secrets(&mut value); - Ok(match value { - Value::Object(map) => map, - _ => Map::new(), - }) -} - -fn hash(bytes: &[u8]) -> String { - Sha256::digest(bytes).iter().map(|byte| format!("{byte:02x}")).collect() -} - -#[tauri::command] -pub(crate) async fn sync_status(webview: Webview, app: AppHandle) -> Result { - shell_only(&webview)?; - status(&app) -} - -/// Picks the folder to sync through (e.g. a OneDrive/iCloud/Dropbox folder). Locks until unlocked. -#[tauri::command] -pub(crate) async fn sync_choose_folder(webview: Webview, app: AppHandle) -> Result { - shell_only(&webview)?; - let title = tr(&app, "native.dialog.syncFolder", "Choose a folder to sync wayBetter settings through"); - let picked = app.dialog().file().set_parent(&webview.window()).set_title(title).blocking_pick_folder(); - let Some(picked) = picked else { return status(&app) }; - let path = picked.into_path().map_err(|_| "SYNC: not a local folder")?; - let mut local = load_sync(&app)?; - local.folder = Some(path.to_string_lossy().into_owned()); - local.last_pulled = 0; - local.last_pushed_hash.clear(); - write_json(&app, SYNC_FILE, &local)?; - forget_key(&app); - status(&app) -} - -/// Unlocks the folder with the passphrase (or sets the folder up with it the first time). -#[tauri::command] -pub(crate) async fn sync_unlock(webview: Webview, app: AppHandle, passphrase: String, remember: bool) -> Result { - shell_only(&webview)?; - let local = load_sync(&app)?; - let dir = sync_folder(&local).ok_or("SYNC: choose a folder first")?; - // Argon2id takes a moment on purpose; keep it off the async runtime's threads. - let task_app = app.clone(); - let key = tauri::async_runtime::spawn_blocking(move || { - let state = sync_state(&task_app)?; - let _busy = state.busy.lock().map_err(|_| "SYNC: busy".to_string())?; - sync::unlock_or_create(&dir, &passphrase, sync::KdfParams::default()) - }) - .await - .map_err(|_| "SYNC: unlock failed")?? - .0; - if remember { - write_json(&app, SYNC_KEY_FILE, &json!({ "key": key.to_base64() }))?; - #[cfg(unix)] - if let Some(path) = data_file(&app, SYNC_KEY_FILE) { - use std::os::unix::fs::PermissionsExt; - let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)); - } - } else if let Some(path) = data_file(&app, SYNC_KEY_FILE) { - let _ = std::fs::remove_file(path); - } - *sync_state(&app)?.key.lock().map_err(|_| "SYNC: busy")? = Some(key); - status(&app) -} - -#[tauri::command] -pub(crate) async fn sync_lock(webview: Webview, app: AppHandle) -> Result { - shell_only(&webview)?; - forget_key(&app); - status(&app) -} - -/// Stops syncing on this computer (the folder and its snapshots stay). -#[tauri::command] -pub(crate) async fn sync_disable(webview: Webview, app: AppHandle) -> Result { - shell_only(&webview)?; - let mut local = load_sync(&app)?; - local.folder = None; - write_json(&app, SYNC_FILE, &local)?; - forget_key(&app); - status(&app) -} - -#[tauri::command] -pub(crate) async fn sync_configure(webview: Webview, app: AppHandle, auto_push: bool, device_name: String) -> Result { - shell_only(&webview)?; - let mut local = load_sync(&app)?; - local.auto_push = auto_push; - let name: String = device_name.chars().filter(|ch| !ch.is_control()).take(40).collect(); - if !name.trim().is_empty() { - local.device_name = name.trim().to_owned(); - } - write_json(&app, SYNC_FILE, &local)?; - status(&app) -} - -#[derive(Serialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct PushResult { - pushed: bool, - name: Option, -} - -/// Writes an encrypted snapshot when the settings changed since the last push. `force` writes one -/// even when nothing changed (the "Sync now" button). `extra`: the shell's own sections (decks). -#[tauri::command] -pub(crate) async fn sync_push(webview: Webview, app: AppHandle, extra: Option>, force: bool) -> Result { - shell_only(&webview)?; - let mut local = load_sync(&app)?; - let dir = sync_folder(&local).ok_or("SYNC: choose a folder first")?; - if !force && !local.auto_push { - return Ok(PushResult { pushed: false, name: None }); - } - let key = current_key(&app, &local).ok_or("SYNC: locked; enter the passphrase")?; - let plaintext = sync::settings_plaintext(&collect(&app, extra)?); - let digest = hash(&plaintext); - if !force && digest == local.last_pushed_hash { - return Ok(PushResult { pushed: false, name: None }); - } - let state = sync_state(&app)?; - let _busy = state.busy.lock().map_err(|_| "SYNC: busy")?; - let now = chrono::Utc::now().timestamp_millis().max(0) as u64; - let name = sync::write_snapshot(&dir, &key, &local.device, &local.device_name, now, &plaintext)?; - local.last_pushed_hash = digest; - local.last_pushed_at = now; - write_json(&app, SYNC_FILE, &local)?; - Ok(PushResult { pushed: true, name: Some(name) }) -} - -/// The newest snapshot another computer wrote since the last pull, if its settings differ from -/// ours (one that equals ours is marked as seen). None when locked or nothing is newer. -#[tauri::command] -pub(crate) async fn sync_check(webview: Webview, app: AppHandle, extra: Option>) -> Result, String> { - shell_only(&webview)?; - let mut local = load_sync(&app)?; - let Some(dir) = sync_folder(&local) else { return Ok(None) }; - let Some(key) = current_key(&app, &local) else { return Ok(None) }; - let Some(newer) = sync::newer_from_others(&dir, &local.device, local.last_pulled) else { return Ok(None) }; - let (_, plaintext) = sync::read_snapshot(&dir, &key, &newer.name)?; - let ours = sync::settings_plaintext(&collect(&app, extra)?); - let theirs: Value = serde_json::from_slice(&plaintext).map_err(|_| "SYNC: damaged snapshot")?; - if serde_json::to_vec(&theirs).unwrap_or_default() == ours { - local.last_pulled = newer.created_at; - write_json(&app, SYNC_FILE, &local)?; - return Ok(None); - } - Ok(Some(newer)) -} - -/// Opens snapshot `name` for the import preview (nothing applied yet). -#[tauri::command] -pub(crate) async fn sync_open(webview: Webview, app: AppHandle, name: String) -> Result, String> { - shell_only(&webview)?; - let local = load_sync(&app)?; - let dir = sync_folder(&local).ok_or("SYNC: choose a folder first")?; - let key = current_key(&app, &local).ok_or("SYNC: locked; enter the passphrase")?; - let (_, plaintext) = sync::read_snapshot(&dir, &key, &name)?; - let wrapped = json!({ "format": backup::FORMAT, "version": backup::VERSION, "sections": serde_json::from_slice::(&plaintext).map_err(|_| "SYNC: damaged snapshot")? }); - backup::parse_backup(&serde_json::to_vec(&wrapped).map_err(|_| "SYNC: damaged snapshot")?, hooks(&app).backup_section_names()) -} - -/// Records that snapshot `name` was pulled (or skipped): it is not offered again. -#[tauri::command] -pub(crate) async fn sync_mark_pulled(webview: Webview, app: AppHandle, name: String) -> Result { - shell_only(&webview)?; - let mut local = load_sync(&app)?; - let created = sync_folder(&local).and_then(|dir| sync::list(&dir).into_iter().find(|info| info.name == name)).map(|info| info.created_at); - if let Some(created) = created { - local.last_pulled = local.last_pulled.max(created); - write_json(&app, SYNC_FILE, &local)?; - } - status(&app) -} - -/// The workspaces and sync commands ([`crate::commands::WORKSPACES`], [`crate::commands::SYNC`]). -pub(crate) fn handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { - tauri::generate_handler![ - workspaces_get, - workspaces_set, - sync_status, - sync_choose_folder, - sync_unlock, - sync_lock, - sync_disable, - sync_configure, - sync_push, - sync_check, - sync_open, - sync_mark_pulled - ] -} diff --git a/crates/waybetter-host/src/tabs.rs b/crates/waybetter-host/src/tabs.rs index cc0286c..a5b38fb 100644 --- a/crates/waybetter-host/src/tabs.rs +++ b/crates/waybetter-host/src/tabs.rs @@ -15,7 +15,7 @@ pub const EVENT_PROFILES_CHANGED: &str = "profiles-changed"; pub const EVENT_OPEN_PANEL: &str = "open-panel"; /// One pane as the shell lays it out (`tabs_sync`). -#[derive(Clone, Debug, Deserialize)] +#[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TabLayout { pub id: String, @@ -159,7 +159,6 @@ pub fn new_window_mode<'a>(on_site: bool, site_mode: &'a str, external_mode: &'a pub const SHORTCUTS: &[&str] = &[ "command-palette", "new-tab", "close-tab", "reopen-tab", "focus-address", "next-tab", "prev-tab", "reload", "back", "forward", "split-right", "split-down", "open-panel", "find", "hard-reload", - "app-menu", "zoom-in", "zoom-out", "zoom-reset", "column-prev", "column-next", "column-1", "column-2", "column-3", "column-4", "column-5", "column-6", "column-7", "column-8", "column-9", "column-page-prev", "column-page-next", "column-mark-read", "deck-compose", "deck-toggle", ]; diff --git a/crates/waybetter-host/src/testkit.rs b/crates/waybetter-host/src/testkit.rs index db75681..50dc896 100644 --- a/crates/waybetter-host/src/testkit.rs +++ b/crates/waybetter-host/src/testkit.rs @@ -125,14 +125,6 @@ impl Capabilities { } } - /// Every command of an optional group (e.g. [`commands::STORE`]) is granted, and only to the - /// local shell webview. - pub fn assert_shell_only_group(&self, group: &[&str]) { - for command in group { - self.assert_shell_only(command); - } - } - /// `command` is granted to no capability at all. pub fn assert_not_granted(&self, command: &str) { let permission = commands::permission(command); @@ -211,77 +203,10 @@ pub fn assert_host_guards() { } } -/// The store commands' wrappers check their caller first. Runs against the host's source. -pub fn assert_store_guards() { - let source = include_str!("store_commands.rs"); - for command in commands::STORE { - assert_guarded(source, command, "shell_only(&webview)?"); - } -} - -/// The media commands' wrappers check their caller first. Runs against the host's source. -pub fn assert_media_guards() { - let source = include_str!("media_commands.rs"); - for command in commands::MEDIA { - assert_guarded(source, command, "shell_only(&webview)?"); - } -} - -/// The fonts commands' wrappers check their caller first. Runs against the host's source. -pub fn assert_fonts_guards() { - let source = include_str!("fonts_commands.rs"); - for command in commands::GFONTS { - assert_guarded(source, command, "shell_only(&webview)?"); - } -} - -/// The update commands' wrappers check their caller first. Runs against the host's source. -pub fn assert_update_guards() { - let source = include_str!("update_commands.rs"); - for command in commands::UPDATE { - assert_guarded(source, command, "shell_only(&webview)?"); - } -} - -/// The workspaces and sync commands' wrappers check their caller first. Runs against the host's source. -pub fn assert_sync_guards() { - let source = include_str!("sync_commands.rs"); - for command in commands::WORKSPACES.iter().chain(commands::SYNC) { - assert_guarded(source, command, "shell_only(&webview)?"); - } -} - -/// The developer-mode commands' wrappers check their caller first. Runs against the host's source. -pub fn assert_dev_guards() { - let source = include_str!("dev_commands.rs"); - for command in commands::DEV { - assert_guarded(source, command, "shell_only(&webview)?"); - } -} - -/// The backup commands' wrappers check their caller first. Runs against the host's source. -pub fn assert_backup_guards() { - let source = include_str!("backup_commands.rs"); - for command in commands::BACKUP { - assert_guarded(source, command, "shell_only(&webview)?"); - } -} - #[cfg(test)] mod tests { use super::*; - #[test] - fn the_store_commands_check_their_caller_first() { - assert_store_guards(); - assert_media_guards(); - assert_fonts_guards(); - assert_update_guards(); - assert_sync_guards(); - assert_dev_guards(); - assert_backup_guards(); - } - fn caps_with(shell_extra: &str, tab_extra: &str, site_extra: &str) -> Capabilities { let host_shell: Vec = commands::SHELL.iter().map(|c| format!("\"{}\"", commands::permission(c))).collect(); let host_tab: Vec = commands::TAB.iter().map(|c| format!("\"{}\"", commands::permission(c))).collect(); diff --git a/crates/waybetter-host/src/theme.rs b/crates/waybetter-host/src/theme.rs index 9e49b21..dfd5425 100644 --- a/crates/waybetter-host/src/theme.rs +++ b/crates/waybetter-host/src/theme.rs @@ -41,11 +41,8 @@ pub const MAX_THEME_BYTES: usize = 1_200_000; pub const MAX_TOTAL_BYTES: usize = 4_000_000; /// Theme names: 1-60 characters (`theme.schema.json` `name`). pub const MAX_NAME_CHARS: usize = 60; -/// Icon packs the owner imported (theme engine v2), each a standalone pack document. -pub const MAX_PACKS: usize = 8; -pub const MAX_PACK_BYTES: usize = 150_000; /// Override groups the panel may change on top of a theme. -pub const OVERRIDE_KEYS: [&str; 8] = ["font", "shape", "layout", "background", "effects", "colors", "css", "variants"]; +pub const OVERRIDE_KEYS: [&str; 7] = ["font", "shape", "layout", "background", "effects", "colors", "css"]; /// The theme applied to the site's tabs: a theme id (built-in or one of `themes`), an optional /// accent, per-group overrides from the panel and the owner's imported theme documents. @@ -59,14 +56,6 @@ pub struct ThemeChoice { pub overrides: Map, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub themes: Vec, - /// The owner's icon pack: absent follows the theme's suggestion, `site` keeps the site's own icons, - /// otherwise a pack id (theme engine v2). A slug; an unknown pack falls back to the site's icons in the page. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub icons: Option, - /// Icon packs the owner imported: data documents (path data, colored layers, small PNGs), checked - /// again by the page runtime's sanitizer; here only their shape and size. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub packs: Vec, } /// A theme id: a lowercase slug of 1-40 characters (`theme.schema.json` `id`). @@ -86,7 +75,7 @@ fn doc_id(theme: &Value) -> Option<&str> { impl ThemeChoice { /// The site's own look, nothing customized. pub fn default_for(site: &ThemeSite) -> Self { - Self { preset: site.own().into(), accent: None, overrides: Map::new(), themes: Vec::new(), icons: None, packs: Vec::new() } + Self { preset: site.own().into(), accent: None, overrides: Map::new(), themes: Vec::new() } } pub fn validate(&self, site: &ThemeSite) -> Result<(), String> { @@ -95,27 +84,6 @@ impl ThemeChoice { return Err("VALIDATION: accent must use six-digit hex".into()); } } - if let Some(icons) = &self.icons { - if !valid_id(icons) { - return Err("VALIDATION: an icon pack id is a lowercase slug".into()); - } - } - if self.packs.len() > MAX_PACKS { - return Err("VALIDATION: too many icon packs".into()); - } - let mut pack_ids: Vec<&str> = Vec::new(); - for pack in &self.packs { - let object = pack.as_object().ok_or("VALIDATION: an icon pack must be an object")?; - let id = object.get("id").and_then(Value::as_str).ok_or("VALIDATION: an icon pack needs an id")?; - let name = object.get("name").and_then(Value::as_str).ok_or("VALIDATION: an icon pack needs a name")?; - if !valid_id(id) || pack_ids.contains(&id) || name.trim().is_empty() || name.chars().count() > MAX_NAME_CHARS || !object.get("glyphs").is_some_and(Value::is_object) { - return Err("VALIDATION: icon packs have unique slug ids, a name and glyphs".into()); - } - if serde_json::to_vec(pack).map(|bytes| bytes.len()).unwrap_or(usize::MAX) > MAX_PACK_BYTES { - return Err("VALIDATION: icon pack is too large".into()); - } - pack_ids.push(id); - } if self.themes.len() > MAX_THEMES { return Err("VALIDATION: too many themes".into()); } @@ -152,7 +120,7 @@ impl ThemeChoice { /// True when the site keeps its own look (nothing to apply). Imported themes are kept in the /// file even while the site's own look is selected, so this only looks at what is applied. pub fn is_default(&self, site: &ThemeSite) -> bool { - self.preset == site.own() && self.accent.is_none() && self.overrides.is_empty() && self.icons.is_none() + self.preset == site.own() && self.accent.is_none() && self.overrides.is_empty() } /// Nothing worth persisting: the site's own look and no imported themes. @@ -171,7 +139,7 @@ impl ThemeChoice { let base = if id == self.preset || !self.knows(site, id) { self.clone() } else { - ThemeChoice { preset: id.into(), accent: None, overrides: Map::new(), themes: self.themes.clone(), icons: self.icons.clone(), packs: self.packs.clone() } + ThemeChoice { preset: id.into(), accent: None, overrides: Map::new(), themes: self.themes.clone() } }; let preset = base.preset.clone(); let themes = base.themes.into_iter().filter(|theme| doc_id(theme) == Some(preset.as_str())).collect(); @@ -336,24 +304,6 @@ mod tests { assert_eq!(imported.page_color(&SITE), Some((0xab, 0xcd, 0xef)), "an invalid page color falls back to bg"); } - #[test] - fn icon_choice_is_a_slug_and_counts_as_a_choice() { - let picked = with(json!({ "preset": "site", "icons": "wb-pixel" })).unwrap(); - assert_eq!(picked.icons.as_deref(), Some("wb-pixel")); - assert!(!picked.is_default(&SITE), "an icon pick is applied even on the site's own look"); - assert!(with(json!({ "preset": "site", "icons": "Bad Pack!" })).is_err()); - assert!(with(json!({ "preset": "site", "overrides": { "variants": { "nav": "top" } } })).is_ok(), "layout variants are an override group"); - assert_eq!(picked.for_theme(&SITE, "nord").icons.as_deref(), Some("wb-pixel"), "the icon pick is global"); - let pack = json!({ "id": "retro", "name": "Retro", "glyphs": { "home": { "d": "M0 0h1" } } }); - let with_pack = with(json!({ "preset": "site", "icons": "retro", "packs": [pack.clone()] })).unwrap(); - assert_eq!(with_pack.packs.len(), 1); - assert_eq!(with_pack.for_theme(&SITE, "nord").packs.len(), 1, "imported packs are global"); - assert!(with(json!({ "preset": "site", "packs": [pack.clone(), pack] })).is_err(), "pack ids are unique"); - assert!(with(json!({ "preset": "site", "packs": [{ "id": "x", "name": "X" }] })).is_err(), "a pack has glyphs"); - let big = json!({ "id": "big", "name": "Big", "glyphs": { "home": { "d": "M".repeat(MAX_PACK_BYTES) } } }); - assert!(with(json!({ "preset": "site", "packs": [big] })).is_err(), "a pack is bounded"); - } - #[test] fn user_themes_and_overrides_are_bounded() { let ok = with(json!({ "preset": "mine", "themes": [{ "id": "mine", "name": "Mine", "colors": null }], "overrides": { "font": { "scale": 1.1 } } })).unwrap(); diff --git a/crates/waybetter-host/src/update.rs b/crates/waybetter-host/src/update.rs index 504f206..86123f0 100644 --- a/crates/waybetter-host/src/update.rs +++ b/crates/waybetter-host/src/update.rs @@ -14,16 +14,6 @@ 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 { @@ -86,16 +76,6 @@ 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/update_commands.rs b/crates/waybetter-host/src/update_commands.rs deleted file mode 100644 index 725f77c..0000000 --- a/crates/waybetter-host/src/update_commands.rs +++ /dev/null @@ -1,53 +0,0 @@ -//! Native updates, for every app that sets [`crate::app::AppConfig::updates`]: the shell's four -//! narrow commands ([`crate::commands::UPDATE`]) over [`crate::updater`] (signed native updates and -//! the signed data-only hotfix channel, configured by the app's [`crate::updater::UpdaterConfig`]). -//! Everything runs in Rust; site tabs get no updater IPC at all, only the verified hotfix data the -//! app injects ([`crate::updater::hotfix_script`]). - -use crate::app::config; -use crate::host::shell_only; -use crate::update::UpdateStatus; -use crate::updater; -use tauri::{AppHandle, Webview}; - -/// Runs the launch handshake, loads the cached hotfix and starts the update loop. Does nothing -/// unless the app set [`crate::app::AppConfig::updates`]. -pub(crate) fn init(app: &AppHandle) { - if let Some(updates) = config(app).updates { - updater::init(app, updates); - } -} - -#[tauri::command] -pub(crate) async fn update_status(webview: Webview, app: AppHandle) -> Result { - shell_only(&webview)?; - updater::status(&app) -} - -/// "Check for updates" in the app menu: the same check the timer runs, once, now (the same updater -/// endpoint; never queued, never retried). Returns the status when the check has finished. -#[tauri::command] -pub(crate) async fn update_check(webview: Webview, app: AppHandle) -> Result { - shell_only(&webview)?; - updater::check_now(&app).await -} - -/// Installs the downloaded update and restarts. On Windows the quiet NSIS installer replaces -/// the app and relaunches it (`/UPDATE /R`), and this process exits inside `install`. -#[tauri::command] -pub(crate) async fn apply_update(webview: Webview, app: AppHandle) -> Result<(), String> { - shell_only(&webview)?; - updater::apply(&app) -} - -/// The shell reached a working state: confirms a just-installed update and returns the status. -#[tauri::command] -pub(crate) async fn app_ready(webview: Webview, app: AppHandle) -> Result { - shell_only(&webview)?; - updater::ready(&app) -} - -/// The update commands ([`crate::commands::UPDATE`]). -pub(crate) fn handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { - tauri::generate_handler![update_status, update_check, apply_update, app_ready] -} diff --git a/crates/waybetter-host/src/updater.rs b/crates/waybetter-host/src/updater.rs index ab5f4b4..d80ac1b 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`], [`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 +//! 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 //! ([`hotfix_script`]). use crate::hotfix::{self, Hotfix, Outcome}; @@ -23,7 +23,6 @@ const HOTFIX_SIG_FILE: &str = "hotfix.json.sig"; /// What differs between apps: the hotfix channel, the page names hotfix data is delivered under, /// the manual download page and what to do when an update is ready. -#[derive(Debug)] pub struct UpdaterConfig { /// Hotfix data goes to this site's tabs. pub site: &'static SiteSpec, @@ -50,10 +49,6 @@ 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 { @@ -116,48 +111,13 @@ pub fn init(app: &AppHandle, config: &'static UpdaterConfig) { tauri::async_runtime::spawn(async move { tokio::time::sleep(update::FIRST_CHECK).await; loop { - check_once(&app).await; + check_native(&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/crates/waybetter-host/src/zoom.rs b/crates/waybetter-host/src/zoom.rs deleted file mode 100644 index 265d8c9..0000000 --- a/crates/waybetter-host/src/zoom.rs +++ /dev/null @@ -1,139 +0,0 @@ -//! Page zoom per tab. The shell alone sets it (`tab_zoom {id, factor}`, shell-only): the factor is -//! a plain number, clamped to 25%..500% and rounded to whole percent, applied natively to that -//! tab's webview (the engine's own page zoom, never CSS) and remembered per tab id in app data -//! `zoom.json`, so a tab keeps its zoom when its webview is created again (a restart with session -//! restore, a profile change). A tab at 100% has no entry; a closed tab's entry goes with it. - -use serde::{Deserialize, Serialize}; -use std::collections::BTreeMap; - -pub const ZOOM_FILE: &str = "zoom.json"; -/// 25%: below this a page is unreadable and engines start refusing. -pub const MIN: f64 = 0.25; -/// 500%: the most the engines accept. -pub const MAX: f64 = 5.0; -pub const DEFAULT: f64 = 1.0; -/// Remembered tabs at most; past this the file is of no use and only grows. -pub const MAX_TABS: usize = 512; - -/// The factor the host applies for a requested one: a finite number, clamped to [`MIN`]..[`MAX`] -/// and rounded to whole percent (so 110% is 1.1, not 1.1000000000000001). -pub fn normalize(factor: f64) -> Result { - if !factor.is_finite() { - return Err("VALIDATION: zoom is not a number".into()); - } - Ok((factor.clamp(MIN, MAX) * 100.0).round() / 100.0) -} - -/// The remembered factors by tab id (`zoom.json`). Only tabs away from 100% are kept. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(transparent)] -pub struct ZoomMap(BTreeMap); - -impl ZoomMap { - /// What was read from disk, made safe: valid tab ids only, every factor normalized, bounded. - pub fn validated(self) -> Self { - let mut out = BTreeMap::new(); - for (id, factor) in self.0 { - if out.len() >= MAX_TABS { - break; - } - if let (true, Ok(factor)) = (crate::policy::valid_tab_id(&id), normalize(factor)) { - if factor != DEFAULT { - out.insert(id, factor); - } - } - } - Self(out) - } - - /// The factor tab `id` shows (100% when nothing is remembered). - pub fn get(&self, id: &str) -> f64 { - self.0.get(id).copied().unwrap_or(DEFAULT) - } - - /// Remembers `factor` for tab `id` and returns the factor in effect. 100% forgets the tab. - pub fn set(&mut self, id: &str, factor: f64) -> Result { - if !crate::policy::valid_tab_id(id) { - return Err("VALIDATION: invalid tab id".into()); - } - let factor = normalize(factor)?; - if factor == DEFAULT { - self.0.remove(id); - } else { - if !self.0.contains_key(id) && self.0.len() >= MAX_TABS { - return Err("VALIDATION: too many zoomed tabs".into()); - } - self.0.insert(id.to_owned(), factor); - } - Ok(factor) - } - - /// A closed tab: true when something was remembered for it (the file changes). - pub fn forget(&mut self, id: &str) -> bool { - self.0.remove(id).is_some() - } - - pub fn len(&self) -> usize { - self.0.len() - } - - pub fn is_empty(&self) -> bool { - self.0.is_empty() - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn factors_are_clamped_and_rounded_and_must_be_numbers() { - assert_eq!(normalize(1.0).unwrap(), 1.0); - assert_eq!(normalize(1.1000000000000001).unwrap(), 1.1); - assert_eq!(normalize(0.666).unwrap(), 0.67); - assert_eq!(normalize(0.01).unwrap(), MIN, "never below 25%"); - assert_eq!(normalize(-3.0).unwrap(), MIN); - assert_eq!(normalize(40.0).unwrap(), MAX, "never above 500%"); - for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { - assert!(normalize(bad).is_err(), "{bad}"); - } - } - - #[test] - fn a_tab_keeps_its_zoom_until_it_is_reset_or_closed() { - let mut map = ZoomMap::default(); - assert_eq!(map.get("t1"), 1.0); - assert_eq!(map.set("t1", 1.25).unwrap(), 1.25); - assert_eq!(map.set("t2", 9.0).unwrap(), 5.0); - assert_eq!((map.get("t1"), map.get("t2"), map.len()), (1.25, 5.0, 2)); - // 100% is the absence of an entry. - assert_eq!(map.set("t1", 1.0).unwrap(), 1.0); - assert_eq!(map.len(), 1); - assert!(map.forget("t2") && !map.forget("t2")); - assert!(map.is_empty()); - // Only tab ids the host itself accepts. - assert!(map.set("../x", 1.5).is_err()); - assert!(map.set("t1", f64::NAN).is_err()); - assert!(map.is_empty()); - } - - #[test] - fn the_file_is_data_and_is_bounded() { - let mut map = ZoomMap::default(); - map.set("t1", 1.5).unwrap(); - let json = serde_json::to_string(&map).unwrap(); - assert_eq!(json, r#"{"t1":1.5}"#); - assert_eq!(serde_json::from_str::(&json).unwrap().validated(), map); - // A hand-edited file: bad ids and neutral entries are dropped, factors are clamped. - let read = serde_json::from_str::(r#"{"t1":99,"t2":1,"bad id!":2,"t3":0.001}"#).unwrap().validated(); - assert_eq!((read.get("t1"), read.get("t2"), read.get("t3"), read.len()), (5.0, 1.0, 0.25, 2)); - assert!(serde_json::from_str::(r#"{"t1":"big"}"#).is_err()); - for n in 0..MAX_TABS { - map.set(&format!("x{n}"), 2.0).unwrap_or(0.0); - } - assert_eq!(map.len(), MAX_TABS); - assert!(map.set("one-more", 2.0).is_err(), "bounded"); - assert_eq!(map.set("t1", 3.0).unwrap(), 3.0, "a remembered tab can still change"); - } -} diff --git a/crates/waybetter-host/tab-bridge.js b/crates/waybetter-host/tab-bridge.js index 355c52a..e094986 100644 --- a/crates/waybetter-host/tab-bridge.js +++ b/crates/waybetter-host/tab-bridge.js @@ -85,21 +85,12 @@ 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. if (event.code === 'Backslash' || event.code === 'IntlBackslash') return event.shiftKey ? 'split-down' : 'split-right'; - // Page zoom is the shell's (`tab_zoom`): this tab only says which key was pressed. - if (key === '=' || key === '+' || event.code === 'NumpadAdd') return 'zoom-in'; - if (key === '-' || event.code === 'NumpadSubtract') return 'zoom-out'; - if (key === '0' || event.code === 'Numpad0') return 'zoom-reset'; } if (key === 'f5') return 'reload'; - // The app menu, like a browser's: F10, and Alt+F where Alt is not a typing key (not on macOS). - if (key === 'f10' && !mod && !event.altKey && !event.shiftKey) return 'app-menu'; - if (event.altKey && !mod && !event.shiftKey && event.code === 'KeyF' && !/Mac/i.test(navigator.platform)) return 'app-menu'; if (event.altKey && !mod && key === 'arrowleft') return 'back'; if (event.altKey && !mod && key === 'arrowright') return 'forward'; return null; diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md deleted file mode 100644 index 52905e6..0000000 --- a/docs/ARCHITECTURE.md +++ /dev/null @@ -1,564 +0,0 @@ -# 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`. - -Besides the commands above, the host serves optional groups of shell-only commands that an app turns -on with `AppConfig::with_*` (see "Optional command groups" in the README): `commands::STORE`, -`MEDIA`, `GFONTS`, `UPDATE`, `SYNC`, `DEV`, `WORKSPACES` and `BACKUP`, with the `SiteHooks` methods -that carry what only the app knows (`fonts_changed`, `backup_sections`, `backup_section_names`, -`backup_drafts`, `backup_apply`, `dev_theme_apply`, `dev_theme_end`). The app keeps its own -`#[tauri::command]` wrappers for everything site-specific, 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`). 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 - -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/docs/STORE.md b/docs/STORE.md index 58273ac..184459f 100644 --- a/docs/STORE.md +++ b/docs/STORE.md @@ -34,15 +34,13 @@ JSON Schema: `waybetter/store-catalog.schema.json` (npm package). The rules apps | --- | --- | | `format` | `2`. An app that reads another format says "update the app". Format 1 (before `apps`) is gone. | | `apps` | 1–16 distinct app ids (`[a-z0-9-]{1,32}`), e.g. `"x"`; an item for several apps lists each. | -| `kind`, `id` | `theme`, `plugin` or `strings` (a string pack, docs/STRING-PACKS.md); `[a-z0-9-]{1,40}`, unique per app and kind. | +| `kind`, `id` | `theme` or `plugin`; `[a-z0-9-]{1,40}`, unique per app and kind. | | `name`, `author`, `version`, `description`, `category`, `tags` | plain text (no control characters), ≤ 60 / 60 / 32 / 600 / 32 characters, ≤ 12 tags of ≤ 32. Known categories show in the reader's language (`wb.store.category.*`). | | `url`, `preview` | https; for the reading app's own items, on its download hosts (below). | | `file` | plugins only: `name.plugin.js` (letters, digits, `-_. `), unique per app ignoring case. | | `sha256`, `size` | of the exact file; size 1 byte … 2 MiB. | | `permissions` | plugins only: the header's `@permissions` (`null` = no line, legacy). | | `colors` | themes only: `#rrggbb` swatches for the card. | -| `language` | string packs only, required: the pack's language tag. | -| `license`, `credits` | any kind, optional: its licence (≤ 60 characters, e.g. an SPDX id) and who made, translated or reviewed it (≤ 600). The install screen shows them. | Also refused: unknown fields anywhere, more than 500 items, a catalog over 1 MiB, a signature file over 512 bytes. A malformed item for another app refuses the whole catalog (one file, one set of diff --git a/docs/STRING-PACKS.md b/docs/STRING-PACKS.md deleted file mode 100644 index abd88f0..0000000 --- a/docs/STRING-PACKS.md +++ /dev/null @@ -1,186 +0,0 @@ -# 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. The framework has the formats, the validator, -the application engine, the hook interface, `waybetter strings check`, the Store kind `strings` -with its install screen, the Languages section and translate mode. Sentences with element slots -(rich text) cannot be replaced 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 compact form: ids and shapes, no hashes. A page does not need -the whole inventory: `sliceInventory(inventory, ids)` is the part that the packs' keys need, and it -travels to the page together with the packs (`isPageInventory` checks its shape on arrival). The -full inventory stays where packs are installed and checked. - -## 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. - -## Installing and turning packs on - -String packs are a Store kind (`kind: "strings"`, with `language`; every item may also carry -`license` and `credits`) and install like themes and plugins: a dropped `*.strings.json`, a -`waybetter://install?kind=strings&url=…` link or the signed Store, always through the install screen. -The screen shows the pack's language, its coverage against the site's inventory, what is ignored -and what cannot be replaced yet, a sample of its text, that it is data only, and the pack file. - -Native code (waybetter-host `store::strings`) only keeps data: it checks the envelope and that every -value is plain text, writes `/strings/.json` and remembers the order and which packs -are on (at most 8). It never sees the inventory. Shell-only commands: `strings_list`, -`strings_read`, `strings_set {order, enabled}`, `strings_remove {id}`, `strings_apply {delivery}`. - -The shell builds the delivery (`buildDelivery`: the packs that are on, in order, with the slice of -the inventory their keys need) and hands it to `strings_apply`. Native code stores it under a new -revision and puts it into every site tab's session storage (`wayBetter.stringPacks`) with a -data-only script that checks `https:` and the site's own hosts, then reloads the tab; a new tab -gets the same script as the first document-start layer. Safe mode leaves the layer out. A tab keeps -the newest revision it was given. The page runtime reads the delivery at document start, before -the site's scripts. - -The Languages section of the panel (`createStringPacksSection({ inventory })`) lists the installed -packs with their coverage, turns them on and off, orders and removes them. - -## Translate mode - -Switched on in the Languages section. The delivery then carries the whole inventory, packs or not, -and the page runtime marks every replaceable string with an invisible marker naming its key -(`createMarker`). A bar at the bottom of each site tab says so; a click on a word opens an editor -with the key, the current text and its parameters. An edit is checked with the pack rules -(`checkEdit`) and kept in the tab's draft (`wayBetter.translateDraft`), which applies as the last -pack after a reload. "Copy pack file" copies the draft as a pack document. "Leave" turns the mode -off for that tab. The markers can reach places that compare text exactly (the window title), so the -mode is for authors only and is never on by default. diff --git a/packages/create-waybetter/README.md b/packages/create-waybetter/README.md index 0ae43bb..3d9f921 100644 --- a/packages/create-waybetter/README.md +++ b/packages/create-waybetter/README.md @@ -6,9 +6,7 @@ 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+. 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. +when run in a terminal; every answer is also a flag. No dependencies, Node 18.3+. ## Plugin @@ -42,14 +40,10 @@ Presets: `midnight`, `paper`, `dusk`. Import it in **wayBetter → Appearance ## App ```sh -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" +npm create waybetter app -- --site kick.com +npm create waybetter app -- --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/create-waybetter/src/app.js b/packages/create-waybetter/src/app.js index 88f62aa..b1651a4 100644 --- a/packages/create-waybetter/src/app.js +++ b/packages/create-waybetter/src/app.js @@ -151,9 +151,9 @@ const COMMANDS = { */ export const HOST_COMMANDS = { shell: [ - 'tabs_sync', 'tab_navigate', 'tab_action', 'tab_zoom', 'tab_find', 'safe_mode_get', 'safe_mode_set', 'diag_get', 'diag_log', 'open_external_url', 'shell_focus', 'shell_ready', 'tab_still_ready', 'shell_raise', 'window_system_menu', + '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', 'mode_get', 'mode_set', 'settings_get', 'settings_set', + 'plugins_list', 'plugin_set_enabled', 'plugins_open_folder', 'custom_css_get', 'custom_css_set', 'features_get', 'features_set', 'settings_get', 'settings_set', ], tab: ['tab_shortcut', 'tab_link_drag'], site: ['open_panel'], @@ -384,8 +384,6 @@ function pluginsRs(o) { ' example: Some(("example.plugin.js", include_str!("../../plugins/example.plugin.js"))),', ' // First-party plugins shipped with the app: written disabled, upgraded only while untouched.', ' bundled: &[],', - ' // Plugin files a later version turned into feature flags (waybetter_host::plugins::migrate).', - ' superseded: &[],', '};', '', '#[cfg(test)]', @@ -530,8 +528,7 @@ function desktopRs(o) { ' // The runtime\'s words in the owner\'s language from the first paint (the site only).', ' app::i18n_page_script(app),', ' // The runtime checks the origin itself and stays inert on other sites.', - ' // Debug builds read the file from disk and rebuild the tabs when `npm run dev` rebuilds it.', - ' waybetter_host::page_script!(RUNTIME, "runtime/runtime.js"),', + ' RUNTIME.to_owned(),', ' ]', ' }', '', @@ -813,23 +810,19 @@ function runtimeTs(o) { "import { createPageStrings } from 'waybetter/runtime/pageStrings';", "import { installPanelButton } from 'waybetter/runtime/panelButton';", "import { createPluginContext } from 'waybetter/runtime/permissions';", - "import { createFeatureRegistry, type FeatureRegistry } from 'waybetter/runtime/featureModules';", - "import { effectiveFlags, tableDefaults, type Flags } from 'waybetter/runtime/featureTable';", - "import { createCorePluginApi, type CorePluginApi } from 'waybetter/runtime/pluginApi';", + "import { createCorePluginApi } from 'waybetter/runtime/pluginApi';", "import { configureRuntime, isSiteUrl } from 'waybetter/runtime/site';", "import { createFeatureFlags, installSiteRuntime, pageInvoke, type FlagInstaller } from 'waybetter/runtime/siteRuntime';", "import { KIT_MESSAGES } from 'waybetter/runtime/ui';", - "import { TABLE } from '../features.ts';", "import { SITE } from '../site.ts';", - "import { MODULES } from './modules.ts';", '', '/**', - ' * The flags are the feature table\'s (src/features.ts): the owner toggles them on the panel\'s', - ' * area cards and native `features_set` delivers them. A feature module (src/runtime/modules.ts)', - ' * is started by the registry; a part of the runtime that must install on a flag at document', - ' * start (a request gate) goes into `INSTALLERS` with `backing: \'app\'` in the table.', + ' * PLACEHOLDER: the app\'s page tweaks. Each flag is a boolean the owner toggles in the panel', + ' * (waybetter/shell/panel `useFeatures` + `FeatureGroups`; native `features_set` delivers them); a part that', + ' * installs when its flag turns on and disposes when it turns off goes into `INSTALLERS`.', ' */', - 'const INSTALLERS: FlagInstaller[] = [];', + 'const FLAGS: Record = {};', + 'const INSTALLERS: FlagInstaller[] = [];', '', '/** The app\'s logo for the floating panel button (a data URI: the site\'s CSP may block other images). */', `const LOGO = ${str(`data:image/svg+xml,${encodeURIComponent(``)}`)};`, @@ -839,24 +832,12 @@ function runtimeTs(o) { ' if ((window as unknown as Record)[SITE.runtimeGlobal]) return;', ' configureRuntime(SITE);', ' const invoke = pageInvoke(window, SITE.product);', - ' let registry: FeatureRegistry | null = null;', - ' const flags = createFeatureFlags({', - ' defaults: tableDefaults(TABLE), label: SITE.product, installers: INSTALLERS, document,', - ' // An area that is switched off turns off the features it owns.', - ' resolve: all => effectiveFlags(TABLE, all),', - ' apply: config => registry?.setFlags(config),', - ' });', + ' const flags = createFeatureFlags({ defaults: FLAGS, label: SITE.product, installers: INSTALLERS, document });', ' // English for the plugin UI kit\'s own words; native code delivers the owner\'s language (i18n_set).', " const strings = createPageStrings({ english: { ...KIT_MESSAGES }, prefixes: ['kit.', 'plugin.'], label: SITE.product });", ' // No theme engine yet: `api.theme` reports the page\'s own colors. Pass `{ theme: source }`', ' // (a ThemeSource from waybetter/runtime/themeApi) once the app has themes.', ' const api = createCorePluginApi(window, SITE.plugins, { i18n: strings.source });', - ' // The feature modules: each runs only while its flag and its area are on. `surfaces` names the', - ' // parts of the site the page is (PLACEHOLDER: classify location.pathname; a feature that lists', - ' // surfaces in the table only runs on those).', - " registry = createFeatureRegistry({ win: window, table: TABLE, api, label: SITE.product, surfaces: () => ['page'], message: strings.message, locale: strings.locale });", - ' for (const module of MODULES) registry.define(module);', - ' registry.setFlags(flags.current());', ' // Each plugin gets an API view for its declared @permissions, with its own strings.', ' const plugins = createPluginContext(api, undefined, (full, id) => ({ i18n: full.i18n.namespace(strings.pluginNamespace(id)) }));', ' const links = SITE.links ? installLinkRouting(window, SITE.links) : undefined;', @@ -898,9 +879,7 @@ function shellTs(o) { "import { isSiteUrl } from 'waybetter/runtime/site';", "import { parseAddress } from 'waybetter/shell/addressModel';", "import { createShell, type ShellSite } from 'waybetter/shell/frame';", - "import { openOnboardingWhenDue } from 'waybetter/shell/panel';", "import { ADDRESS_SITE } from '../address.ts';", - "import { MESSAGES } from '../features.ts';", "import { SITE } from '../site.ts';", "import { Panel } from './Panel.tsx';", "import './app.css';", @@ -908,7 +887,7 @@ function shellTs(o) { `const ORIGIN = ${str(o.origin)};`, '', '/** English; merge `waybetter/locales/.json` (and your own catalog) for other languages. */', - "const i18n = createI18n({ source: { ...en.messages, ...MESSAGES }, available: ['en'] });", + "const i18n = createI18n({ source: en.messages, available: ['en'] });", '', 'const site: ShellSite = {', ` name: ${str(o.label)},`, @@ -939,16 +918,8 @@ function shellTs(o) { ' ],', ' },', ' // Native features this app does not wire up yet (waybetter-host workspaces, sync, devmode,', - ' // plugins::commands) and panel sections it does not have (the Store, the updater): the frame', - ' // shows nothing of them until they are switched on here. Page zoom (`tab_zoom`) is the host\'s own.', - ' features: { workspaces: false, sync: false, developer: false, pluginCommands: false, store: false, updates: false },', - ' // The app menu (the titlebar\'s "Settings and more", Alt+F / F10) needs nothing: without `menu`', - ' // the app gets every built-in row it can serve (new tab, splits, zoom, Plugins, the palette,', - ' // About, Settings). `menu.groups` orders them and adds rows of your own, e.g.', - ' // menu: { groups: menuWith(DEFAULT_MENU, "plugins", [{ id: "help", label: () => "Help", run: () => openHelp() }]) },', - ' // and `menu.languages` / `menu.modes` (menuModes() from waybetter/shell/panel) add those submenus.', - ' // The first-run screen (the modes of src/features.ts) is the panel\'s: open it when it is due.', - ' start() { openOnboardingWhenDue(); return undefined; },', + ' // plugins::commands): the frame shows nothing of them until they are switched on here.', + ' features: { workspaces: false, sync: false, developer: false, pluginCommands: false },', '};', '', 'const { core, event, window: tauriWindow } = window.__TAURI__;', @@ -957,83 +928,15 @@ function shellTs(o) { ); } -/** @param {AppOptions} o */ -function featuresTs(o) { - return lines( - '// The feature table: everything the owner can switch, as data (waybetter/runtime/featureTable).', - '// An AREA is one card in the panel\'s Plugins section with a switch of its own; a FEATURE is one', - '// flag, owned by an area or by nobody (a core flag: listed under "Fixes"); a MODE is a preset the', - '// first-run screen offers. The page runtime (src/runtime/main.ts) and the panel', - '// (src/shell/Panel.tsx) both read this table, so they cannot disagree. A flag\'s id never changes', - '// once it shipped: it is in the owner\'s features.json and backups.', - '', - "import type { FeatureTable } from 'waybetter/runtime/featureTable';", - '', - '/** PLACEHOLDER: one example area with one feature; its code is in src/runtime/modules.ts. */', - 'export const TABLE: FeatureTable = {', - ' areas: [', - ` { id: 'reading', name: 'Reading+', description: 'area.reading.description', owner: ${str(`${o.prefix}-reading-plus.plugin.js`)}, namespace: 'reading-plus' },`, - ' ],', - ' features: [', - " // `backing: 'module'`: a feature module the registry starts while the flag is on. Other kinds:", - " // 'app' (a part of the runtime that installs on the flag) and 'plugin' (a plugin file).", - " { id: 'reading.focusRing', area: 'reading', default: false, backing: 'module', label: 'feature.focusRing.label', description: 'feature.focusRing.description' },", - ' ],', - ' modes: [', - " { id: 'basic', name: 'mode.basic.name', description: 'mode.basic.description', flags: { 'area.reading': false } },", - " { id: 'advanced', name: 'mode.advanced.name', description: 'mode.advanced.description', recommended: true, flags: {} },", - " { id: 'power', name: 'mode.power.name', description: 'mode.power.description', flags: { 'reading.focusRing': true } },", - ' ],', - '};', - '', - '/** The table\'s words in English (merged into the shell\'s catalog in src/shell/main.tsx). */', - 'export const MESSAGES: Record = {', - " 'area.reading.description': 'Reading the page: small comforts.',", - " 'feature.focusRing.label': 'Mark the focused item',", - " 'feature.focusRing.description': 'Draws a ring around the item that has keyboard focus.',", - " 'mode.basic.name': 'Basic',", - ` 'mode.basic.description': ${str(`Only the app around ${o.label}. The page looks the way the site ships it.`)},`, - " 'mode.advanced.name': 'Advanced',", - " 'mode.advanced.description': 'Every plugin on with calm defaults.',", - " 'mode.power.name': 'Power User',", - " 'mode.power.description': 'Advanced, plus the keyboard helpers.',", - '};', - ); -} - -function modulesTs() { - return lines( - '// Feature modules: the code of the table\'s features (src/features.ts). The registry starts a', - '// module only while its flag is on, its area is on and the page is on one of its surfaces, and', - '// undoes everything the module did through its context when any of those stops being true.', - '', - "import type { FeatureModule } from 'waybetter/runtime/featureModules';", - "import type { CorePluginApi } from 'waybetter/runtime/pluginApi';", - "import { SITE } from '../site.ts';", - '', - 'export const MODULES: ReadonlyArray> = [', - ' {', - " id: 'reading.focusRing',", - ' start(ctx) {', - ' // One stylesheet while the feature is on; removed when it stops.', - ' ctx.css(`${SITE.plugins.itemSelector}:focus-within { outline: 2px solid Highlight; outline-offset: 2px; }`);', - ' },', - ' },', - '];', - ); -} - function panelTsx(o) { return lines( '// The app\'s own tab (Ctrl+Shift+W, the brand button, the floating button in the site\'s page,', '// Ctrl+K "Plugins"): the wayBetter panel (waybetter/shell/panel). The framework brings the', - '// sections this app serves: Home, Plugins (the area cards of src/features.ts, plugin files and', - '// custom CSS), Accounts and Settings. It grows', + '// sections this app serves: Home, Plugins (with custom CSS), Accounts and Settings. It grows', '// with the app: `themes` adds Appearance and the Theme Builder, `store` the Store, `make` the Make', '// section, `backup` and `updates` theirs, `sections` the app\'s own (see `PanelSite`).', '', "import { createPanel } from 'waybetter/shell/panel';", - "import { TABLE } from '../features.ts';", "import { SITE } from '../site.ts';", '', 'export const Panel = createPanel({', @@ -1048,8 +951,6 @@ function panelTsx(o) { " { section: 'accounts', title: () => 'Accounts', text: () => 'Real logins side by side, one per profile.' },", ' ],', ' },', - ' // Area plugins, the Fixes list and the modes (first-run screen, Settings): src/features.ts.', - ' features: { table: TABLE },', ' // Placeholder CSS in the custom CSS editor, written with this site\'s own selectors.', ` cssExamples: { custom: ${str(`/* Example */\n${o.site.selectors.item} { outline: 1px dashed; }`)} },`, '});', @@ -1066,7 +967,6 @@ function tauriTypes() { ' toggleMaximize(): Promise;', ' close(): Promise;', " startResizeDragging(direction: 'North' | 'South' | 'East' | 'West' | 'NorthEast' | 'NorthWest' | 'SouthEast' | 'SouthWest'): Promise;", - ' startDragging(): Promise;', ' isMaximized(): Promise;', ' onResized(handler: () => void): Promise<() => void>;', ' setBackgroundColor(color: [number, number, number, number]): Promise;', @@ -1144,12 +1044,11 @@ function buildMjs() { '// page Tauri serves from dist/: the wayBetter shell frame, bundled with its styles), both with', "// `waybetter/build`, and writes the shell's first-frame script.", "import { copyFileSync, mkdirSync, writeFileSync } from 'node:fs';", - "import { buildRuntime, watchRequested } from 'waybetter/build';", + "import { buildRuntime } from 'waybetter/build';", "import { bootScript } from 'waybetter/shell/frame/boot';", '', "mkdirSync('dist', { recursive: true });", - "// `node scripts/build.mjs --watch` (npm run dev) keeps rebuilding the runtime; a debug app reloads its tabs.", - `await buildRuntime({ entry: 'src/runtime/main.ts', outfile: ${str(APP_OUTPUTS.runtime)}, watch: watchRequested() });`, + `await buildRuntime({ entry: 'src/runtime/main.ts', outfile: ${str(APP_OUTPUTS.runtime)} });`, 'await buildRuntime({', " entry: 'src/shell/main.tsx',", " outfile: 'dist/shell.js',", @@ -1164,7 +1063,7 @@ function buildMjs() { "writeFileSync('dist/boot.js', bootScript());", "copyFileSync('src/shell/index.html', 'dist/index.html');", "copyFileSync('src-tauri/icons/icon.png', 'dist/icon.png');", - "console.log(watchRequested() ? 'watching " + APP_OUTPUTS.runtime + "' : 'built dist/ and " + APP_OUTPUTS.runtime + "');", + "console.log('built dist/ and " + APP_OUTPUTS.runtime + "');", ); } @@ -1186,8 +1085,6 @@ function readme(o) { 'npm install', 'npm run build # dist/ (shell) and ' + APP_OUTPUTS.runtime + ' (page runtime)', 'npm run tauri dev # the app', - 'npm run dev # the app with the dev loop: a saved runtime change reloads the tabs (debug build)', - 'npm run dev:stable # the same, and Rust changes do not restart the app', 'npm run test:rust # site adapter + plugin host tests, headless', '```', '', @@ -1198,9 +1095,7 @@ function readme(o) { '```', 'src/site.ts SiteAdapter: the page half of the adapter (PLACEHOLDER selectors)', 'src/address.ts address bar chips for the site\'s pages', - 'src/features.ts the feature table: areas (plugin cards), feature flags, modes (first-run presets)', - 'src/runtime/main.ts page runtime: window.' + o.runtimeGlobal + ' (+ window.wayBetter), plugin API, feature flags and modules, account report, the panel button', - 'src/runtime/modules.ts feature modules: the code of the table\'s features', + 'src/runtime/main.ts page runtime: window.' + o.runtimeGlobal + ' (+ window.wayBetter), plugin API, tweaks, account report, the panel button', 'src/shell/main.tsx the shell: the wayBetter shell frame (createShell) with this site\'s pages', 'src/shell/Panel.tsx the app\'s own tab: the wayBetter panel (createPanel) with this app\'s home page', 'plugins/example.plugin.js written (disabled) into a new plugins folder', @@ -1227,9 +1122,8 @@ function readme(o) { '2. Keep `hosts` and the runtime global identical in `site.ts` and `site.rs`.', '3. Add site-only commands like `site_ready`: `host::site_tab_only(&SITE, &webview)?` first,', ' then list them in `build.rs`, `capabilities/site-tab.json` and `tests/security.rs`.', - '4. Features: add a row to `TABLE` in `src/features.ts` (an area is a card in Plugins; a feature', - ' a toggle on it; `area: null` lists it under Fixes) and its module to `src/runtime/modules.ts`.', - ' The modes of the first-run screen are `TABLE.modes`.', + '4. Page tweaks: add flags to `FLAGS` in `src/runtime/main.ts` and a section with', + ' `useFeatures` and `FeatureGroups` (waybetter/shell/panel) to `sections` in `src/shell/Panel.tsx`.', '5. Next steps from the framework: account profiles (`waybetter_host::profiles`), split panes', ' (`waybetter/shell/paneModel`), the rail hider (`waybetter/runtime/paneNav`), themes', ' (`waybetter/runtime/themeApi`, `theme.schema.json`), signed updates (`updater: true` in the', @@ -1263,8 +1157,6 @@ export function appFiles(o) { build: 'node scripts/build.mjs', typecheck: 'tsc -p tsconfig.json', tauri: 'tauri', - dev: 'waybetter dev --watch "node scripts/build.mjs --watch"', - 'dev:stable': 'waybetter dev --stable --watch "node scripts/build.mjs --watch"', 'desktop:build': 'waybetter build-env -- tauri build', 'privacy:scan': 'waybetter privacy-scan --tracked .', 'test:rust': 'cargo test --manifest-path src-tauri/Cargo.toml --no-default-features', @@ -1301,9 +1193,7 @@ export function appFiles(o) { { path: 'scripts/build.mjs', content: buildMjs() }, { path: 'src/site.ts', content: siteTs(o) }, { path: 'src/address.ts', content: addressTs(o) }, - { path: 'src/features.ts', content: featuresTs(o) }, { path: 'src/runtime/main.ts', content: runtimeTs(o) }, - { path: 'src/runtime/modules.ts', content: modulesTs() }, { path: 'src/shell/main.tsx', content: shellTs(o) }, { path: 'src/shell/Panel.tsx', content: panelTsx(o) }, { path: 'src/shell/index.html', content: indexHtml(o) }, diff --git a/packages/create-waybetter/src/plugin.js b/packages/create-waybetter/src/plugin.js index 4431cb1..8c4f643 100644 --- a/packages/create-waybetter/src/plugin.js +++ b/packages/create-waybetter/src/plugin.js @@ -398,7 +398,7 @@ export function pluginFiles(o) { type: 'module', description: o.description, scripts: { build: 'node build.mjs', typecheck: 'tsc -p tsconfig.json' }, - devDependencies: { typescript: '^5.9.0', waybetter: '^0.6.0' }, + devDependencies: { typescript: '^5.9.0', waybetter: '^0.2.0' }, }; const tsconfig = { compilerOptions: { diff --git a/packages/create-waybetter/tests/create.test.mjs b/packages/create-waybetter/tests/create.test.mjs index ab7f9c7..0c95ad7 100644 --- a/packages/create-waybetter/tests/create.test.mjs +++ b/packages/create-waybetter/tests/create.test.mjs @@ -335,19 +335,13 @@ test('app: every site skeleton is consistent across its native and page halves', assert.ok(existsSync(join(PACKAGE, 'windows', 'installer.nsi')), 'the package has the installer template'); assert.ok(JSON.parse(readFileSync(join(PACKAGE, 'package.json'), 'utf8')).files.includes('windows'), 'and publishes it'); // Every `waybetter/...` import is a published subpath of the package. - const sources = ['src/site.ts', 'src/address.ts', 'src/features.ts', 'src/runtime/main.ts', 'src/runtime/modules.ts', 'src/shell/main.tsx', 'src/shell/Panel.tsx', 'scripts/build.mjs'].map(path => file(...path.split('/'))).join('\n'); + const sources = ['src/site.ts', 'src/address.ts', 'src/runtime/main.ts', 'src/shell/main.tsx', 'src/shell/Panel.tsx', 'scripts/build.mjs'].map(path => file(...path.split('/'))).join('\n'); for (const [, specifier] of sources.matchAll(/from '(waybetter\/[^']+)'/g)) assert.ok(exported(specifier), `${specifier} is exported`); // The shell is the framework's shell frame (createShell), not a copy; it needs the window calls. assert.match(file('src', 'shell', 'main.tsx'), /createShell\(site, /); // The app's tab is the framework's panel (createPanel); the page runtime is composed by the framework. assert.match(file('src', 'shell', 'Panel.tsx'), /export const Panel = createPanel\(\{/); assert.match(file('src', 'runtime', 'main.ts'), /installSiteRuntime\(\{/); - // The example of a feature module and of modes: one table read by the runtime and the panel. - assert.match(file('src', 'features.ts'), /export const TABLE: FeatureTable = \{/); - assert.match(file('src', 'runtime', 'main.ts'), /createFeatureRegistry\(\{ win: window, table: TABLE/); - assert.match(file('src', 'runtime', 'modules.ts'), /id: 'reading\.focusRing'/); - assert.match(file('src', 'shell', 'Panel.tsx'), /features: \{ table: TABLE \}/); - assert.match(file('src', 'shell', 'main.tsx'), /openOnboardingWhenDue\(\)/); assert.match(file('src-tauri', 'src', 'desktop.rs'), /AppConfig::new\(&SITE, SITE\.product, &plugins::HOST\)/); assert.ok(caps[0].permissions.includes('core:window:allow-start-resize-dragging'), 'the frame\'s resize grips'); // Icons Tauri decodes at compile time. diff --git a/packages/runtime/src/domHub.ts b/packages/runtime/src/domHub.ts index 6b3e7c6..5c48796 100644 --- a/packages/runtime/src/domHub.ts +++ b/packages/runtime/src/domHub.ts @@ -5,11 +5,6 @@ // text, a named attribute) and they run together in the next frame: layout readers first, then DOM // writers, so a reader never forces a synchronous layout behind another feature's write. Features // marked `offOnHeavy` do not run on the site's heavy pages (see `configureDomHub`), e.g. a WASM chat. -// -// A site that renders a part of itself inside an open shadow root (X's chat, since 2026-10-01, in -// the shadow root of its embed host) names the host in `shadowHosts`: the hub's one observer then -// observes each such root too (picked up when the host appears or gets its root, dropped with the -// observer), selector observers look inside, and `domRoots` gives features the roots to query. export type DomWatch = { /** Also run on text changes (characterData). */ @@ -28,8 +23,6 @@ export type DomHubConfig = { label: string; /** Pathnames where `offOnHeavy` features are skipped; null = none. */ heavyPath: RegExp | null; - /** Selectors of hosts whose open shadow roots are part of the page (observed and searched like it). */ - shadowHosts: readonly string[]; }; export type DomWindow = { @@ -41,7 +34,7 @@ export type DomWindow = { type Sub = { run: () => void; opts: DomWatch; pending: boolean }; type Hub = { subs: Sub[]; mark(sub: Sub): void; refresh(): void }; -const config: DomHubConfig = { label: 'wayBetter', heavyPath: null, shadowHosts: [] }; +const config: DomHubConfig = { label: 'wayBetter', heavyPath: null }; const hubs = new WeakMap(); /** Set once by the site adapter, before features register. */ @@ -49,31 +42,6 @@ export function configureDomHub(next: Partial): void { Object.assign(config, next); } -/** The page's roots: the document, then the open shadow roots of the configured hosts now in it. */ -export function domRoots(win: { document: Document }): Array { - const doc = win.document; - const out: Array = [doc]; - if (!config.shadowHosts.length) return out; - let hosts: Element[] = []; - try { hosts = Array.from(doc.querySelectorAll(config.shadowHosts.join(','))); } catch { return out; } - for (const host of hosts) { - const root = (host as Element & { shadowRoot?: ShadowRoot | null }).shadowRoot; - if (root) out.push(root); - } - return out; -} - -/** The site names hosts whose shadow roots are part of the page. */ -export function hasShadowHosts(): boolean { - return config.shadowHosts.length > 0; -} - -/** A configured host is in the page but has no open shadow root yet (it may attach one later). */ -function hostWithoutRoot(doc: Document): boolean { - if (!config.shadowHosts.length) return false; - try { return Array.from(doc.querySelectorAll(config.shadowHosts.join(','))).some(host => !(host as Element & { shadowRoot?: ShadowRoot | null }).shadowRoot); } catch { return false; } -} - export function isHeavyPath(pathname: string): boolean { return !!config.heavyPath && config.heavyPath.test(pathname); } @@ -85,28 +53,6 @@ function hubFor(win: DomWindow): Hub { let frameRequested = false; let observer: MutationObserver | null = null; let observing = ''; - let options: MutationObserverInit = { childList: true, subtree: true }; - // Shadow roots the observer already observes (with the current options). - let roots = new WeakSet(); - let retries = 0; - let retry: ReturnType | null = null; - /** Observes configured shadow roots that are new; a new one marks every feature (its content is new to them). */ - const observeRoots = () => { - if (!observer || !config.shadowHosts.length) return; - let added = false; - for (const root of domRoots(win).slice(1)) { - if (roots.has(root)) continue; - roots.add(root); - observer.observe(root, options); - added = true; - } - if (added) { retries = 0; for (const sub of hub.subs) hub.mark(sub); } - // attachShadow makes no mutation: a host that has no root yet is looked at again, a few times. - if (!retry && retries < 20 && hostWithoutRoot(doc)) { - retries += 1; - retry = setTimeout(() => { retry = null; observeRoots(); }, 300); - } - }; const frame = () => { frameRequested = false; @@ -132,7 +78,6 @@ function hubFor(win: DomWindow): Hub { else if (record.type === 'attributes' && record.attributeName) (attributes ??= new Set()).add(record.attributeName); } } - if (!known || childList) observeRoots(); for (const sub of hub.subs) { if (!known || childList || (characterData && sub.opts.characterData) || (attributes && sub.opts.attributes?.some(name => attributes!.has(name)))) hub.mark(sub); @@ -146,15 +91,12 @@ function hubFor(win: DomWindow): Hub { if (observer && observing === key) return; observer ??= new win.MutationObserver(onRecords); observing = key; - options = { + // Re-observing the same node replaces its options. + observer.observe(doc.body, { childList: true, subtree: true, ...(characterData ? { characterData: true } : {}), ...(filter.length ? { attributes: true, attributeFilter: filter } : {}), - }; - // Re-observing the same node replaces its options (the shadow roots get them again too). - observer.observe(doc.body, options); - roots = new WeakSet(); - observeRoots(); + }); }; const hub: Hub = { @@ -168,8 +110,6 @@ function hubFor(win: DomWindow): Hub { observer?.disconnect(); observer = null; observing = ''; - roots = new WeakSet(); - if (retry) { clearTimeout(retry); retry = null; } doc.removeEventListener('DOMContentLoaded', start); hubs.delete(win); return; @@ -182,55 +122,6 @@ 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 root of domRoots(win)) { - for (const element of Array.from(root.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 deleted file mode 100644 index 90d6ae5..0000000 --- a/packages/runtime/src/featureModules.ts +++ /dev/null @@ -1,545 +0,0 @@ -// 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 { domRoots, hasShadowHosts, isHeavyPath, observeSelector, watchDom, type DomWatch, type DomWatchHandle, type DomWindow } from './domHub.ts'; -import { adoptStyles, type RootStyles } from './styles.ts'; -import { HEALTH_COMMAND, areaFlag, healthKeywords, 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 { KIT_MESSAGES, type KitKey, 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; - - -/** - * A selector a feature depends on. `english`: it reads an English label, so it only counts on an - * English page. `when`: it only counts while this selector matches (the part of the page it lives - * in is there: a column the site drops in a narrow window is no verdict). - */ -export type Probe = string | { selector: string; english?: boolean; when?: string }; - -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; - /** The page's window (use it and its `document` instead of the globals: tests run without them). */ - readonly win: Window & typeof globalThis; - /** This feature's stylesheet (one per `name`, replaced in place, cleared by an empty string; removed on stop). It also styles the site's configured open shadow roots (domHub `shadowHosts`). */ - 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, or - * `plugin..` for a module that names its own namespace (`words`). (Not - * named `t`: the i18n tools read `t('…')` as a whole catalog key.) - */ - text(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>; - /** - * Where its words are in the catalog. Default: `plugin...`. A feature - * ported from a plugin names that plugin's namespace (`focus-mode`) and keeps its keys - * (`plugin.focus-mode.`, its label `plugin.focus-mode.name`): nothing is retranslated. - */ - words?: string; - /** 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 words are the kit's: `kit.feature.*`, `kit.save`). */ - 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 healthScopes = 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; - - // The registry's own words are the kit's (`kit.feature.*`, `kit.save`): English unless the app delivers them. - const text = (key: KitKey, params: Params = {}) => - formatMessage(options.message?.(key) ?? KIT_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; - /** A selector matches in the page or in one of its configured open shadow roots. */ - const inPage = (selector: string) => domRoots(doc.defaultView ?? { document: doc }).some(root => !!root.querySelector(selector)); - const words = (area: AreaSpec) => api.i18n.namespace(area.namespace); - /** A feature's word `key`: under its own namespace when it names one (`words`), else under its area's. */ - const wordOf = (module: FeatureModule, area: AreaSpec, key: string, params?: Params) => - (module.words ? api.i18n.namespace(module.words).t(key, params) : words(area).t(`${featureName(module.id)}.${key}`, params)); - /** 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 legacy = modules.get(spec.id)?.words; - if (legacy) { const own = api.i18n.namespace(legacy); return own.has('name') ? own.t('name') : null; } - 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(); - // The same sheets, adopted by each configured open shadow root of the page (a site part rendered - // inside one, e.g. X's chat embed); roots that appear later get them on the next hub frame. - const rootCss = new Map(); - const rootSheets = new Map>(); - let rootWatch: DomWatchHandle | null = null; - const syncRoots = () => { - const roots = domRoots(domWin).slice(1); - for (const [root, sheets] of rootSheets) { - if (roots.includes(root as ShadowRoot)) continue; - for (const item of sheets.values()) item.sheet.remove(); - rootSheets.delete(root); - } - for (const root of roots) { - let sheets = rootSheets.get(root); - if (!sheets) { sheets = new Map(); rootSheets.set(root, sheets); } - for (const [styleId, item] of sheets) if (!rootCss.has(styleId)) { item.sheet.remove(); sheets.delete(styleId); } - for (const [styleId, css] of rootCss) { - const item = sheets.get(styleId); - if (!item) sheets.set(styleId, { sheet: adoptStyles(root as ShadowRoot, css), css }); - else if (item.css !== css) { item.sheet.update(css); item.css = css; } - } - } - }; - const ctx: FeatureContext = { - id: module.id, - name, - area, - api, - win, - 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); - if (css) rootCss.set(styleId, css); else rootCss.delete(styleId); - if (!rootWatch && css && hasShadowHosts()) { - rootWatch = watchDom(domWin, syncRoots, { offOnHeavy: !spec.heavy }); - scope.defer(() => { - rootWatch?.dispose(); rootWatch = null; - rootCss.clear(); - for (const sheets of rootSheets.values()) for (const item of sheets.values()) item.sheet.remove(); - rootSheets.clear(); - }); - } - if (rootWatch) syncRoots(); - }, - 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; - }, - text: (key, params) => wordOf(module, area, 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; } - if (typeof probe !== 'string' && probe.when) { - let there = false; - try { there = inPage(probe.when); } catch { there = false; } - if (!there) continue; - } - let found = false; - try { found = inPage(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); - return { entry, title: featureLabel(entry.spec, area) ?? name, form: buildSettingsForm(h, entry.module.settings!, entry.settings.get(), key => wordOf(entry.module, area, 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.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); - } - // A paused feature that would run (its flag and area are on) is named in the palette: the - // entry opens the notes, and the panel reads it for the feature's row (featureTable `pausedFeatures`). - const ids = [...paused.keys()].filter(id => specs.get(id)!.area === area.id && flags[id] === true).join(' '); - const shown = healthScopes.get(area.id); - if (shown && shown.ids !== ids) { shown.scope.dispose(); healthScopes.delete(area.id); } - if (ids && !healthScopes.has(area.id)) { - const created = api.commands.withOwner(area.owner, () => api.scope()); - healthScopes.set(area.id, { scope: created, ids }); - try { - created.commands.register({ id: HEALTH_COMMAND, title: text('kit.feature.pausedList', { area: area.name }), keywords: healthKeywords(ids.split(' ')), run: () => { openSettings(area.id); } }); - } catch (error) { console.error(`[${label}] ${area.name} health command failed`, error); } - } - } - } - - 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(); - for (const shown of healthScopes.values()) shown.scope.dispose(); - healthScopes.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 deleted file mode 100644 index e734cda..0000000 --- a/packages/runtime/src/featureTable.ts +++ /dev/null @@ -1,290 +0,0 @@ -// 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; -} - -export type ModeStatus = { - /** The flags differ from what the mode starts from: "Custom (based on )". */ - custom: boolean; - /** What applying the mode again would turn on and off (flag ids, in table order). */ - on: string[]; - off: string[]; - /** - * Of those, the ones the mode gained since it was applied (an update made its preset larger). - * Empty when nothing is known about the preset of that time. - */ - added: string[]; -}; - -/** - * How the stored flags relate to mode `mode` (null or unknown: no mode, nothing to say). A mode is - * a starting point: nothing here applies anything. `applied` is the mode's `flags` as they were - * when it was applied (the shell stores it with the choice); without it a difference is simply the - * owner's own change. - */ -export function modeStatus(table: FeatureTable, flags: Readonly, mode: string | null | undefined, applied?: Readonly> | null): ModeStatus { - const spec = modeById(table, mode); - if (!spec) return { custom: false, on: [], off: [], added: [] }; - const preset = modeFlags(table, spec.id); - const defaults = tableDefaults(table); - const differs = Object.keys(preset).filter(key => typeof flags[key] === 'boolean' && flags[key] !== preset[key]); - const was = (key: string) => typeof applied?.[key] === 'boolean' ? applied[key] : defaults[key]; - return { - custom: differs.length > 0, - on: differs.filter(key => preset[key]), - off: differs.filter(key => !preset[key]), - added: applied ? differs.filter(key => was(key) !== preset[key]) : [], - }; -} - -/** - * Feature health, as the panel learns it. A feature that paused itself (featureModules.ts: its - * selector probes failed) is named by its area's `health` palette command in the page: the entry - * opens the notes there, and its keywords carry the paused flags. The panel reads the focused - * tab's command list (it already has it for the palette), so no new report crosses to the host. - */ -export const HEALTH_COMMAND = 'health'; -const HEALTH_WORD = 'paused'; - -/** The keywords of an area's health command: the paused flags of that area. */ -export const healthKeywords = (ids: readonly string[]) => [HEALTH_WORD, ...ids].join(' '); - -/** The flags of `table` a tab's reported commands say are paused (unknown words are ignored). */ -export function pausedFeatures(table: FeatureTable, commands: ReadonlyArray<{ id: string; keywords?: string }> | null | undefined): Set { - const paused = new Set(); - for (const area of table.areas) { - const words = commands?.find(command => command.id === `${area.owner}:${HEALTH_COMMAND}`)?.keywords?.split(' ') ?? []; - if (words[0] !== HEALTH_WORD) continue; - for (const feature of table.features) if (feature.area === area.id && words.includes(feature.id)) paused.add(feature.id); - } - return paused; -} - -/** 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 21b7ec0..2379385 100644 --- a/packages/runtime/src/pluginApi.ts +++ b/packages/runtime/src/pluginApi.ts @@ -9,7 +9,6 @@ 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'; @@ -61,10 +60,7 @@ 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. - * Page-wide observers share one MutationObserver (domHub.ts); pass `root` only for a tree of your own. - */ + /** Calls `callback` once for every element matching `selector`, now and as the page renders more. */ 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 @@ -149,25 +145,6 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi }); const styleNodes = new Map(); const adoptedFallbacks = new Map(); - // At document start the engine may run us before the document has an element to hold a