@x-tech-laboratories/x-app 0.118.0 → 0.120.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,7 +9,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
9
9
 
10
10
  | Import | What it holds |
11
11
  | ---------------------------------------- | ----------------------------------------------------------------------------- |
12
- | `app/define` | The base app: `define_app` puts an X-app's name, ports, files, its own settings and its `define_feature` features (tables, migrations, calls, `api_spec`, settings, histories) together into one store every device keeps (`open_store` calling each feature's `on_open`, `needs_upgrade`, `bind_methods(database, on_change, caller)` running each call as its `caller`, calling each feature's `after_write`, recording versions and announcing writes, `is_read_only`), `page_only` (the specs' `page_only` calls and the writes of `user_only` settings, refused with `page_only_refusal`), its sync engine, its backups' names and schedule, and its bridges named after the app; `AppMethodsOf<typeof app>` types the app's calls. `history_days` sets how far an app's history reaches back until the user chooses (365 unless set); what opening changed is recorded as this device's version, and old versions are pruned on opening and after a write once a day. `settings_knows(key)` lets an import take keys without a spec of their own, such as `diet.target_protein`; `upgrade_layout: { needed, run }` brings a database an older version laid out its own way, such as a versions table keyed another way, in line before any migration, backed up first; `adopt_backup_schedule(database, saved)` moves a schedule an older version kept elsewhere into the setting once. `tools`, a feature of the app's own, is what MCP offers in place of the page's calls, such as tools that take names rather than ids, each run as the `program` caller (`app.mcp`). Sync's and history's triggers come off while migrations run, so a step may drop a column they name. `synced_theme` keeps the light, dark or system theme as a synced setting, `theme`, so every device shows the one picked last. |
12
+ | `app/define` | The base app: `define_app` puts an X-app's name, ports, files, its own settings and its `define_feature` features (tables, migrations, calls, `api_spec`, settings, histories) together into one store every device keeps (`open_store` calling each feature's `on_open`, `needs_upgrade`, `bind_methods(database, on_change, caller)` running each call as its `caller`, calling each feature's `after_write`, recording versions and announcing writes, `is_read_only`), `page_only` (the specs' `page_only` calls and the writes of `user_only` settings, refused with `page_only_refusal`), its sync engine, its backups' names and schedule, and its bridges named after the app; `AppMethodsOf<typeof app>` types the app's calls. `history_days` sets how far an app's history reaches back until the user chooses (365 unless set); what opening changed is recorded as this device's version, and old versions are pruned on opening and after a write once a day. `settings_knows(key)` lets an import take keys without a spec of their own, such as `diet.target_protein`; `upgrade_layout: { needed, run }` brings a database an older version laid out its own way, such as a versions table keyed another way, in line before any migration, backed up first; `adopt_backup_schedule(database, saved)` moves a schedule an older version kept elsewhere into the setting once. `tools`, a feature of the app's own, is what MCP offers in place of the page's calls, such as tools that take names rather than ids, each run as the `program` caller (`app.mcp`). Sync's and history's triggers come off while migrations run, so a step may drop a column they name. `take_data_change(database)` names the synced tables written since the last call for that connection (null on its first call and after a restore); the server and daemon send it with each change, so a page's `on_change(listener)` hears `{ tables }` and fetches only what it shows from them, or everything on null. `synced_theme` keeps the light, dark or system theme as a synced setting, `theme`, so every device shows the one picked last. |
13
13
  | `app/server`, `app/daemon` | `run_server(app, { web_folder })`: the web server from `<PREFIX>_CONFIG` with accounts in `accounts.db` (moved there once from the data's own file, tokens starting with the app's `token_prefix`), the calls, OpenAPI, MCP, the server's backups and its sync peer, a token or MCP client refused the app's `page_only` calls and the `user_only_backup_calls` (restore, remove, schedule) and its calls run as the `program` caller; `run_daemon(app)`: the desktop daemon from `<PREFIX>_DB` with sync, letting devices connect, backups, certificates and the desktop settings; Both take the app's `services` (see `app/services`), `run_daemon(app, env, { services })`. A `backup-schedule.json` an older version kept beside the database moves into this device's setting on opening. Both tell every page when another program, such as an older build, writes the database file (`watch_outside_changes`, on SQLite's `data_version`). `build_server`, `start_daemon`, `open_app_database` (with `on_restore` hooks) and `register_app_calls` for tests and apps that add their own. |
14
14
  | `app/services` | An app's own work beside its calls, run by both hosts: `StartServices` gets a `HostContext` (`kind`, `database()`, `profile`, `device_name`, the server's raw `config`, `plugins_folder`, `declared_file` from `<PREFIX>_DECLARED_FILE` or `/etc/<id>/declared.json`, `announce`, `emit(event, data)` for the page's `on_event`, `side_database(name)` for a never-backed-up file such as `<base>-index.db`, `back_up`) and returns `HostServices` (`before_restore`, `after_restore`, `stop`), stopped before sync and the database. |
15
15
  | `app/links` | `app_link(scheme, route)` and `route_of_link(scheme, link)`: an app's links such as `x-notes://note/<id>` and the page route they open. |
@@ -45,7 +45,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
45
45
  | `grouping` | `group_items`: items sorted into groups by a key each has, such as a status, a year or the collections they are in, an item with several keys in each of their groups, the app's `order` of keys first and the rest by name, numbers by value, `descending` when asked, each group keeping the items' order and those with no key last; for `GroupSections`, `GroupedMediaGrid` or a table under headings. |
46
46
  | `money` | `format_money` in a currency and locale to a set number of places, falling back to the number and code on a currency Intl refuses; `round_money` rounding halves away from zero, `money_step`, `sum_money`, `is_currency_code` and `currency_options` naming each currency for a select. |
47
47
  | `i18n` | Words in the reader's language: `create_translator` looks each key up in catalogs in turn, so a missing translation falls back to the next, with `{name}` placeholders filled; `merge_messages`; `best_locale`, the available locale that best fits the reader's preferred ones, an exact tag before the same language; `text_direction` for the `dir` attribute. |
48
- | `sql` | `SqlDatabase`, the part of a synchronous SQLite connection the apps use, met by node:sqlite and by `web/sqlite_wasm`; `in_transaction`, and `migrate`, each step (a script, its statements, or code given the database) once in its own transaction, through `user_version` or, with an `owner` such as a feature or plugin, its own row in `schema_versions`. |
48
+ | `sql` | `SqlDatabase`, the part of a synchronous SQLite connection the apps use, met by node:sqlite and by `web/sqlite_wasm`; `in_transaction`, and `migrate`, each step (a script, its statements, or code given the database) once in its own transaction, through `user_version` or, with an `owner` such as a feature or plugin, its own row in `schema_versions`; `tidy_database` refreshes the query planner's statistics and, once a tenth of the file (or the `free_share` given) is empty pages, vacuums it smaller and empties the write-ahead log, leaving a rewrite another connection's write holds up for next time. The base app tidies its database on opening, after a restore and every `tidy_every_ms` (a day) on the server and the desktop daemon, and on opening and on coming back after a day on a phone. |
49
49
  | `settings` | An app's settings feature: one synced `settings (key, value)` table of JSON values, the same table and first step (`settings_migration` under the owner `"settings"`) every app already ran. Each feature declares a `SettingSpec` per key (`default`, `user_only`, `local` for this device alone, `secret` for another service's key, or its own `hide` and `keep`), `settings_of` giving every key of a defaults table the same spec; `create_settings_store(tables, { app })` merges them, refusing a key declared twice, and gives the migration, the synced table entry with its `local_keys`, `defaults`, the `user_only` set, `is_user_only_call` for `page_only_calls` (a user-only write, an import holding one, an export with secrets), `is_device_only` for `register_sync_routes`, `value_of`, and `get_settings`, `set_setting`, `export_settings` and `import_settings` with their api specs. Secrets read as `hidden_secret` and are kept when it comes back; the settings file is the standard's `{ app, kind: "settings", version, exported_at, settings }`, an import ignoring unknown keys and those of one device. `read_setting`, `write_setting` and `read_stored_settings` reach rows directly. No `node:` or DOM imports. |
50
50
  | `caller`, `node_caller_scope` | Who is making the call in hand: `as_caller("page" \| "program" \| "engine", work)` around a call, `current_caller()` read by a store, and `caller_of(request)` (a token is a program). With a `CallerScope` in use (`use_caller_scope`), the caller holds across the call's awaits; the base app's server and daemon use `node_caller_scope()`, Node's `AsyncLocalStorage`, and without one, as on a phone, it holds for the call's synchronous part. |
