@x-tech-laboratories/x-app 0.125.0 → 0.126.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
@@ -267,8 +267,20 @@ An app whose work needs a computer, such as one that runs programs on checkouts,
267
267
  webhook, mail or Apprise). `context.withdraw(key)` takes it back wherever it shows, such as a call that stopped ringing.
268
268
  - **Following changes**: the services' `after_change(change)` runs after every change the pages hear of, whoever made
269
269
  it, with the synced tables written when known, such as to follow a setting; `after_remote_change` runs only for sync's.
270
- - **Plugins**: the services load `context.plugins_folder`; on the server the page loads the plugins' web sides from
271
- `/api/plugins/index.json`.
270
+ - **Plugins**: the services load `context.plugins_folder`; the page loads the plugins' web sides from
271
+ `page().plugin_base` (`index.json` and the files it names): a browser from the server's `/api/plugins/`, and a desktop
272
+ window through `page().read_plugin_file(path)` from the plugins folder of the daemon it works on.
273
+ - **Synced files**: `synced_files: { folder: "covers", referenced }` keeps files named by their content beside the
274
+ database on every host, the phone's in IndexedDB, and sync sends the ones `referenced(database)` still names. The
275
+ services keep them through `context.files`, the server and daemon serve them at `/api/files/<name>` to those signed
276
+ in, and the page shows one from `page().file_src(name)`: the server's route, the desktop's `<id>-file://<name>` from
277
+ this computer or the server in use, or a blob on the phone.
278
+ - **Keys in a settings export**: `render_app`'s `exports_secrets: true` offers "Include keys and tokens" on exporting
279
+ the settings, for an app whose settings hold other services' keys.
280
+ - **Links to other apps**: `run_desktop`'s `external_schemes`, such as `["stremio:", "steam:"]`, opens those links in
281
+ the apps installed for them, beside http and mailto.
282
+ - **Work after the answer**: a call returning `new Background(answer, finished)` answers at once; its writes so far are
283
+ recorded and announced, and again once `finished` settles, such as a refresh that downloads as it goes.
272
284
  - **Other devices**: `remote_access: true` lets the daemon serve its calls and host tables on the network, and
273
285
  `phone: "portal"` makes the phone a window onto a host chosen under Connections, keeping no data, its notices shown