51
51
  | `api_spec` | An app's calls described once for other programs: `ApiSpec` gives each method its words and a JSON Schema per argument, so a method without one fails to compile; `input_schema` takes the arguments as one object, `positional_args` puts named arguments back in the method's order from a spec or any `NamedParams`, `openapi_document` writes an OpenAPI 3.1 document with one POST per call, and `route_openapi_document` one for REST routes such as `server/mcp`'s `route_tools` serves, each under its own path and verb with its path, query and body arguments; `check_known_ids` refuses a call naming an id that does not exist, such as "no such track a1", before it acts, `unknown_ids` lists them, and `keep_known_ids` cuts a remembered list, such as picked columns, down to the ids that still exist. A spec marked `page_only: true` is a call only the user may make at the app's own page (a signed-in browser, or a desktop window through its daemon's socket), such as approving what an assistant proposed: `page_only_calls(api, { rule?, refusal? })` gives the `PageOnlyCalls` the other modules take (`is_page_only(method)` for the marks, `is_page_only_call(method, args)` adding the app's `rule(method, args)` such as a write to some settings, `is_page_only_request(method, body)` for arguments as a list or by name, unchecked so a call with wrong names is left to refuse them itself, and the `refusal` text, `default_page_only_refusal` unless set), and both OpenAPI documents mark such a call with `x-page-only: true` and a 403. |
@@ -55,7 +55,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
55
55
  | `email_links` | `bare_message_id` and `email_uri`: an email linked by its Message-ID as an RFC 2392 `mid:` link, which mail programs such as Thunderbird open wherever the message was filed. |
56
56
  | `snippets` | `shorten(text, length = 200)`: text put on one line and cut with an ellipsis, for an excerpt under a title. |
57
57
  | `drizzle`, `drizzle_migrations` | Typed SQLite on Drizzle ORM 1.0.0-rc.5, chosen over Kysely and hand-written SQL because it types rows from one schema in TypeScript, writes the migration SQL from it with drizzle-kit and runs synchronously: `open_drizzle` over any `SqlDatabase`, and `drizzle_of`, which the stores call, making it once per connection, so the same queries run on node:sqlite and in a phone's page, `synced_tables` reading the sync list from the schema's primary keys, `migrate_drizzle` per owner, the schema builders and query operators so an app never imports Drizzle, with `AnySQLiteColumn` for a table whose rows point at its own, and `x-app-bundle-migrations <folder>`, which turns drizzle-kit's migration folders into an `index.ts` a server running .ts files can import. |
58
- | `sync_engine`, `sync_peer`, `sync_protocol`, `sync_seal`, `server/sync_peer_routes`, `sync_peer_discovery`, `sync_peer_listening` | SQLite kept alike on every device with no server: `create_sync_engine` stamps each value of the tables it is given through triggers, so the app's own writes need no change, and the newest write of each value wins, each key of a table's `map_columns` (JSON objects such as ids from many sources) counting as a value of its own so two devices adding different keys keep both. Every copy is a peer: `create_sync_peer` pairs with another device through a one-time code (`create_pairing_code`, `pair_device`), the two copies merging with nothing asked, then sends each paired device its changes within seconds, takes theirs in the same round trip, holds a waiting call open to hear of theirs at once, and passes on what it took from the others, so devices that never reach each other still end up alike; the group's list of devices travels too, so a new device is introduced to the rest and a removed one (`remove_device`) is refused by all. Each call is sealed with both devices' keys on tweetnacl's box (`sync_seal`), chosen over TLS with pinned certificates because it runs alike on Node and in a phone's page; calls still travel over https only. After a restore (`forget_history`) each peer is made to match the restored copy once, keeping a copy of its own first. `register_sync_peer_routes` answers other devices at `sync/peer` under a daemon's prefix, `listen_for_peers` opens a desktop daemon's own port for them, `discover_peers` finds paired devices on the local network by mDNS, on bonjour-service, and `keep_listening_for_peers` (`sync_peer_listening`) is a desktop daemon's "Let other devices connect" setting, kept in a file beside the database, which answers over https with a self-signed certificate made once (`peer_certificate`, on selfsigned, chosen because it makes one with Node's own crypto) and whose `PeerListeningMethods`, its fingerprint included, the page shows with `PeerListeningSettings`; `SyncSettings` given `certificates` asks to review and trust that certificate when pairing fails over it, and pairs again. |
58
+ | `sync_engine`, `sync_peer`, `sync_protocol`, `sync_seal`, `server/sync_peer_routes`, `sync_peer_discovery`, `sync_peer_listening` | SQLite kept alike on every device with no server: `create_sync_engine` stamps each value of the tables it is given through triggers, so the app's own writes need no change, and the newest write of each value wins, each key of a table's `map_columns` (JSON objects such as ids from many sources) counting as a value of its own so two devices adding different keys keep both; a table marked `rows_never_change`, such as saved versions, keeps one version per row instead of one per column, its older per-column versions folded into it on opening. `changed_tables_since(database, cursor)` names the synced tables written after a point. Every copy is a peer: `create_sync_peer` pairs with another device through a one-time code (`create_pairing_code`, `pair_device`), the two copies merging with nothing asked, then sends each paired device its changes within seconds, takes theirs in the same round trip, holds a waiting call open to hear of theirs at once, and passes on what it took from the others, so devices that never reach each other still end up alike; the group's list of devices travels too, so a new device is introduced to the rest and a removed one (`remove_device`) is refused by all. Each call is sealed with both devices' keys on tweetnacl's box (`sync_seal`), chosen over TLS with pinned certificates because it runs alike on Node and in a phone's page; calls still travel over https only. After a restore (`forget_history`) each peer is made to match the restored copy once, keeping a copy of its own first. `register_sync_peer_routes` answers other devices at `sync/peer` under a daemon's prefix, `listen_for_peers` opens a desktop daemon's own port for them, `discover_peers` finds paired devices on the local network by mDNS, on bonjour-service, and `keep_listening_for_peers` (`sync_peer_listening`) is a desktop daemon's "Let other devices connect" setting, kept in a file beside the database, which answers over https with a self-signed certificate made once (`peer_certificate`, on selfsigned, chosen because it makes one with Node's own crypto) and whose `PeerListeningMethods`, its fingerprint included, the page shows with `PeerListeningSettings`; `SyncSettings` given `certificates` asks to review and trust that certificate when pairing fails over it, and pairs again. |
59
59
  | `sync_files`, `node_file_store`, `electron/file_protocol` | Files that sync beside the rows that name them, such as covers or photos, so a large picture never travels with every change: each is named by the sha256 of its bytes (`hash_bytes`, `put_file`, `is_file_name`) and kept in a `SyncFileStore`, a folder on Node (`folder_file_store`, written through a rename) or IndexedDB on a phone (`indexed_db_files`); given `files: { store, referenced }`, the sync peer sends each paired device the named files it lacks and fetches those this device lacks after each exchange, a few at a time, trying a file neither has yet again next round, and keeps the ones it is sent, refusing bytes that do not match their name; `register_file_scheme` and `serve_files` show them in a desktop page as `<scheme>://<name>`. |
60
60
  | `app_android` | `x-app-android [app folder]`: the app's Capacitor project in `android/`, made from Capacitor's template when it is missing, given X-App's `config/android/release.gradle` and, where it has none of its own, a network rule allowing plain http only to the phone itself (`network_security_config`), for `adb reverse` while testing, (the version CI hands each build, and signing when the release key is in the environment), its launcher icons from `x-app-icons`, then `cap sync android`. Run after the Android page is built; the app keeps `android/` out of git. |
61
61
  | `app_android_key` | `x-app-android-key [app folder] [key folder]` or `x-app-android-key --org <org> [key folder]`: an Android release key, made once with keytool in `~/.local/share/<name>/signing` (or the given folder) and never replaced, and stored with gh as the `ANDROID_KEYSTORE_BASE64`, `ANDROID_KEYSTORE_PASSWORD` and `ANDROID_KEY_ALIAS` secrets `app-android` signs with, handed over on stdin so nothing prints it. `--org` makes one key for every app, kept as organization secrets every repository reads; a repository's own secrets of those names win. Run it in the app's Android shell. |
@@ -72,7 +72,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
72
72
  | `phone_sockets` | `phone_sockets()`: UDP and TCP sockets for a `phone_service` worker, answered by X-App's Android side: `udp_open` (with `broadcast`, holding Android's multicast lock), `tcp_listen`, `tcp_connect` and `list_interfaces`; a TCP socket reads nothing until `read_line` takes one line or `start_reading` everything after, so `start_tls` can follow plain text in either TLS role, as KDE Connect's identity line does, with the app's PEM certificate and key, letting any peer through and handing back its certificate for the worker to pin; `pause` and `resume` for a slow reader, and `write` settling once sent. Events that arrive before a listener are kept for it. Needs `CHANGE_WIFI_MULTICAST_STATE` and `WAKE_LOCK` in the app's manifest; each event keeps the phone awake a few seconds so the worker can answer. |
73
73
  | `app/item_history`, `app/web/item_history` | A history for each kind of item made of rows across tables, such as a workout with its exercises and sets: `item_history_feature(kinds)` keeps each kind's versions (an `ItemLevel` list read by `read_snapshot` and put back by `apply_snapshot`, a deleted item coming back whole) and adds `list_item_history`, `list_recent_changes` and `restore_item_version` with their specs; on the page, `HistoryView` lists the latest changes, `HistoryButton` and `open_item_history` open one item's versions, each restorable after a confirm. |
74
74
  | `api_schemas` | The argument shapes many calls share as JSON Schema: `text(description)`, `number(description)`, `id_of("workout")`, a local `day`, a `moment`, a `json_file`'s text and a `step` of -1 or 1. |