274
286
  through `phone_notifications` (Capacitor's `LocalNotifications`).
@@ -20,6 +20,8 @@ import { file_sync_storage } from "../sync_file_storage.js";
20
20
  import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
21
21
  import { keep_listening_for_peers } from "../sync_peer_listening.js";
22
22
  import { mcp_tools, register_host_tables } from "./host_tables.js";
23
+ import { folder_file_store } from "../node_file_store.js";
24
+ import { register_synced_files } from "../server/synced_file_route.js";
23
25
  import { notice_event, notice_withdrawn_event, notice_is_on, read_desktop_settings } from "./protocol.js";
24
26
  import { create_remote_access } from "./remote_access.js";
25
27
  import { declared_file_of, no_services, side_databases } from "./services.js";
@@ -41,12 +43,15 @@ export async function start_daemon(app, options) {
41
43
  const certificates = create_certificate_trust({ file: join(profile, "trusted-certificates.json"), use_in_node: true });
42
44
  // Off until "Let other devices connect" is turned on; then other devices reach this computer's sync on its port.
43
45
  const listening = keep_listening_for_peers({ peer: () => sync, app: app.id, file: join(profile, "sync-listening.json"), default_port: options.default_peer_port ?? app.ports.peer });
46
+ // The app's synced files, such as covers, kept beside the database.
47
+ const files = app.synced_files ? folder_file_store(join(profile, app.synced_files.folder)) : null;
44
48
  // This computer is one sync peer among the devices, reaching out to the ones it is paired with.
45
49
  const sync = create_sync_peer({
46
50
  app: app.id,
47
51
  engine: app.sync_engine,
48
52
  database: opened.database,
49
53
  storage: file_sync_storage({ file: join(profile, "sync-peers.json"), back_up_before_replace: opened.back_up }),
54
+ ...(files ? { files: { store: files, referenced: app.synced_files.referenced } } : {}),
50
55
  device_name: `${app.name} on ${hostname()}`,
51
56
  addresses: () => listening.addresses(),
52
57
  on_remote_change: () => {
@@ -127,6 +132,7 @@ export async function start_daemon(app, options) {
127
132
  backup_methods: opened.backup_methods,
128
133
  kind: "desktop",
129
134
  services: services_now,
135
+ files,
130
136
  ...(options.routes ? { routes: options.routes } : {}),
131
137
  ...(https ? { https } : {}),
132
138
  }),
@@ -154,6 +160,8 @@ export async function start_daemon(app, options) {
154
160
  // This computer's own window reaches every host table, those kept to it included.
155
161
  const reach = { kind: "desktop", from_network: false, is_admin: () => true, has_role: () => true };
156
162
  register_host_tables(api, app, reach, services_now, changes);
163
+ if (files)
164
+ register_synced_files(api, files);
157
165
  }, { prefix: "/api" });
158
166
  // ── Lifecycle ──────────────────────────────────────────────────────
159
167
  let stopping = null;
@@ -203,6 +211,7 @@ export async function start_daemon(app, options) {
203
211
  declared_tokens: () => [],
204
212
  reread_declared_tokens: () => undefined,
205
213
  plugins_folder: join(profile, "plugins"),
214
+ files,
206
215
  declared_file: options.declared_file ?? `/etc/${app.id}/declared.json`,
207
216
  announce: (client_id) => changes.announce_change(client_id),
208
217
  wrote: () => {
@@ -42,8 +42,14 @@ export interface HostTable<Methods = Record<string, (...args: never[]) => unknow
42
42
  export declare function route_of(table: HostTable, method: string): string | null;
43
43
  declare const host_table_route: (name: string) => string;
44
44
  type UnionToIntersection<Union> = (Union extends unknown ? (value: Union) => void : never) extends (value: infer Both) => void ? Both : never;
45
+ export declare class Background<Answer> {
46
+ readonly answer: Answer;
47
+ readonly finished: Promise<unknown>;
48
+ constructor(answer: Answer, finished: Promise<unknown>);
49
+ }
50
+ type Answer<Result> = Result extends Background<infer Carried> ? Carried : Result;
45
51
  type Bound<Methods> = {
46
- [Name in keyof Methods]: Methods[Name] extends (database: SqlDatabase, ...args: infer Args) => infer Result ? (...args: Args) => Result : never;
52
+ [Name in keyof Methods]: Methods[Name] extends (database: SqlDatabase, ...args: infer Args) => infer Result ? (...args: Args) => Answer<Result> : never;
47
53
  };
48
54
  type StoreMethodsOf<Features extends readonly Feature[]> = UnionToIntersection<Features[number]["methods"]>;
49
55
  export type AppMethods<Features extends readonly Feature[]> = Bound<SettingsMethods & StoreMethodsOf<Features>>;
@@ -81,6 +87,10 @@ export interface AppOptions<Features extends readonly Feature[]> {
81
87
  local_mcp?: {
82
88
  default_port: number;
83
89
  };
90
+ synced_files?: {
91
+ folder: string;
92
+ referenced: (database: SqlDatabase) => string[];
93
+ };
84
94
  synced_theme?: boolean;
85
95
  host_tables?: Readonly<Record<string, HostTable>>;
86
96
  remote_access?: boolean;
@@ -158,6 +168,10 @@ export declare function define_app<const Features extends readonly Feature[]>(op
158
168
  local_mcp?: {
159
169
  default_port: number;
160
170
  };
171
+ synced_files?: {
172
+ folder: string;
173
+ referenced: (database: SqlDatabase) => string[];
174
+ };
161
175
  synced_theme?: boolean;
162
176
  remote_access?: boolean;
163
177
  phone?: "device" | "portal";
@@ -34,6 +34,16 @@ export function route_of(table, method) {
34
34
  }
35
35
  // The path a host table's calls are posted under, such as /api/stages/.
36
36
  const host_table_route = (name) => `/api/${name}/`;
37
+ // A call's answer while its work goes on, such as a library refresh: the caller has the answer at once, and the
38
+ // features' catch-up, the history and the other pages follow once the work has finished, as after any write.
39
+ export class Background {
40
+ answer;
41
+ finished;
42
+ constructor(answer, finished) {
43
+ this.answer = answer;
44
+ this.finished = finished;
45
+ }
46
+ }
37
47
  // The settings every app keeps: how long its history reaches back, and this device's backup schedule.
38
48
  export const base_setting_defaults = {
39
49
  // How many days of changes the history keeps, each item keeping its newest version; 0 keeps them all.
@@ -170,7 +180,14 @@ export function define_app(options) {
170
180
  on_change();
171
181
  return value;
172
182
  };
173
- return result instanceof Promise ? result.then(done) : done(result);
183
+ if (result instanceof Promise)
184
+ return result.then(done);
185
+ if (!(result instanceof Background))
186
+ return done(result);
187
+ // The write so far is announced now, and again once the work it left running has finished.
188
+ done(undefined);
189
+ void result.finished.then(() => done(undefined), () => done(undefined));
190
+ return result.answer;
174
191
  };
175
192
  return [name, call];
176
193
  });
@@ -6,6 +6,7 @@ import { type TrayElectronLike, type TrayLike, type TrayRow } from "../electron/
6
6
  import { type BrowserWindowLike, type BrowserWindowOptionsLike, type NativeThemeLike, type ScreenLike, type ShellLike } from "../electron/window.ts";
7
7
  import { call_daemon, start_daemon } from "../local_daemon.ts";
8
8
  import type { App } from "./define.ts";
9
+ import { type ProtocolLike } from "../electron/file_protocol.ts";
9
10
  import { type AppNotice } from "./protocol.ts";
10
11
  type DesktopWindow = BrowserWindowLike & FocusableWindowLike & WindowLike & {
11
12
  webContents: {
@@ -71,6 +72,7 @@ export interface ElectronLike {
71
72
  }): unknown;
72
73
  };
73
74
  };
75
+ protocol?: ProtocolLike;
74
76
  }
75
77
  export interface SaveDialogOptionsLike {
76
78
  defaultPath: string;
@@ -104,6 +106,7 @@ export interface DesktopOptions {
104
106
  width: number;
105
107
  height: number;
106
108
  };
109
+ external_schemes?: string[];
107
110
  argv?: string[];
108
111
  env?: NodeJS.ProcessEnv;
109
112
  cwd?: string;
@@ -23,7 +23,10 @@ import { call_daemon, daemon_log_path, daemon_socket_path, start_daemon } from "
23
23
  import { peer_listening_method_names, sync_device_method_names } from "../sync_protocol.js";
24
24
  import { route_of_link } from "./links.js";
25
25
  import { remote_access_method_names } from "../remote_access_protocol.js";
26
- import { host_ability_method_names, notice_event, notice_is_on, notice_withdrawn_event } from "./protocol.js";
26
+ import { file_response, register_file_scheme } from "../electron/file_protocol.js";
27
+ import { folder_file_store } from "../node_file_store.js";
28
+ import { read_plugin_file } from "../plugin_folder.js";
29
+ import { file_scheme_of, host_ability_method_names, notice_event, notice_is_on, notice_withdrawn_event } from "./protocol.js";
27
30
  // The Save dialog's options for a file name: Downloads with that name, offering files of its kind.
28
31
  export function save_dialog_options(file_name, downloads) {
29
32
  const extension = extname(file_name).slice(1);
@@ -124,7 +127,31 @@ export function run_desktop(app, electron, options) {
124
127
  window.webContents.reload();
125
128
  },
126
129
  });
127
- const { call, forwarded } = router;
130
+ const { call, forwarded, is_here } = router;
131
+ // A file a server serves by GET under its /api/, such as a synced file or a plugin's web side, fetched with this
132
+ // device's token; 404 while the window works on this computer.
133
+ async function fetch_from_server(path) {
134
+ const daemon = connections.current();
135
+ if (daemon?.kind !== "remote")
136
+ return new Response(null, { status: 404 });
137
+ const escaped = path.split("/").map((part) => encodeURIComponent(part)).join("/");
138
+ return fetch(`${daemon.address.replace(/\/+$/, "")}/api/${escaped}`, { headers: { authorization: `Bearer ${daemon.token}` } }).catch(() => new Response(null, { status: 502 }));
139
+ }
140
+ // The app's synced files come from this computer's folder, or from the server the window works on.
141
+ const synced_files = app.synced_files ? folder_file_store(join(profile, app.synced_files.folder)) : null;
142
+ function file_answer(request) {
143
+ return is_here() ? file_response(synced_files, request.url) : fetch_from_server(`files/${new URL(request.url).hostname}`);
144
+ }
145
+ // The plugins' web files of the daemon the window works on: this computer's plugins folder, or the server's.
146
+ async function read_plugin_web_file(path) {
147
+ if (is_here())
148
+ return read_plugin_file(join(profile, "plugins"), path);
149
+ const response = await fetch_from_server(`plugins/${path}`);
150
+ return response.ok ? response.text() : "";
151
+ }
152
+ // Named before the app is ready, as Electron asks, so the page may load the files from it.
153
+ if (synced_files && electron.protocol)
154
+ register_file_scheme(electron.protocol, file_scheme_of(app.id));
128
155
  // This computer's own settings, always from its own daemon.
129
156
  function get_desktop_settings() {
130
157
  return call("daemon/get_desktop_settings");
@@ -159,6 +186,7 @@ export function run_desktop(app, electron, options) {
159
186
  min_size: options.min_size ?? { width: 360, height: 480 },
160
187
  native_theme: electron.nativeTheme,
161
188
  shell: electron.shell,
189
+ ...(options.external_schemes ? { external_schemes: options.external_schemes } : {}),
162
190
  screen: electron.screen,
163
191
  state_file: join(profile, "window.json"),
164
192
  });
@@ -268,6 +296,7 @@ export function run_desktop(app, electron, options) {
268
296
  const picked = await dialog.showOpenDialog({ properties: ["openDirectory"], ...(current ? { defaultPath: current } : {}) });
269
297
  return picked.canceled ? null : (picked.filePaths[0] ?? null);
270
298
  },
299
+ read_plugin_file: read_plugin_web_file,
271
300
  show_data_path: async (which) => {
272
301
  if (which === "database")
273
302
  electron.shell.showItemInFolder?.(database_path);
@@ -288,6 +317,8 @@ export function run_desktop(app, electron, options) {
288
317
  electron.app.exit(1);
289
318
  return;
290
319
  }
320
+ if (synced_files && electron.protocol)
321
+ electron.protocol.handle(file_scheme_of(app.id), file_answer);
291
322
  register_bridges();
292
323
  router.start();
293
324
  await apply_window_settings().catch(() => undefined);
@@ -31,12 +31,15 @@ export interface DesktopMethods {
31
31
  get_data_paths: () => DataPaths;
32
32
  show_data_path: (which: keyof DataPaths) => void;
33
33
  pick_folder: (current: string) => string | null;
34
+ read_plugin_file: (path: string) => string;
34
35
  }
35
36
  export interface DataPaths {
36
37
  database: string;
37
38
  backups: string;
38
39
  }
39
- export declare const desktop_method_names: readonly ["get_desktop_settings", "set_desktop_setting", "quit_completely", "get_idle_seconds", "save_text_file", "set_window_theme", "get_data_paths", "show_data_path", "pick_folder"];
40
+ export declare const desktop_method_names: readonly ["get_desktop_settings", "set_desktop_setting", "quit_completely", "get_idle_seconds", "save_text_file", "set_window_theme", "get_data_paths", "show_data_path", "pick_folder", "read_plugin_file"];
41
+ export declare function file_scheme_of(app_id: string): string;
42
+ export declare const desktop_plugin_base = "x-app-plugins://local/";
40
43
  export interface DaemonMethods {
41
44
  get_desktop_settings: () => DesktopSettings;
42
45
  set_desktop_setting: (key: keyof DesktopSettings, value: boolean) => void;
@@ -88,6 +91,9 @@ export interface PageApi<Methods extends Record<keyof Methods, (...args: never[]
88
91
  };
89
92
  reread_abilities?: () => Promise<Pick<PageApi, "admin" | "tables">>;
90
93
  server_theme?: ServerTheme;
94
+ file_src?: (name: string) => Promise<string>;
95
+ plugin_base?: string;
96
+ read_plugin_file?: (path: string) => Promise<string>;
91
97
  on_change: (listener: (change: DataChange | null) => void) => () => void;
92
98
  on_event?: (event: string, listener: (data: unknown) => void) => () => void;
93
99
  }
@@ -12,7 +12,13 @@ export function read_desktop_settings(saved, specs = {}) {
12
12
  const defaults = { ...desktop_setting_defaults, ...Object.fromEntries(Object.entries(specs).map(([key, spec]) => [key, spec.default])) };
13
13
  return Object.fromEntries(Object.entries(defaults).map(([key, fallback]) => [key, typeof settings[key] === "boolean" ? settings[key] : fallback]));
14
14
  }
15
- export const desktop_method_names = ["get_desktop_settings", "set_desktop_setting", "quit_completely", "get_idle_seconds", "save_text_file", "set_window_theme", "get_data_paths", "show_data_path", "pick_folder"];
15
+ export const desktop_method_names = ["get_desktop_settings", "set_desktop_setting", "quit_completely", "get_idle_seconds", "save_text_file", "set_window_theme", "get_data_paths", "show_data_path", "pick_folder", "read_plugin_file"];
16
+ // The desktop page's scheme for the app's synced files, as <scheme>://<name>, such as x-notes-file://<name>.
17
+ export function file_scheme_of(app_id) {
18
+ return `${app_id}-file`;
19
+ }
20
+ // Where the desktop page pretends the plugins' web files are, so their addresses resolve against each other.
21
+ export const desktop_plugin_base = "x-app-plugins://local/";
16
22
  export const host_ability_method_names = ["get_host_abilities"];
17
23
  // The named event a host sends its pages with each notice.
18
24
  export const notice_event = "notice";
@@ -6,6 +6,7 @@ import { OidcClient } from "../server/oidc.ts";
6
6
  import { AccountStore } from "../server/account_store.ts";
7
7
  import { type Channel } from "../server/notify/channels.ts";
8
8
  import { EventStream } from "../server/events.ts";
9
+ import type { SyncFileStore } from "../sync_files.ts";
9
10
  import { type SqlDatabase } from "../sql.ts";
10
11
  import { type ServerTheme } from "../web/theme.ts";
11
12
  import { type SyncPeer } from "../sync_peer.ts";
@@ -48,6 +49,7 @@ export interface ServerOptions {
48
49
  remembered_seconds?: number | null;
49
50
  theme?: ServerTheme;
50
51
  plugins_folder?: string | null;
52
+ files?: SyncFileStore | null;
51
53
  second_factor_from?: string | null;
52
54
  }
53
55
  export declare const backup_tools: Record<"list_backups" | "create_backup" | "get_backup_schedule", MethodSpec>;
@@ -26,6 +26,8 @@ import { register_security_headers } from "../server/security_headers.js";
26
26
  import { EventStream } from "../server/events.js";
27
27
  import { register_mcp_route } from "../server/mcp.js";
28
28
  import { register_plugin_files } from "../server/plugin_files.js";
29
+ import { register_synced_files } from "../server/synced_file_route.js";
30
+ import { folder_file_store } from "../node_file_store.js";
29
31
  import { load_accounts } from "../server/passwords.js";
30
32
  import { BAD_JSON, register_error_replies, register_lenient_json_body, send_text } from "../server/replies.js";
31
33
  import { sqlite_backups } from "../server/sqlite_backups.js";
@@ -272,6 +274,8 @@ export async function build_server(app, options) {
272
274
  api.get("/theme", async () => options.theme ?? read_server_theme(null));
273
275
  register_app_calls(api, app, database, changes);
274
276
  register_host_tables(api, app, reach, services, changes);
277
+ if (options.files)
278
+ register_synced_files(api, options.files);
275
279
  // A route table's calls are documented as the routes they run, the rest as the calls posted under /api.
276
280
  api.get("/openapi.json", async () => {
277
281
  const called = Object.fromEntries(Object.entries(documented).filter(([method]) => !route_calls.has(method)));
@@ -380,11 +384,14 @@ export async function run_server(app, options) {
380
384
  const channels = read_channels(config.notify_channels, { name: "notify_channels" });
381
385
  // The server is one sync peer among the devices, kept beside the data so a restore leaves its pairings be; an app
382
386
  // whose server is the only copy keeps none.
387
+ // The app's synced files, such as covers, kept beside the data.
388
+ const files = app.synced_files ? folder_file_store(join(dirname(database_path), app.synced_files.folder)) : null;
383
389
  const sync = app.sync === false ? null : create_sync_peer({
384
390
  app: app.id,
385
391
  engine: app.sync_engine,
386
392
  database: opened.database,
387
393
  storage: file_sync_storage({ file: join(dirname(database_path), "sync-peers.json"), back_up_before_replace: opened.back_up }),
394
+ ...(files ? { files: { store: files, referenced: app.synced_files.referenced } } : {}),
388
395
  device_name: `${app.name} server on ${hostname()}`,
389
396
  addresses: () => (config.sync_address ? [config.sync_address] : []),
390
397
  on_remote_change: () => {
@@ -402,6 +409,7 @@ export async function run_server(app, options) {
402
409
  ...(config.second_factor_from ? { second_factor_from: config.second_factor_from } : {}),
403
410
  theme: read_server_theme(config.theme),
404
411
  plugins_folder: config.plugins_folder ? resolve(config.plugins_folder) : null,
412
+ files,
405
413
  });
406
414
  const stop_watching = watch_outside_changes(opened.database, () => changes.announce_change());
407
415
  const address = await server.listen({ host: server_config.host, port: server_config.port });
@@ -421,6 +429,7 @@ export async function run_server(app, options) {
421
429
  accounts.set_declared_tokens(declared_tokens.filter((token) => token.role !== null));
422
430
  },
423
431
  plugins_folder: config.plugins_folder ? resolve(config.plugins_folder) : null,
432
+ files,
424
433
  declared_file: declared_file_of(app, options.env ?? process.env),
425
434
  announce: (client_id) => changes.announce_change(client_id),
426
435
  wrote: () => {
@@ -2,6 +2,7 @@ import { DatabaseSync } from "node:sqlite";
2
2
  import type { FastifyInstance } from "fastify";
3
3
  import type { Need } from "../server/account_sign_in.ts";
4
4
  import type { DeclaredToken } from "../server/declared_tokens.ts";
5
+ import type { SyncFileStore } from "../sync_files.ts";
5
6
  import type { DataChange } from "../sync_protocol.ts";
6
7
  import type { App } from "./define.ts";
7
8
  import type { AppNotice } from "./protocol.ts";
@@ -14,6 +15,7 @@ export interface HostContext {
14
15
  config_file: string | null;
15
16
  declared_tokens: () => readonly DeclaredToken[];
16
17
  reread_declared_tokens: (config: Readonly<Record<string, unknown>>) => void;
18
+ files: SyncFileStore | null;
17
19
  plugins_folder: string | null;
18
20
  declared_file: string;
19
21
  announce: (client_id?: string) => void;
@@ -1,4 +1,5 @@
1
1
  import { type BackupFolderPlugin } from "../../phone_backups.ts";
2
+ import type { SyncFileStore } from "../../sync_files.ts";
2
3
  import { type FileStore } from "../../web/sqlite_wasm.ts";
3
4
  import { type SqlDatabase } from "../../sql.ts";
4
5
  import type { App } from "../define.ts";
@@ -9,6 +10,8 @@ export interface PhoneLifecycle {
9
10
  }
10
11
  export interface PhoneContext {
11
12
  database: () => SqlDatabase;
13
+ files: SyncFileStore | null;
14
+ wrote: () => void;
12
15
  }
13
16
  export interface PhoneServices {
14
17
  changed?: () => void;
@@ -17,6 +20,7 @@ export type StartPhoneServices = (context: PhoneContext) => PhoneServices | Prom
17
20
  export interface PhoneOptions {
18
21
  lifecycle?: PhoneLifecycle;
19
22
  files?: FileStore;
23
+ synced_files?: SyncFileStore;
20
24
  folder?: BackupFolderPlugin;
21
25
  services?: StartPhoneServices;
22
26
  storage?: Pick<Storage, "getItem" | "removeItem">;
@@ -61,7 +61,9 @@ export async function android_api(app, options = {}) {
61
61
  tidy_database(database.connection);
62
62
  await database.save_now();
63
63
  const keeper = keep_backing_up(kept, () => app.read_backup_schedule(database.connection));
64
- const services = options.services ? await options.services({ database: () => database.connection }) : {};
64
+ // The app's synced files, such as covers, apart from the database, which is saved whole after every change.
65
+ const synced = app.synced_files ? (options.synced_files ?? indexed_db_files(`${app.id}-${app.synced_files.folder}`)) : null;
66
+ let services = {};
65
67
  const listeners = new Set();
66
68
  const announce = () => {
67
69
  let change = null;
@@ -75,12 +77,32 @@ export async function android_api(app, options = {}) {
75
77
  listener(change);
76
78
  services.changed?.();
77
79
  };
80
+ if (options.services)
81
+ services = await options.services({ database: () => database.connection, files: synced, wrote: () => {
82
+ app.record_writes(database.connection);
83
+ announce();
84
+ } });
78
85
  // The paired devices and keys stay in the app's private storage; before another copy replaces this one the data is
79
86
  // backed up to the folder, or beside the database while there is none.
80
87
  const before_sync_file = app.database_file.replace(/\.db$/, "") + "-before-sync.db";
81
88
  const back_up_before_replace = async () => ((await has_folder()) ? void (await kept.create()) : files.write(before_sync_file, database.export_bytes()));
82
89
  const storage = local_sync_storage({ key: `${app.id}-sync-peers`, back_up_before_replace });
83
- const sync = create_sync_peer({ app: app.id, engine: app.sync_engine, database: () => database.connection, storage, device_name: `${app.name} on Android`, on_remote_change: announce });
90
+ const sync = create_sync_peer({
91
+ app: app.id, engine: app.sync_engine, database: () => database.connection, storage, device_name: `${app.name} on Android`, on_remote_change: announce,
92
+ ...(synced ? { files: { store: synced, referenced: app.synced_files.referenced } } : {}),
93
+ });
94
+ // Each kept file is read from IndexedDB once and shown from a blob address after; one not here yet is asked for
95
+ // again later, once sync or the app's services have brought it.
96
+ const file_sources = new Map();
97
+ const file_src = (name) => {
98
+ let source = file_sources.get(name);
99
+ if (!source) {
100
+ source = synced.read(name).then((bytes) => (bytes ? URL.createObjectURL(new Blob([bytes])) : ""));
101
+ file_sources.set(name, source);
102
+ void source.then((url) => url === "" && file_sources.delete(name));
103
+ }
104
+ return source;
105
+ };
84
106
  // A phone may close the app at any moment once it is in the background, so the database is saved straight away.
85
107
  lifecycle.addListener("pause", () => void database.save_now());
86
108
  lifecycle.addListener("resume", () => {
@@ -109,6 +131,7 @@ export async function android_api(app, options = {}) {
109
131
  return name;
110
132
  },
111
133
  },
134
+ ...(synced ? { file_src } : {}),
112
135
  on_change: (listener) => {
113
136
  listeners.add(listener);
114
137
  return () => listeners.delete(listener);
@@ -2,7 +2,7 @@ import type { App } from "../define.ts";
2
2
  import { type HostAbilities, type PageApi } from "../protocol.ts";
3
3
  export declare function read_host_abilities(read: () => Promise<unknown>): Promise<HostAbilities>;
4
4
  export declare function host_tables_of(app: Pick<App, "bridges">, abilities: HostAbilities, client_of: (name: string) => unknown): NonNullable<PageApi["tables"]>;
5
- export declare function web_api(app: Pick<App, "bridges"> & Partial<Pick<App, "sync">>): PageApi;
5
+ export declare function web_api(app: Pick<App, "bridges"> & Partial<Pick<App, "sync" | "synced_files">>): PageApi;
6
6
  export declare function is_desktop(app: Pick<App, "bridges">): boolean;
7
- export declare function desktop_api(app: Pick<App, "bridges"> & Partial<Pick<App, "local_mcp" | "remote_access">>): Promise<PageApi>;
7
+ export declare function desktop_api(app: Pick<App, "bridges"> & Partial<Pick<App, "id" | "local_mcp" | "remote_access" | "synced_files">>): Promise<PageApi>;
8
8
  export declare function is_android(): boolean;
@@ -3,7 +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
+ import { data_change_of, desktop_plugin_base, file_scheme_of } from "../protocol.js";
7
7
  // ── Host tables ──────────────────────────────────────────────────────────────
8
8
  // What the host lets the page reach, or nothing while it cannot be asked, such as before signing in.
9
9
  export async function read_host_abilities(read) {
@@ -105,6 +105,8 @@ export function web_api(app) {
105
105
  // The server's own sync peer and backups, which only an admin reaches; an app whose server is the only copy has no peer.
106
106
  device: app.sync === false ? null : bridges.device.web_rpc((method, args) => post_call(device_path, method, args)),
107
107
  backups: bridges.backups.web_rpc((method, args) => post_call(backups_path, method, args)),
108
+ ...(app.synced_files ? { file_src: async (name) => `api/files/${encodeURIComponent(name)}` } : {}),
109
+ plugin_base: "api/plugins/",
108
110
  on_change: (listener) => {
109
111
  listeners.add(listener);
110
112
  return () => listeners.delete(listener);
@@ -133,6 +135,7 @@ export async function desktop_api(app) {
133
135
  const is_here = (await connections.list_connections()).current === LOCAL_CONNECTION_ID;
134
136
  const host = exposed[bridges.host.api_name];
135
137
  const abilities = await read_host_abilities(async () => host?.get_host_abilities());
138
+ const desktop = exposed[bridges.desktop.api_name];
136
139
  return {
137
140
  host: "desktop",
138
141
  admin: abilities.admin,
@@ -147,7 +150,10 @@ export async function desktop_api(app) {
147
150
  backups: exposed[bridges.backups.api_name],
148
151
  certificates: exposed[bridges.certificates.api_name],
149
152
  connections,
150
- desktop: exposed[bridges.desktop.api_name],
153
+ desktop,
154
+ ...(app.synced_files && app.id ? { file_src: async (name) => `${file_scheme_of(app.id)}://${name}` } : {}),
155
+ plugin_base: desktop_plugin_base,
156
+ read_plugin_file: (path) => desktop.read_plugin_file(path),
151
157
  on_change: (listener) => events.on("changed", listener),
152
158
  on_event: (event, listener) => events.on("app_event", (sent) => sent.event === event && listener(sent.data)),
153
159
  };
@@ -48,6 +48,7 @@ export interface AppPages {
48
48
  phone_services?: () => Promise<StartPhoneServices>;
49
49
  phone_notifications?: () => Promise<LocalNotificationsLike>;
50
50
  remote_access_reach?: string;
51
+ exports_secrets?: boolean;
51
52
  role_text?: Readonly<Record<string, string>>;
52
53
  }
53
54
  export interface SettingsViewer {
@@ -59,10 +59,11 @@ function NoticeSwitches({ app, switches }) {
59
59
  } }) }, key))) }));
60
60
  }
61
61
  // Every setting but this device's own, as a file to take to another device or install, and read back.
62
- function SettingsFile({ app_id }) {
62
+ function SettingsFile({ app_id, secrets }) {
63
63
  const settings_calls = calls();
64
+ const [with_secrets, set_with_secrets] = useState(false);
64
65
  const export_file = async () => {
65
- const file = await attempt_value(() => settings_calls.export_settings());
66
+ const file = await attempt_value(() => settings_calls.export_settings(secrets && with_secrets));
66
67
  if (file)
67
68
  save_text(`${app_id}-settings-${new Date().toISOString().slice(0, 10)}.json`, JSON.stringify(file, null, 2));
68
69
  };
@@ -73,7 +74,7 @@ function SettingsFile({ app_id }) {
73
74
  if (result)
74
75
  toast(result.changed === 1 ? "1 setting set." : `${result.changed} settings set.`, { tone: "good" });
75
76
  };
76
- return (_jsx(SettingRow, { label: "Settings file", hint: "Every setting but this device's own, such as its notifications; keys for other services stay out.", children: _jsxs("div", { className: "button-list", children: [_jsx("button", { type: "button", onClick: () => void export_file(), children: "Export" }), _jsxs("label", { className: "button", children: ["Import", _jsx("input", { type: "file", accept: ".json,application/json", className: "visually-hidden", "aria-label": "Import settings", onChange: (event) => void read_picked(event).then(import_file) })] })] }) }));
77
+ return (_jsxs(SettingRow, { label: "Settings file", hint: with_secrets ? "Every setting but this device's own, with your keys and tokens for other services; keep the file private." : "Every setting but this device's own, such as its notifications; keys for other services stay out.", children: [secrets && _jsx(Switch, { label: "Include keys and tokens", show_label: true, checked: with_secrets, on_change: set_with_secrets }), _jsxs("div", { className: "button-list", children: [_jsx("button", { type: "button", onClick: () => void export_file(), children: "Export" }), _jsxs("label", { className: "button", children: ["Import", _jsx("input", { type: "file", accept: ".json,application/json", className: "visually-hidden", "aria-label": "Import settings", onChange: (event) => void read_picked(event).then(import_file) })] })] })] }));
77
78
  }
78
79
  // A desktop window on a server's daemon, or a phone that keeps no data, works on the host's data, as a browser does.
79
80
  function storage_category(pages, is_admin) {
@@ -100,7 +101,7 @@ function storage_category(pages, is_admin) {
100
101
  }
101
102
  if (desktop && !on_server)
102
103
  sections.push({ id: "storage", heading: "Storage", hint: `Where this computer keeps its ${data_name}.`, content: _jsx(DataFolder, { desktop: desktop }) });
103
- sections.push({ id: "settings-file", heading: "Import and export", hint: `Take ${name}'s settings to another device, or bring them back.`, content: _jsx(SettingsFile, { app_id: app.id }) });
104
+ sections.push({ id: "settings-file", heading: "Import and export", hint: `Take ${name}'s settings to another device, or bring them back.`, content: _jsx(SettingsFile, { app_id: app.id, secrets: pages.exports_secrets === true }) });
104
105
  if (backups && (!on_server || is_admin)) {
105
106
  const hint = backup_folder ? `This device's ${data_name}, kept in a folder of the phone's storage.` : on_server ? `The server's ${data_name}, kept in its data folder.` : `This device's ${data_name}, kept beside its database.`;
106
107
  // This computer's backups folder opens in the file manager.
@@ -0,0 +1,3 @@
1
+ import type { FastifyInstance } from "fastify";
2
+ import { type SyncFileStore } from "../sync_files.ts";
3
+ export declare function register_synced_files(api: FastifyInstance, store: SyncFileStore): void;
@@ -0,0 +1,14 @@
1
+ // An app's synced files, such as covers, served by name, the same on the web server and on the desktop daemon.
2
+ import { is_file_name } from "../sync_files.js";
3
+ import { send_text } from "./replies.js";
4
+ // ── Route ────────────────────────────────────────────────────────────────────
5
+ // GET <prefix>/files/<name>: a kept file by its name, which names its content, so it may be cached for good.
6
+ export function register_synced_files(api, store) {
7
+ api.get("/files/:name", async (request, reply) => {
8
+ const { name } = request.params;
9
+ const bytes = is_file_name(name) ? await store.read(name) : undefined;
10
+ if (!bytes)
11
+ return send_text(reply, 404, "no such file");
12
+ return reply.header("cache-control", "private, max-age=31536000, immutable").type("application/octet-stream").send(Buffer.from(bytes));
13
+ });
14
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-tech-laboratories/x-app",
3
- "version": "0.125.0",
3
+ "version": "0.126.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": {