75
- | `history` | Every change to an app's items kept as versions in SQLite: `create_history` sets triggers on the tables that change an item, `record` saves one version of each item touched, and `restore` brings a version back, a deleted item with what was deleted under it; the versions table syncs, `read_changed_since` gives the newest version of each item changed after a moment, oldest first, and `history_methods` are the page's calls. Its tables are made only where missing, so an app with its own older versions table keeps it, naming its item column with `item_column`. A table that reaches its item only through another, such as a workout's sets through its exercises, names it with `item_lookup`, a query from the row. |
75
+ | `history` | Every change to an app's items kept as versions in SQLite: `create_history` sets triggers on the tables that change an item, `record` saves one version of each item touched, and `restore` brings a version back, a deleted item with what was deleted under it; the versions table syncs as rows that never change, an app's own index on the same columns as its item index is dropped, `read_changed_since` gives the newest version of each item changed after a moment, oldest first, and `history_methods` are the page's calls. Its tables are made only where missing, so an app with its own older versions table keeps it, naming its item column with `item_column`. A table that reaches its item only through another, such as a workout's sets through its exercises, names it with `item_lookup`, a query from the row. |
76
76
  | `items` | The four read-only calls every app answers about its items for other apps ([Items for other apps](#items-for-other-apps)): `item_calls` turns the app's own kinds, search, get and changes into `list_item_kinds`, `search_items`, `get_items` and `list_item_changes` with their `api_spec` entries, every item in one shape (`Item`, `DeletedItem`, `ItemChange`) with its snippet clipped to 200 characters, limits defaulted and capped, and changes oldest first; `item_link` and `parse_item_link` for `x-<app>://<kind>/<id>` links with the id percent-encoded; `history_item_changes` answers the changes from `create_history` versions; a source with `text` adds the optional `get_item_texts`, each item's full text (`ItemText`) as plain text or Markdown cut to 256 KB by `clip_item_text`, and `has_text` on each kind. |
77
77
  | `item_client` | Reading another app through its item calls: `item_client(app)` makes `list_item_kinds`, `search_items`, `get_items`, `list_item_changes` and `get_item_texts` at `POST /api/call/<method>`, falling back to the older `/api/<method>` and remembering which answered, ids sent a page at a time, `get_item_texts` null for an app that does not answer it (`ItemCallMissing`), and failures in plain words that never hold the token. |
78
78
  | `plugins` | `create_plugin_host`: plugins bundled with the app or loaded at run time, each a manifest and a `start(context)`, started in the order their `requires` need and refused when meant for another app or app version; through the context a plugin adds hooks the app calls (on hookable, chosen for its typed, ordered and parallel calls with nothing of its own to style), providers the app picks one of by id, commands with keys, slot contents and settings fields, all taken back when it stops, is turned off or fails to start; one plugin's failing hook is reported and the rest still run; on/off and settings kept through `json_plugin_storage`, stored values that no longer fit falling back to their defaults; a text field marked `secret`, such as an API key, drawn hidden, replaced by `hidden_secret` in what `hide_secrets` gives other programs and given back its stored value by `keep_secrets` when those records are written; versions checked with semver. |
@@ -153,7 +153,7 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
153
153
  | `web/files` | `read_picked`: a file picker's text, the picker cleared so the same file can be picked again; `save_text(file_name, text, type)` offers text as a download, such as a settings export. |
154
154
  | `web/states`, `web/tables`, `web/menus`, `web/split`, `web/errors` | `LoginNeeded`; sorting by several columns, trees and column order; for rows of plain objects, the same on a server and in the page, `sort_rows` (numbers before text, natural order, empty cells last), `filter_rows` on every typed word, `next_sort_keys` for header clicks, `keyed_rows` from contents and `tree_rows` by a parent field; menu items, placement and keys; pane sizing; `describe_error` for anything thrown, such as shaka's coded objects, and `describe_call_error`, the same without Electron's remote-method prefix, for a failed call shown to the user. |
155
155
  | `web/api`, `web/events` | `create_api`: JSON calls whose 401 throws `LoginNeeded` except on open paths such as the login, whose refusals throw `ApiError` in the server's words (a proxy's HTML error page, such as a 504, in plain ones), with headers read afresh per call and `{ keepalive: true }` letting a call outlive the page while its body fits under the browser's 64 KiB; `follow_changes`: the page's side of `EventStream`, a watch bumped on each change and after a reconnect, and the client id to send back. |
156
- | `web/tree` | Rows with `parent_id` and `position`: nesting, subtrees, tree order, paths, and where a dropped or keyed row lands, its siblings ordered by position or, with `by_list_order`, as the list gives them. |
156
+ | `web/tree` | Rows with `parent_id` and `position`: nesting, subtrees, tree order, paths, and where a dropped or keyed row lands, its siblings ordered by position or, with `by_list_order`, as the list gives them; `item_by_id` and `with_ancestors` look items up through an index made once per list, which `subtree_ids` and `path_names` share, so a list's items are copied rather than edited in place. |
157
157
  | `web/watch`, `web/react/watch` | `create_watch`: a change counter a store bumps; `use_watch` redraws only the components that read that store; `coalesce_bumps` lands a bump at most once per interval, for streamed tokens. |
158
158
  | `web/store`, `web/react/store` | `create_store`: a value with a watch, set or updated, redrawing at a steady pace when `coalesce_in_milliseconds` is given; `use_store` reads it. |
159
159
  | `web/prefs`, `web/react/prefs` | Remembered view settings that read as their default when stored corrupt, stale or of the wrong shape; `use_pref` keeps one as component state. |
@@ -17,7 +17,7 @@ import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
17
17
  import { keep_listening_for_peers } from "../sync_peer_listening.js";
18
18
  import { declared_file_of, no_services, side_databases } from "./services.js";
19
19
  import { read_desktop_settings } from "./protocol.js";
20
- import { call_body_limit, open_app_database, register_app_calls, watch_outside_changes } from "./server.js";
20
+ import { call_body_limit, data_change_text, open_app_database, register_app_calls, watch_outside_changes } from "./server.js";
21
21
  // ── Daemon ───────────────────────────────────────────────────────────────────
22
22
  // Answers on the socket and starts sync; null when another daemon on the same database already answers.
23
23
  export async function start_daemon(app, options) {
@@ -28,7 +28,7 @@ export async function start_daemon(app, options) {
28
28
  // Backed up before an upgrade, before another copy replaces it, and daily, beside the database.
29
29
  const opened = open_app_database(app, database_path, join(profile, "backups"));
30
30
  // Every window's event stream, told when the data changed or sync's status moved.
31
- const changes = new EventStream();
31
+ const changes = new EventStream({ change_data: data_change_text(app, opened.database) });
32
32
  // Server certificates the user trusted, such as a home server's self-signed one, handed to Node's own fetch.
33
33
  const certificates = create_certificate_trust({ file: join(profile, "trusted-certificates.json"), use_in_node: true });
34
34
  // Off until "Let other devices connect" is turned on; then other devices reach this computer's sync on its port.
@@ -12,7 +12,7 @@ import { type SettingSpec, type SettingsMethods, type SettingsStore, type Settin
12
12
  import { type MigrationStep, type SqlDatabase } from "../sql.ts";
13
13
  import { type SyncedTable } from "../sync_engine.ts";
14
14
  import { type PeerListeningMethods, type SyncDeviceMethods, type SyncStatus } from "../sync_protocol.ts";
15
- import { type DesktopMethods, type DesktopSettingSpec } from "./protocol.ts";
15
+ import { type DataChange, type DesktopMethods, type DesktopSettingSpec } from "./protocol.ts";
16
16
  export type StoreMethod = (database: SqlDatabase, ...args: never[]) => unknown;
17
17
  export type KeptHistory = Pick<History<unknown>, "synced_table" | "install" | "forget_touched" | "record" | "prune"> & Partial<Pick<History<unknown>, "drop_triggers">>;
18
18
  export interface Feature<Methods extends Record<string, StoreMethod> = Record<string, StoreMethod>> {
@@ -79,7 +79,7 @@ export interface Restorable extends Backups {
79
79
  restore: (name: string) => Promise<void>;
80
80
  }
81
81
  export type AppEvents = {
82
- changed: null;
82
+ changed: DataChange | null;
83
83
  sync_status: SyncStatus;
84
84
  app_event: {
85
85
  event: string;
@@ -148,10 +148,15 @@ export declare function define_app<const Features extends readonly Feature[]>(op
148
148
  has_unsent_changes: (database: SqlDatabase, device: string) => boolean;
149
149
  count_unsent_rows: (database: SqlDatabase, devices: readonly string[]) => number;
150
150
  collect_changes_since: (database: SqlDatabase, cursor: number, except_site: string) => import("../sync_engine.ts").CollectedChanges;
151
+ changed_tables_since: (database: SqlDatabase, cursor: number) => {
152
+ tables: string[];
153
+ up_to_seq: number;
154
+ };
151
155
  collect_snapshot: (database: SqlDatabase) => import("../sync_engine.ts").CollectedChanges;
152
156
  apply_changes: (database: SqlDatabase, changes: import("../sync_protocol.ts").SyncChange[]) => number;
153
157
  claim_everything: (database: SqlDatabase, theirs: import("../sync_protocol.ts").SyncChange[]) => void;
154
158
  };
159
+ take_data_change: (database: SqlDatabase) => DataChange | null;
155
160
  needs_upgrade: (database: SqlDatabase) => boolean;
156
161
  open_store: (database: SqlDatabase) => void;
157
162
  method_names: ((keyof UnionToIntersection<Features[number]["methods"]> | keyof SettingsMethods) & string)[];
@@ -62,6 +62,18 @@ export function define_app(options) {
62
62
  tables: [...features.flatMap((feature) => feature.tables), ...histories.map((history) => history.synced_table)],
63
63
  after_apply: (database) => histories.forEach((history) => history.forget_touched(database)),
64
64
  });
65
+ // Where each open connection's last announced change reached, so the next one names only the tables written since.
66
+ const announced = new WeakMap();
67
+ // The synced tables changed since the last call for this connection; the first call, and any after a restore, cannot tell.
68
+ function take_data_change(database) {
69
+ const { generation, last_seq } = sync_engine.read_state(database);
70
+ const since = announced.get(database);
71
+ const { tables, up_to_seq } = sync_engine.changed_tables_since(database, since?.seq ?? last_seq);
72
+ announced.set(database, { generation, seq: up_to_seq });
73
+ if (!since || since.generation !== generation || since.seq > last_seq)
74
+ return null;
75
+ return { tables };
76
+ }
65
77
  // ── Opening ──────────────────────────────────────────────────────────
66
78
  // Whether a database already holding data has steps to run, so it can be backed up before its schema is upgraded.
67
79
  function needs_upgrade(database) {
@@ -224,6 +236,7 @@ export function define_app(options) {
224
236
  settings_store,
225
237
  setting_defaults: settings_store.defaults,
226
238
  sync_engine,
239
+ take_data_change,
227
240
  needs_upgrade,
228
241
  open_store,
229
242
  method_names,
@@ -87,8 +87,8 @@ export function run_desktop(app, electron, options) {
87
87
  restart_local: () => ensure_daemon(),
88
88
  local_tables: [...default_local_tables, "peer_listening"],
89
89
  is_read_only: app.is_read_only,
90
- on_change: () => {
91
- app.bridges.events.emit(windows(), "changed", null);
90
+ on_change: (change) => {
91
+ app.bridges.events.emit(windows(), "changed", change);
92
92
  void apply_window_settings().catch(() => undefined);
93
93
  void tray?.refresh();
94
94
  },
@@ -4,6 +4,8 @@ import type { ConnectionClient } from "../connection_protocol.ts";
4
4
  import type { LocalMcpClient } from "../local_mcp_protocol.ts";
5
5
  import type { Client } from "../electron/bridge.ts";
6
6
  import type { PeerListeningClient, SyncDeviceClient } from "../sync_protocol.ts";
7
+ import type { DataChange } from "../sync_protocol.ts";
8
+ export { data_change_of, type DataChange } from "../sync_protocol.ts";
7
9
  export interface DesktopSettings {
8
10
  show_tray_icon: boolean;
9
11
  keep_running_in_background: boolean;
@@ -54,6 +56,6 @@ export interface PageApi<Methods extends Record<keyof Methods, (...args: never[]
54
56
  peer_listening?: PeerListeningClient;
55
57
  desktop?: Client<DesktopMethods>;
56
58
  local_mcp?: LocalMcpClient;
57
- on_change: (listener: () => void) => () => void;
59
+ on_change: (listener: (change: DataChange | null) => void) => () => void;
58
60
  on_event?: (event: string, listener: (data: unknown) => void) => () => void;
59
61
  }
@@ -1,5 +1,6 @@
1
1
  // What the base app's hosts and processes say to each other: the page's api on every host, and the desktop app's own
2
2
  // settings, which its daemon keeps beside the database rather than syncing, since they belong to the computer.
3
+ export { data_change_of } from "../sync_protocol.js";
3
4
  export const desktop_setting_defaults = {
4
5
  show_tray_icon: true,
5
6
  keep_running_in_background: true,
@@ -3,7 +3,7 @@ import { type FastifyInstance } from "fastify";
3
3
  import { type BackupMethods } from "../backups.ts";
4
4
  import { AccountStore } from "../server/account_store.ts";
5
5
  import { EventStream } from "../server/events.ts";
6
- import type { SqlDatabase } from "../sql.ts";
6
+ import { type SqlDatabase } from "../sql.ts";
7
7
  import { type SyncPeer } from "../sync_peer.ts";
8
8
  import type { App } from "./define.ts";
9
9
  import { type StartServices } from "./services.ts";
@@ -18,6 +18,7 @@ export interface AppDatabase {
18
18
  close: () => void;
19
19
  }
20
20
  export declare function open_app_database(app: App, path: string, backups_folder: string): AppDatabase;
21
+ export declare function data_change_text(app: Pick<App, "take_data_change">, database: () => SqlDatabase): () => string;
21
22
  export declare function watch_outside_changes(database: () => SqlDatabase, on_change: () => void, every_ms?: number): () => void;
22
23
  export declare const call_body_limit: number;
23
24
  export declare function call_args(app: App, method: string, body: unknown): unknown[];
@@ -24,6 +24,7 @@ import { BAD_JSON, register_error_replies, register_lenient_json_body, send_text
24
24
  import { sqlite_backups } from "../server/sqlite_backups.js";
25
25
  import { register_sync_peer_routes } from "../server/sync_peer_routes.js";
26
26
  import { register_web_folder } from "../server/web_folder.js";
27
+ import { tidy_database, tidy_every_ms } from "../sql.js";
27
28
  import { file_sync_storage } from "../sync_file_storage.js";
28
29
  import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
29
30
  import { declared_file_of, no_services, side_databases } from "./services.js";
@@ -48,6 +49,7 @@ export function open_app_database(app, path, backups_folder) {
48
49
  open: () => {
49
50
  database = new DatabaseSync(path);
50
51
  start(database);
52
+ tidy_database(database);
51
53
  restore_hooks.after?.();
52
54
  },
53
55
  // The restored data no longer matches other devices', so sync asks again which copy wins.
@@ -64,6 +66,17 @@ export function open_app_database(app, path, backups_folder) {
64
66
  start(database);
65
67
  adopt_schedule_file(app, database, join(dirname(path), "backup-schedule.json"));
66
68
  const keeper = keep_backing_up(kept, () => app.read_backup_schedule(database));
69
+ // The file is tidied on opening and once a day, so space freed by pruning and clean-ups goes back to the disk.
70
+ tidy_database(database);
71
+ const tidy_timer = setInterval(() => {
72
+ try {
73
+ tidy_database(database);
74
+ }
75
+ catch {
76
+ // Closed for a restore, which tidies the copy it opens.
77
+ }
78
+ }, tidy_every_ms);
79
+ tidy_timer.unref?.();
67
80
  return {
68
81
  database: () => database,
69
82
  back_up: async () => void (await kept.create()),
@@ -71,6 +84,7 @@ export function open_app_database(app, path, backups_folder) {
71
84
  on_restore: (hooks) => void (restore_hooks = hooks),
72
85
  close: () => {
73
86
  keeper.stop();
87
+ clearInterval(tidy_timer);
74
88
  database.close();
75
89
  },
76
90
  };
@@ -89,6 +103,17 @@ function adopt_schedule_file(app, database, file) {
89
103
  app.adopt_backup_schedule(database, saved);
90
104
  rmSync(file, { force: true });
91
105
  }
106
+ // What a change event carries: the tables written since the last one, or nothing when that cannot be told, as mid-restore.
107
+ export function data_change_text(app, database) {
108
+ return () => {
109
+ try {
110
+ return JSON.stringify(app.take_data_change(database()));
111
+ }
112
+ catch {
113
+ return "";
114
+ }
115
+ };
116
+ }
92
117
  // Another program, such as an older build of the app, may write the database file; SQLite moves data_version only
93
118
  // for another connection's commits, so this one's own writes never count. Checked every second; returns how to stop.
94
119
  export function watch_outside_changes(database, on_change, every_ms = 1000) {
@@ -244,8 +269,8 @@ export async function run_server(app, options) {
244
269
  ...(app.token_prefix ? { token_prefix: app.token_prefix } : {}),
245
270
  declared: load_accounts(`${prefix}_PASSWORD_HASH_FILE`, server_config.values.password_hash_file),
246
271
  });
247
- // Every page hears of a change, whether a page or another device made it.
248
- const changes = new EventStream();
272
+ // Every page hears of a change, whether a page or another device made it, and which tables it touched.
273
+ const changes = new EventStream({ change_data: data_change_text(app, opened.database) });
249
274
  // The server is one sync peer among the devices, kept beside the data so a restore leaves its pairings be.
250
275
  const sync = create_sync_peer({
251
276
  app: app.id,
@@ -1,6 +1,6 @@
1
1
  import { type BackupFolderPlugin } from "../../phone_backups.ts";
2
2
  import { type FileStore } from "../../web/sqlite_wasm.ts";
3
- import type { SqlDatabase } from "../../sql.ts";
3
+ import { type SqlDatabase } from "../../sql.ts";
4
4
  import type { App } from "../define.ts";
5
5
  import type { PageApi } from "../protocol.ts";
6
6
  export interface PhoneLifecycle {
@@ -8,6 +8,7 @@ import { phone_certificates } from "../../phone_certificates.js";
8
8
  import { create_sync_peer, sync_device_methods } from "../../sync_peer.js";
9
9
  import { indexed_db_files, open_wasm_database } from "../../web/sqlite_wasm.js";
10
10
  import { local_sync_storage } from "../../web/sync_storage.js";
11
+ import { tidy_database, tidy_every_ms } from "../../sql.js";
11
12
  // An older version kept the phone's backup schedule in the page's storage; it moves into the setting once.
12
13
  function adopt_stored_schedule(app, database, storage) {
13
14
  const key = `${app.id}-backup-schedule`;
@@ -55,13 +56,23 @@ export async function android_api(app, options = {}) {
55
56
  await kept.create();
56
57
  app.open_store(database.connection);
57
58
  adopt_stored_schedule(app, database.connection, options.storage ?? page_storage());
59
+ // Tidied on opening and on coming back after a day or more, so freed space leaves the phone's storage too.
60
+ let tidied_at = Date.now();
61
+ tidy_database(database.connection);
58
62
  await database.save_now();
59
63
  const keeper = keep_backing_up(kept, () => app.read_backup_schedule(database.connection));
60
64
  const services = options.services ? await options.services({ database: () => database.connection }) : {};
61
65
  const listeners = new Set();
62
66
  const announce = () => {
67
+ let change = null;
68
+ try {
69
+ change = app.take_data_change(database.connection);
70
+ }
71
+ catch {
72
+ // A database closed mid-restore cannot tell, so the page fetches everything.
73
+ }
63
74
  for (const listener of listeners)
64
- listener();
75
+ listener(change);
65
76
  services.changed?.();
66
77
  };
67
78
  // The paired devices and keys stay in the app's private storage; before another copy replaces this one the data is
@@ -73,6 +84,11 @@ export async function android_api(app, options = {}) {
73
84
  // A phone may close the app at any moment once it is in the background, so the database is saved straight away.
74
85
  lifecycle.addListener("pause", () => void database.save_now());
75
86
  lifecycle.addListener("resume", () => {
87
+ if (Date.now() - tidied_at >= tidy_every_ms) {
88
+ tidied_at = Date.now();
89
+ if (tidy_database(database.connection))
90
+ void database.save_now();
91
+ }
76
92
  void sync.sync_now();
77
93
  services.changed?.();
78
94
  });
@@ -1,5 +1,5 @@
1
1
  import type { App } from "../define.ts";
2
- import type { PageApi } from "../protocol.ts";
2
+ import { type PageApi } from "../protocol.ts";
3
3
  export declare function web_api(app: Pick<App, "bridges">): PageApi;
4
4
  export declare function is_desktop(app: Pick<App, "bridges">): boolean;
5
5
  export declare function desktop_api(app: Pick<App, "bridges"> & Partial<Pick<App, "local_mcp">>): Promise<PageApi>;
@@ -3,6 +3,7 @@
3
3
  // this computer's daemon or to the server Settings → Connections chose.
4
4
  import { LOCAL_CONNECTION_ID } from "../../connection_protocol.js";
5
5
  import { LoginNeeded } from "../../web/states.js";
6
+ import { data_change_of } from "../protocol.js";
6
7
  // ── Web ──────────────────────────────────────────────────────────────────────
7
8
  // Relative, so a server behind a proxy under a folder keeps it.
8
9
  const call_path = "api/call/";
@@ -31,10 +32,10 @@ function follow_changes(on_change, on_client_id, named) {
31
32
  events.addEventListener("hello", (event) => {
32
33
  on_client_id(event.data);
33
34
  if (has_connected)
34
- on_change();
35
+ on_change(null);
35
36
  has_connected = true;
36
37
  });
37
- events.addEventListener("changed", on_change);
38
+ events.addEventListener("changed", (message) => on_change(data_change_of(message.data)));
38
39
  // The browser retries a dropped stream by itself but gives up on a refused one, so the page tries again later.
39
40
  events.addEventListener("error", () => {
40
41
  if (events.readyState === EventSource.CLOSED)
@@ -66,9 +67,9 @@ export function web_api(app) {
66
67
  }
67
68
  const listeners = new Set();
68
69
  const named = new Map();
69
- const listen_for = follow_changes(() => {
70
+ const listen_for = follow_changes((change) => {
70
71
  for (const listener of listeners)
71
- listener();
72
+ listener(change);
72
73
  }, (given) => (client_id = given), named);
73
74
  const { bridges } = app;
74
75
  return {
@@ -1,6 +1,6 @@
1
1
  import type { Connections } from "./connections.ts";
2
2
  import type { DaemonLink } from "./daemon_link.ts";
3
- import type { SyncStatus } from "./sync_protocol.ts";
3
+ import { type DataChange, type SyncStatus } from "./sync_protocol.ts";
4
4
  export interface DaemonRouterOptions {
5
5
  connections: Pick<Connections, "current" | "subscribe">;
6
6
  link: Pick<DaemonLink, "call" | "follow_events">;
@@ -10,7 +10,7 @@ export interface DaemonRouterOptions {
10
10
  is_read_only?: (name: string) => boolean;
11
11
  events_path?: string;
12
12
  api_prefix?: string;
13
- on_change: () => void;
13
+ on_change: (change: DataChange | null) => void;
14
14
  on_sync_status?: (status: SyncStatus) => void;
15
15
  on_event?: (event: string, data: string) => void;
16
16
  on_switch: () => void;
@@ -3,6 +3,7 @@
3
3
  // such as its sync and trusted certificates. It follows the chosen daemon's events, starts this computer's daemon
4
4
  // again when it went away, and tells the app when another daemon was chosen, so the page never knows where its daemon
5
5
  // runs. It holds no Electron, so the app gives it the windows' side as callbacks.
6
+ import { data_change_of } from "./sync_protocol.js";
6
7
  // What stays on this computer in every app: its sync, its trusted certificates, its MCP endpoint and its own settings.
7
8
  export const default_local_tables = ["device", "certificates", "local_mcp", "daemon"];
8
9
  // ── Router ───────────────────────────────────────────────────────────────────
@@ -46,13 +47,13 @@ export function create_daemon_router(options) {
46
47
  if (event === "hello")
47
48
  client_id = data;
48
49
  else if (event === "changed")
49
- options.on_change();
50
+ options.on_change(data_change_of(data));
50
51
  else if (event === "sync_status")
51
52
  options.on_sync_status?.(JSON.parse(data));
52
53
  else
53
54
  options.on_event?.(event, data);
54
55
  }, {
55
- on_connect: options.on_change,
56
+ on_connect: () => options.on_change(null),
56
57
  on_disconnect: () => {
57
58
  if (!is_quitting && is_here() && options.restart_local)
58
59
  void options.restart_local().catch(on_error);
package/dist/history.js CHANGED
@@ -29,7 +29,8 @@ export function create_history(options) {
29
29
  CREATE INDEX IF NOT EXISTS ${versions}_by_time ON ${versions} (changed_at);
30
30
  CREATE TABLE IF NOT EXISTS ${pending} (${item_column} TEXT PRIMARY KEY) WITHOUT ROWID`;
31
31
  // For the sync engine's tables, so every device has every version.
32
- const synced_table = { name: versions, key_columns: ["uid"], local_columns: ["id"] };
32
+ // A version is never changed once saved, so it syncs as one value rather than one per column.
33
+ const synced_table = { name: versions, key_columns: ["uid"], local_columns: ["id"], rows_never_change: true };
33
34
  // ── Triggers ─────────────────────────────────────────────────────────────
34
35
  const triggers = options.watches.flatMap((watch) => ["insert", "update", "delete"].map((event) => {
35
36
  const row = event === "delete" ? "OLD" : "NEW";
@@ -46,6 +47,7 @@ export function create_history(options) {
46
47
  // a first version as it stands now, with an id every device gives it alike.
47
48
  function install(database) {
48
49
  database.exec(schema);
50
+ drop_duplicate_indexes(database);
49
51
  drop_triggers(database);
50
52
  for (const trigger of triggers)
51
53
  database.exec(`CREATE TRIGGER ${trigger.name} ${trigger.sql}`);
@@ -58,6 +60,17 @@ export function create_history(options) {
58
60
  insert(database, `first_seen:${id}`, String(id), options.created_at?.(snapshot) ?? new Date().toISOString(), "first_seen", site, null, snapshot);
59
61
  }
60
62
  }
63
+ // An index an app made itself on the same columns as the item index only slows every write, so it goes.
64
+ function drop_duplicate_indexes(database) {
65
+ const columns_of = (index) => database.prepare(`PRAGMA index_info("${index}")`).all().map((column) => column.name).join(",");
66
+ const indexes = database.prepare(`PRAGMA index_list("${versions}")`).all();
67
+ const item_index = `${versions}_by_item`;
68
+ const item_columns = columns_of(item_index);
69
+ for (const index of indexes) {
70
+ if (index.name !== item_index && index.origin === "c" && index.unique === 0 && columns_of(index.name) === item_columns)
71
+ database.exec(`DROP INDEX "${index.name}"`);
72
+ }
73
+ }
61
74
  // Writes that arrive by sync touch items too, but their versions come from the device that made them; pass it as the
62
75
  // sync engine's after_apply.
63
76
  function forget_touched(database) {
@@ -5,6 +5,7 @@ export interface EventStreamOptions {
5
5
  hello_event?: string | null;
6
6
  changed_event?: string;
7
7
  client_id_header?: string;
8
+ change_data?: () => string;
8
9
  }
9
10
  export interface StreamClient {
10
11
  id: string;
@@ -22,6 +23,7 @@ export declare class EventStream {
22
23
  readonly hello_event: string | null;
23
24
  readonly changed_event: string;
24
25
  readonly client_id_header: string;
26
+ private readonly change_data;
25
27
  private readonly streams;
26
28
  constructor(options?: EventStreamOptions);
27
29
  get client_count(): number;
@@ -11,6 +11,7 @@ export class EventStream {
11
11
  hello_event;
12
12
  changed_event;
13
13
  client_id_header;
14
+ change_data;
14
15
  streams = new Map();
15
16
  constructor(options = {}) {
16
17
  this.heartbeat_ms = options.heartbeat_ms ?? 25_000;
@@ -18,6 +19,7 @@ export class EventStream {
18
19
  this.hello_event = options.hello_event === undefined ? "hello" : options.hello_event;
19
20
  this.changed_event = options.changed_event ?? "changed";
20
21
  this.client_id_header = options.client_id_header ?? default_client_id_header;
22
+ this.change_data = options.change_data ?? (() => "");
21
23
  }
22
24
  get client_count() {
23
25
  return this.streams.size;
@@ -39,7 +41,7 @@ export class EventStream {
39
41
  }
40
42
  // The page that made a change already shows it, so only the others are told.
41
43
  announce_change(except_client_id = "") {
42
- this.send("", { event: this.changed_event, except_client_id });
44
+ this.send(this.change_data(), { event: this.changed_event, except_client_id });
43
45
  }
44
46
  // Serves the stream on the path, and ends every stream when the app closes, since one never ends by itself.
45
47
  register(app, path = "/events") {
package/dist/sql.d.ts CHANGED
@@ -20,3 +20,8 @@ export interface MigrateOptions {
20
20
  owner?: string;
21
21
  }
22
22
  export declare function migrate(database: SqlDatabase, steps: readonly MigrationStep[], options?: MigrateOptions): void;
23
+ export declare const tidy_every_ms: number;
24
+ export interface TidyOptions {
25
+ free_share?: number;
26
+ }
27
+ export declare function tidy_database(database: SqlDatabase, options?: TidyOptions): boolean;
package/dist/sql.js CHANGED
@@ -38,3 +38,24 @@ export function migrate(database, steps, options = {}) {
38
38
  });
39
39
  }
40
40
  }
41
+ // ── Upkeep ───────────────────────────────────────────────────────────────────
42
+ // How often an app keeps its open database tidy.
43
+ export const tidy_every_ms = 24 * 60 * 60 * 1000;
44
+ // Refreshes the query planner's statistics, and rewrites the file without its empty pages once enough of it is empty;
45
+ // says whether it rewrote it. A rewrite held up by another connection's write is left for next time.
46
+ export function tidy_database(database, options = {}) {
47
+ database.exec("PRAGMA optimize");
48
+ const { page_count } = database.prepare("PRAGMA page_count").get();
49
+ const { freelist_count } = database.prepare("PRAGMA freelist_count").get();
50
+ if (page_count === 0 || freelist_count / page_count < (options.free_share ?? 0.1))
51
+ return false;
52
+ try {
53
+ database.exec("VACUUM");
54
+ }
55
+ catch {
56
+ return false;
57
+ }
58
+ // The rewrite passes through the write-ahead log, which is emptied so it does not keep the old size on disk.
59
+ database.exec("PRAGMA wal_checkpoint(TRUNCATE)");
60
+ return true;
61
+ }
@@ -6,6 +6,7 @@ export interface SyncedTable {
6
6
  local_columns?: string[];
7
7
  local_keys?: readonly string[];
8
8
  map_columns?: string[];
9
+ rows_never_change?: boolean;
9
10
  }
10
11
  export interface SyncEngineOptions {
11
12
  tables: SyncedTable[];
@@ -47,6 +48,10 @@ export declare function create_sync_engine(options: SyncEngineOptions): {
47
48
  has_unsent_changes: (database: SqlDatabase, device: string) => boolean;
48
49
  count_unsent_rows: (database: SqlDatabase, devices: readonly string[]) => number;
49
50
  collect_changes_since: (database: SqlDatabase, cursor: number, except_site: string) => CollectedChanges;
51
+ changed_tables_since: (database: SqlDatabase, cursor: number) => {
52
+ tables: string[];
53
+ up_to_seq: number;
54
+ };
50
55
  collect_snapshot: (database: SqlDatabase) => CollectedChanges;
51
56
  apply_changes: (database: SqlDatabase, changes: SyncChange[]) => number;
52
57
  claim_everything: (database: SqlDatabase, theirs: SyncChange[]) => void;
@@ -63,7 +63,13 @@ function add_missing_state_columns(database) {
63
63
  }
64
64
  // ── Engine ───────────────────────────────────────────────────────────────────
65
65
  export function create_sync_engine(options) {
66
- const tables = options.tables.map((table) => ({ ...table, local_columns: table.local_columns ?? [], local_keys: table.local_keys ?? [], map_columns: table.map_columns ?? [] }));
66
+ const tables = options.tables.map((table) => ({
67
+ ...table,
68
+ local_columns: table.local_columns ?? [],
69
+ local_keys: table.local_keys ?? [],
70
+ map_columns: table.map_columns ?? [],
71
+ rows_never_change: table.rows_never_change ?? false,
72
+ }));
67
73
  const tables_by_name = new Map(tables.map((table) => [table.name, table]));
68
74
  // The map column and key a cell names, or null for a cell of a whole value.
69
75
  function split_map_cell(table, cell_name) {
@@ -84,6 +90,10 @@ export function create_sync_engine(options) {
84
90
  function column_names(database, table) {
85
91
  return database.prepare(`PRAGMA table_info("${table.name}")`).all().map((column) => column.name);
86
92
  }
93
+ // The columns that keep a version of their own; a row that never changes keeps only the one saying it exists.
94
+ function stamped_columns(database, table) {
95
+ return table.rows_never_change ? [] : synced_columns(database, table);
96
+ }
87
97
  // The columns that sync as one value each.
88
98
  function synced_columns(database, table) {
89
99
  return column_names(database, table).filter((name) => !table.local_columns.includes(name) && !table.map_columns.includes(name));
@@ -144,8 +154,8 @@ export function create_sync_engine(options) {
144
154
  drop_triggers(database);
145
155
  const is_local = "(SELECT is_applying FROM sync_state) = 0";
146
156
  for (const table of tables) {
147
- const columns = synced_columns(database, table);
148
- const map_columns = synced_map_columns(database, table);
157
+ const columns = stamped_columns(database, table);
158
+ const map_columns = table.rows_never_change ? [] : synced_map_columns(database, table);
149
159
  const new_key = key_sql(table, "NEW");
150
160
  const old_key = key_sql(table, "OLD");
151
161
  database.exec(`CREATE TRIGGER ${trigger_name(table, "insert")} AFTER INSERT ON "${table.name}"
@@ -158,7 +168,8 @@ export function create_sync_engine(options) {
158
168
  ...columns.map((column) => stamp_cell_sql(table, new_key, column, `OLD."${column}" IS NOT NEW."${column}"`)),
159
169
  ...map_columns.map((column) => stamp_map_sql(table, new_key, column, changed_keys_sql(column))),
160
170
  ];
161
- database.exec(`CREATE TRIGGER ${trigger_name(table, "update")} AFTER UPDATE ON "${table.name}"
171
+ if (update_steps.length > 0)
172
+ database.exec(`CREATE TRIGGER ${trigger_name(table, "update")} AFTER UPDATE ON "${table.name}"
162
173
  WHEN ${is_local} AND ${filter_sql(table, "NEW")}
163
174
  BEGIN ${update_steps.join("\n")} END`);
164
175
  database.exec(`CREATE TRIGGER ${trigger_name(table, "delete")} AFTER DELETE ON "${table.name}"
@@ -166,18 +177,34 @@ export function create_sync_engine(options) {
166
177
  BEGIN ${stamp_cell_sql(table, old_key, exists_column)} END`);
167
178
  }
168
179
  backfill_cells(database);
180
+ compact_unchanging_rows(database);
181
+ }
182
+ // A row that never changes needs only its existence cell, which takes the newest version any of its cells had.
183
+ function compact_unchanging_rows(database) {
184
+ for (const table of tables.filter((each) => each.rows_never_change)) {
185
+ const has_extra = database.prepare("SELECT 1 FROM sync_cells WHERE table_name = ? AND column_name != ? LIMIT 1").get(table.name, exists_column);
186
+ if (!has_extra)
187
+ continue;
188
+ database
189
+ .prepare(`UPDATE sync_cells AS row_cell SET
190
+ ts = (SELECT max(ts) FROM sync_cells AS cell WHERE cell.table_name = row_cell.table_name AND cell.row_key = row_cell.row_key),
191
+ seq = (SELECT max(seq) FROM sync_cells AS cell WHERE cell.table_name = row_cell.table_name AND cell.row_key = row_cell.row_key)
192
+ WHERE table_name = ? AND column_name = ?`)
193
+ .run(table.name, exists_column);
194
+ database.prepare("DELETE FROM sync_cells WHERE table_name = ? AND column_name != ?").run(table.name, exists_column);
195
+ }
169
196
  }
170
197
  // Rows written before sync existed, and columns added since, get a version older than any real write.
171
198
  function backfill_cells(database) {
172
199
  for (const table of tables) {
173
- for (const column of [exists_column, ...synced_columns(database, table)]) {
200
+ for (const column of [exists_column, ...stamped_columns(database, table)]) {
174
201
  database
175
202
  .prepare(`INSERT OR IGNORE INTO sync_cells (table_name, row_key, column_name, ts, site, seq)
176
203
  SELECT '${table.name}', ${key_sql(table, "row")}, '${column}', 0, '', 0 FROM "${table.name}" AS row WHERE ${filter_sql(table, "row")}`)
177
204
  .run();
178
205
  }
179
206
  // A column that has just become a map column gives each of its keys the version the whole value had.
180
- for (const column of synced_map_columns(database, table)) {
207
+ for (const column of table.rows_never_change ? [] : synced_map_columns(database, table)) {
181
208
  const row_key = key_sql(table, "row");
182
209
  database
183
210
  .prepare(`INSERT OR IGNORE INTO sync_cells (table_name, row_key, column_name, ts, site, seq)
@@ -254,6 +281,13 @@ export function create_sync_engine(options) {
254
281
  return row.count;
255
282
  }
256
283
  // ── Reading changes ──────────────────────────────────────────────────────
284
+ // The synced tables with a change after the cursor, and how far that reaches; tables with rows kept on one device always count, as those rows' writes leave no version.
285
+ function changed_tables_since(database, cursor) {
286
+ const { last_seq } = read_state(database);
287
+ const stamped = database.prepare("SELECT DISTINCT table_name FROM sync_cells WHERE seq > ? AND seq <= ?").all(cursor, last_seq).map((row) => row.table_name);
288
+ const unstamped = tables.filter((table) => table.local_keys.length > 0).map((table) => table.name);
289
+ return { tables: [...new Set([...stamped, ...unstamped])], up_to_seq: last_seq };
290
+ }
257
291
  function read_row(database, table, row_key) {
258
292
  return database.prepare(`SELECT * FROM "${table.name}" AS row WHERE ${key_sql(table, "row")} = ? AND ${filter_sql(table, "row")}`).get(row_key);
259
293
  }
@@ -271,8 +305,14 @@ export function create_sync_engine(options) {
271
305
  const row = rows.get(row_id);
272
306
  const base = { table: cell.table_name, key: cell.row_key, column: cell.column_name, ts: cell.ts, site: cell.site };
273
307
  const map_cell = split_map_cell(table, cell.column_name);
274
- if (cell.column_name === exists_column)
308
+ if (cell.column_name === exists_column) {
275
309
  changes.push({ ...base, value: row ? 1 : 0 });
310
+ // A row that never changes sends all its values under the version of its existence.
311
+ if (row && table.rows_never_change) {
312
+ for (const column of Object.keys(row).filter((name) => !table.local_columns.includes(name)))
313
+ changes.push({ ...base, column, value: row[column] });
314
+ }
315
+ }
276
316
  else if (map_cell) {
277
317
  if (row && map_cell.column in row)
278
318
  changes.push({ ...base, value: object_of(row[map_cell.column])[map_cell.key] ?? null });
@@ -328,18 +368,30 @@ export function create_sync_engine(options) {
328
368
  if (exists_change.value === 1 && !exists) {
329
369
  const values = [
330
370
  ...changes.filter((change) => change.column !== exists_column && known_columns.includes(change.column)).map((change) => [change.column, change.value]),
331
- ...known_map_columns.map((column) => [column, "{}"]),
371
+ ...known_map_columns.map((column) => [column, table.rows_never_change ? (changes.find((change) => change.column === column)?.value ?? "{}") : "{}"]),
332
372
  ];
333
373
  database
334
374
  .prepare(`INSERT INTO "${table.name}" (${values.map(([column]) => `"${column}"`).join(", ")}) VALUES (${values.map(() => "?").join(", ")})`)
335
375
  .run(...values.map(([, value]) => value));
336
376
  exists = true;
337
377
  }
378
+ // A newer version of a row that never changes replaces its values, so devices that each wrote it end alike.
379
+ else if (exists_change.value === 1 && table.rows_never_change) {
380
+ const values = changes.filter((change) => change.column !== exists_column && known_columns.includes(change.column));
381
+ for (const change of values) {
382
+ database
383
+ .prepare(`UPDATE "${table.name}" SET "${change.column}" = ? WHERE rowid IN (SELECT rowid FROM "${table.name}" AS row WHERE ${where_row})`)
384
+ .run(change.value, row_key);
385
+ }
386
+ }
338
387
  if (exists_change.value === 0 && exists) {
339
388
  database.prepare(`DELETE FROM "${table.name}" WHERE rowid IN (SELECT rowid FROM "${table.name}" AS row WHERE ${where_row})`).run(row_key);
340
389
  exists = false;
341
390
  }
342
391
  }
392
+ // A row that never changes took its values with its existence above.
393
+ if (table.rows_never_change)
394
+ return applied;
343
395
  for (const change of changes) {
344
396
  const map_cell = split_map_cell(table, change.column);
345
397
  const is_known = map_cell ? known_map_columns.includes(map_cell.column) : known_columns.includes(change.column);
@@ -423,7 +475,8 @@ export function create_sync_engine(options) {
423
475
  const add_cell = database.prepare("INSERT OR IGNORE INTO sync_cells (table_name, row_key, column_name, ts, site, seq) VALUES (?, ?, ?, ?, '', 0)");
424
476
  for (const change of theirs) {
425
477
  const table = tables_by_name.get(change.table);
426
- if (table && !table.local_keys.includes(change.key))
478
+ const is_unstamped = table?.rows_never_change && change.column !== exists_column;
479
+ if (table && !table.local_keys.includes(change.key) && !is_unstamped)
427
480
  add_cell.run(change.table, change.key, change.column, change.ts);
428
481
  }
429
482
  const newest_here = database.prepare("SELECT coalesce(max(ts), 0) AS ts FROM sync_cells").get().ts;
@@ -452,6 +505,7 @@ export function create_sync_engine(options) {
452
505
  has_unsent_changes,
453
506
  count_unsent_rows,
454
507
  collect_changes_since,
508
+ changed_tables_since,
455
509
  collect_snapshot,
456
510
  apply_changes,
457
511
  claim_everything,
@@ -180,3 +180,7 @@ export declare const peer_listening_method_names: readonly ["get_peer_listening"
180
180
  export type PeerListeningClient = {
181
181
  [Name in keyof PeerListeningMethods]: (...args: Parameters<PeerListeningMethods[Name]>) => Promise<Awaited<ReturnType<PeerListeningMethods[Name]>>>;
182
182
  };
183
+ export interface DataChange {
184
+ tables: readonly string[];
185
+ }
186
+ export declare function data_change_of(text: string): DataChange | null;
@@ -22,3 +22,14 @@ export const sync_device_method_names = [
22
22
  "sync_now",
23
23
  ];
24
24
  export const peer_listening_method_names = ["get_peer_listening", "set_peer_listening"];
25
+ // A change event's data as sent; anything else, such as an older daemon's empty data, means anything may have changed.
26
+ export function data_change_of(text) {
27
+ try {
28
+ const parsed = JSON.parse(text);
29
+ const tables = parsed?.tables;
30
+ return Array.isArray(tables) && tables.every((table) => typeof table === "string") ? { tables } : null;
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
@@ -16,11 +16,13 @@ export interface TreeMove {
16
16
  export interface DropOptions {
17
17
  by_list_order?: boolean;
18
18
  }
19
+ export declare function item_by_id<Item extends TreeItem>(items: readonly Item[], id: string | null): Item | undefined;
20
+ export declare function with_ancestors<Item extends TreeItem>(item: Item, items: readonly Item[]): Item[];
19
21
  export declare function by_position<Item extends {
20
22
  position: number;
21
23
  }>(first: Item, second: Item): number;
22
24
  export declare function children_of<Item extends TreeItem>(parent_id: string | null, items: Item[]): Item[];
23
- export declare function subtree_ids(item_id: string, items: TreeItem[]): Set<string>;
25
+ export declare function subtree_ids(item_id: string, items: readonly TreeItem[]): Set<string>;
24
26
  export declare function nest<Item extends TreeItem>(shown: Item[], all?: Item[]): TreeNode<Item>[];
25
27
  export declare function in_tree_order<Item extends TreeItem>(items: Item[], reversed?: boolean): Item[];
26
28
  export declare function path_names<Item extends TreeItem>(item: Item, items: Item[], name_of: (item: Item) => string): string[];
package/dist/web/tree.js CHANGED
@@ -1,4 +1,38 @@
1
1
  // Trees of rows that name their parent and their place among siblings, and where a dragged or keyed row lands.
2
+ // Made once per list and reused while it keeps its length; a list whose items are edited in place must be copied first.
3
+ const indexes = new WeakMap();
4
+ function index_of(items) {
5
+ const kept = indexes.get(items);
6
+ if (kept && kept.length === items.length)
7
+ return kept;
8
+ const index = { length: items.length, by_id: new Map(), child_ids: new Map() };
9
+ for (const item of items) {
10
+ index.by_id.set(item.id, item);
11
+ const siblings = index.child_ids.get(item.parent_id);
12
+ if (siblings)
13
+ siblings.push(item.id);
14
+ else
15
+ index.child_ids.set(item.parent_id, [item.id]);
16
+ }
17
+ indexes.set(items, index);
18
+ return index;
19
+ }
20
+ // The item with the id, found without walking the list each time.
21
+ export function item_by_id(items, id) {
22
+ return id === null ? undefined : index_of(items).by_id.get(id);
23
+ }
24
+ // The item and every item above it, nearest first; stops at a missing parent or a loop.
25
+ export function with_ancestors(item, items) {
26
+ const chain = [item];
27
+ const seen = new Set([item.id]);
28
+ let parent = item_by_id(items, item.parent_id);
29
+ while (parent && !seen.has(parent.id)) {
30
+ chain.push(parent);
31
+ seen.add(parent.id);
32
+ parent = item_by_id(items, parent.parent_id);
33
+ }
34
+ return chain;
35
+ }
2
36
  // ── Shape ────────────────────────────────────────────────────────────────────
3
37
  export function by_position(first, second) {
4
38
  return first.position - second.position;
@@ -8,10 +42,11 @@ export function children_of(parent_id, items) {
8
42
  }
9
43
  // The item itself plus everything below it, at any depth.
10
44
  export function subtree_ids(item_id, items) {
45
+ const { child_ids } = index_of(items);
11
46
  const ids = new Set([item_id]);
12
47
  for (const id of ids) {
13
- for (const child of children_of(id, items))
14
- ids.add(child.id);
48
+ for (const child_id of child_ids.get(id) ?? [])
49
+ ids.add(child_id);
15
50
  }
16
51
  return ids;
17
52
  }
@@ -46,14 +81,7 @@ export function in_tree_order(items, reversed = false) {
46
81
  }
47
82
  // The names from the top of the tree down to the item, such as ["Work", "Clients"]; stops at a missing parent or a loop.
48
83
  export function path_names(item, items, name_of) {
49
- const item_by_id = new Map(items.map((each) => [each.id, each]));
50
- const path = [item];
51
- let parent = item.parent_id === null ? undefined : item_by_id.get(item.parent_id);
52
- while (parent && !path.includes(parent)) {
53
- path.unshift(parent);
54
- parent = parent.parent_id === null ? undefined : item_by_id.get(parent.parent_id);
55
- }
56
- return path.map(name_of);
84
+ return with_ancestors(item, items).reverse().map(name_of);
57
85
  }
58
86
  // ── Dropping ─────────────────────────────────────────────────────────────────
59
87
  // The top and bottom quarters of a row drop beside it and the middle drops into it, or halves when nothing drops inside.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-tech-laboratories/x-app",
3
- "version": "0.118.0",
3
+ "version": "0.120.0",
4
4
  "description": "Code the X-apps share: agents and their long runs, passwords and sign-in, the Fastify server pieces, durations, and the web page's helpers and widgets",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "repository": {