@x-tech-laboratories/x-app 0.121.0 → 0.123.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.
@@ -1,24 +1,29 @@
1
1
  import { DatabaseSync } from "node:sqlite";
2
2
  import { type FastifyInstance } from "fastify";
3
3
  import { type BackupMethods } from "../backups.ts";
4
+ import { OidcClient } from "../server/oidc.ts";
4
5
  import { AccountStore } from "../server/account_store.ts";
6
+ import { type Channel } from "../server/notify/channels.ts";
5
7
  import { EventStream } from "../server/events.ts";
6
8
  import { type SqlDatabase } from "../sql.ts";
9
+ import { type ServerTheme } from "../web/theme.ts";
7
10
  import { type SyncPeer } from "../sync_peer.ts";
11
+ import { type DataChange } from "../sync_protocol.ts";
8
12
  import type { App, HostKind } from "./define.ts";
13
+ import { type AppNotice } from "./protocol.ts";
9
14
  import { type AppRoutes, type HostServices, type StartServices } from "./services.ts";
10
15
  export interface AppDatabase {
11
16
  database: () => DatabaseSync;
12
17
  back_up: () => Promise<void>;
13
18
  backup_methods: BackupMethods;
14
19
  on_restore: (hooks: {
15
- before?: () => void;
16
- after?: () => void;
20
+ before?: () => void | Promise<void>;
21
+ after?: () => void | Promise<void>;
17
22
  }) => void;
18
23
  close: () => void;
19
24
  }
20
25
  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;
26
+ export declare function data_change_text(app: Pick<App, "take_data_change">, database: () => SqlDatabase, after?: (change: DataChange | null) => void): () => string;
22
27
  export declare function watch_outside_changes(database: () => SqlDatabase, on_change: () => void, every_ms?: number): () => void;
23
28
  export declare const call_body_limit: number;
24
29
  export declare function call_args(app: App, method: string, body: unknown): unknown[];
@@ -37,9 +42,15 @@ export interface ServerOptions {
37
42
  cert: Buffer;
38
43
  key: Buffer;
39
44
  };
45
+ oidc?: OidcClient | null;
46
+ session_seconds?: number | null;
47
+ remembered_seconds?: number | null;
48
+ theme?: ServerTheme;
49
+ plugins_folder?: string | null;
40
50
  }
41
51
  export declare const user_only_backup_calls: ReadonlySet<string>;
42
52
  export declare function build_server(app: App, options: ServerOptions): Promise<FastifyInstance>;
53
+ export declare function notify_through(channels: readonly Channel[], notice: AppNotice): void;
43
54
  export interface RunServerOptions {
44
55
  web_folder: URL;
45
56
  argv?: string[];
@@ -12,14 +12,18 @@ import { openapi_document, positional_args } from "../api_spec.js";
12
12
  import { keep_backing_up } from "../backups.js";
13
13
  import { backup_method_names } from "../backups.js";
14
14
  import { calls_under, register_accounts } from "../server/account_sign_in.js";
15
+ import { read_declared_tokens } from "../server/declared_tokens.js";
16
+ import { OidcClient, oidc_from_environment } from "../server/oidc.js";
15
17
  import { caller_of, use_caller_scope } from "../caller.js";
16
18
  import { node_caller_scope } from "../node_caller_scope.js";
17
19
  import { AccountStore, holds_accounts, move_accounts } from "../server/account_store.js";
18
20
  import { register_call_table } from "../server/call_table.js";
19
21
  import { register_open_cors } from "../server/cors.js";
20
22
  import { read_server_config } from "../server/config.js";
23
+ import { read_channels } from "../server/notify/channels.js";
21
24
  import { EventStream } from "../server/events.js";
22
25
  import { register_mcp_route } from "../server/mcp.js";
26
+ import { register_plugin_files } from "../server/plugin_files.js";
23
27
  import { load_accounts } from "../server/passwords.js";
24
28
  import { BAD_JSON, register_error_replies, register_lenient_json_body, send_text } from "../server/replies.js";
25
29
  import { sqlite_backups } from "../server/sqlite_backups.js";
@@ -27,9 +31,11 @@ import { register_sync_peer_routes, sync_peer_headers } from "../server/sync_pee
27
31
  import { register_web_folder } from "../server/web_folder.js";
28
32
  import { tidy_database, tidy_every_ms } from "../sql.js";
29
33
  import { file_sync_storage } from "../sync_file_storage.js";
34
+ import { read_server_theme } from "../web/theme.js";
30
35
  import { create_sync_peer, sync_device_methods } from "../sync_peer.js";
36
+ import { data_change_of } from "../sync_protocol.js";
31
37
  import { call_path_of, mcp_tools, register_host_tables } from "./host_tables.js";
32
- import { notice_event } from "./protocol.js";
38
+ import { notice_event, notice_withdrawn_event } from "./protocol.js";
33
39
  import { declared_file_of, no_services, side_databases } from "./services.js";
34
40
  // The server and the daemon run on Node, so a call's caller holds across its awaits.
35
41
  use_caller_scope(node_caller_scope());
@@ -45,15 +51,15 @@ export function open_app_database(app, path, backups_folder) {
45
51
  naming: app.backup_naming,
46
52
  database: () => database,
47
53
  database_path: () => path,
48
- close: () => {
49
- restore_hooks.before?.();
54
+ close: async () => {
55
+ await restore_hooks.before?.();
50
56
  database.close();
51
57
  },
52
- open: () => {
58
+ open: async () => {
53
59
  database = new DatabaseSync(path);
54
60
  start(database);
55
61
  tidy_database(database);
56
- restore_hooks.after?.();
62
+ await restore_hooks.after?.();
57
63
  },
58
64
  // The restored data no longer matches other devices', so sync asks again which copy wins.
59
65
  after_restore: (restored) => app.sync_engine.forget_history(restored),
@@ -106,15 +112,24 @@ function adopt_schedule_file(app, database, file) {
106
112
  app.adopt_backup_schedule(database, saved);
107
113
  rmSync(file, { force: true });
108
114
  }
109
- // What a change event carries: the tables written since the last one, or nothing when that cannot be told, as mid-restore.
110
- export function data_change_text(app, database) {
115
+ // What a change event carries: the tables written since the last one, or nothing when that cannot be told, as
116
+ // mid-restore. after hears of each change as it is announced, such as the app's services following a setting.
117
+ export function data_change_text(app, database, after) {
111
118
  return () => {
119
+ let text = "";
112
120
  try {
113
- return JSON.stringify(app.take_data_change(database()));
121
+ text = JSON.stringify(app.take_data_change(database()));
114
122
  }
115
123
  catch {
116
- return "";
124
+ text = "";
125
+ }
126
+ try {
127
+ after?.(data_change_of(text));
117
128
  }
129
+ catch (error) {
130
+ console.error(`after a change: ${error instanceof Error ? error.message : String(error)}`);
131
+ }
132
+ return text;
118
133
  };
119
134
  }
120
135
  // Another program, such as an older build of the app, may write the database file; SQLite moves data_version only
@@ -201,16 +216,26 @@ export async function build_server(app, options) {
201
216
  }
202
217
  const admin_tables = app.tables_on(kind, true).filter((name) => app.host_tables[name].network !== "any").map((name) => `/api/${name}/`);
203
218
  const is_admin = (request) => request.viewer !== null && request.viewer !== undefined && options.accounts.has_role(request.viewer.role, options.accounts.top_role);
204
- const reach = { kind, from_network: true, is_admin };
219
+ const has_role = (request, role) => request.viewer !== null && request.viewer !== undefined && options.accounts.has_role(request.viewer.role, role);
220
+ const reach = { kind, from_network: true, is_admin, has_role };
205
221
  await register_accounts(server, {
206
222
  accounts: options.accounts,
207
223
  cookie_name: `${app.id.replaceAll("-", "_")}_session`,
208
224
  // Each peer call is sealed between the two devices, so it needs no sign-in, and the app's open routes check their
209
225
  // callers themselves.
210
- open_paths: ["/api/sync/peer", ...(options.routes?.open_paths ?? [])],
226
+ open_paths: ["/api/sync/peer", "/api/theme", ...(options.routes?.open_paths ?? [])],
227
+ open_prefixes: options.routes?.open_prefixes ?? [],
228
+ guarded_paths: options.routes?.guarded_paths ?? [],
229
+ oidc: options.oidc ?? null,
230
+ ...(options.session_seconds !== undefined ? { session_seconds: options.session_seconds } : {}),
231
+ ...(options.remembered_seconds !== undefined ? { remembered_seconds: options.remembered_seconds } : {}),
211
232
  // A read-only token may still list and read through MCP, which posts every request.
212
233
  read_only_paths: ["/api/mcp"],
213
- needed: (_method, path) => ([...admin_paths, ...admin_tables].some((admin_path) => path.startsWith(admin_path)) ? { role: options.accounts.top_role } : "any"),
234
+ needed: (method, path) => {
235
+ if ([...admin_paths, ...admin_tables].some((admin_path) => path.startsWith(admin_path)))
236
+ return { role: options.accounts.top_role };
237
+ return options.routes?.needed?.(method, path) ?? "any";
238
+ },
214
239
  // A token is refused the calls only the user at the page may make; a read-only one may make the calls that only read.
215
240
  call_of: calls_under("/api/call"),
216
241
  is_read_only: app.is_read_only,
@@ -223,6 +248,7 @@ export async function build_server(app, options) {
223
248
  const documented = Object.assign({}, app.api_spec, ...app.tables_on(kind, true).map((name) => app.host_tables[name].api));
224
249
  await server.register(async (api) => {
225
250
  changes.register(api, "/events");
251
+ api.get("/theme", async () => options.theme ?? read_server_theme(null));
226
252
  register_app_calls(api, app, database, changes);
227
253
  register_host_tables(api, app, reach, services, changes);
228
254
  api.get("/openapi.json", async () => openapi_document(documented, { ...description, path_of: call_path_of(app, kind), is_read_only: app.is_read_only }));
@@ -255,10 +281,18 @@ export async function build_server(app, options) {
255
281
  register_call_table(api, "/sync", sync_device_methods(options.sync), { is_read_only: app.is_read_only });
256
282
  }
257
283
  }, { prefix: "/api" });
284
+ if (options.plugins_folder)
285
+ register_plugin_files(server, { folder: options.plugins_folder, prefix: "/api/plugins", side: "web" });
258
286
  await options.routes?.register(server, services);
259
287
  await register_web_folder(server, { folder: options.web_folder });
260
288
  return server;
261
289
  }
290
+ // A notice the server passes on through each of its channels; a channel that fails is only logged.
291
+ export function notify_through(channels, notice) {
292
+ const level = notice.urgency === "critical" ? "warning" : "info";
293
+ for (const channel of channels)
294
+ void channel({ title: notice.title, body: notice.body, level }).catch((error) => console.warn(`notify: ${error instanceof Error ? error.message : String(error)}`));
295
+ }
262
296
  // Starts the app's web server on the database its config names, and stops it on SIGINT and SIGTERM.
263
297
  export async function run_server(app, options) {
264
298
  const prefix = app.env_prefix;
@@ -287,18 +321,32 @@ export async function run_server(app, options) {
287
321
  await opened.back_up();
288
322
  move_accounts(opened.database(), accounts_database);
289
323
  }
324
+ // Tokens the config declares, read again whenever the app's services read a changed config.
325
+ const declare_tokens = (from) => {
326
+ const declared = app.declared_tokens;
327
+ if (!declared)
328
+ return [];
329
+ return read_declared_tokens(from[declared.key], { scopes: declared.scopes, ...(declared.limit_key ? { limit_key: declared.limit_key } : {}), new_token_command: `${app.id} token new` });
330
+ };
331
+ let declared_tokens = declare_tokens(config);
290
332
  const accounts = new AccountStore({
291
333
  database: accounts_database,
292
334
  app_name: app.name,
335
+ ...(app.roles ? { roles: app.roles } : {}),
293
336
  ...(app.token_prefix ? { token_prefix: app.token_prefix } : {}),
294
337
  declared: load_accounts(`${prefix}_PASSWORD_HASH_FILE`, server_config.values.password_hash_file),
338
+ declared_tokens: declared_tokens.filter((token) => token.role !== null),
295
339
  });
340
+ const oidc_settings = oidc_from_environment(prefix, options.env ?? process.env);
296
341
  // Every page hears of a change, whether a page or another device made it, and which tables it touched.
297
- const changes = new EventStream({ change_data: data_change_text(app, opened.database) });
298
342
  // Answers the host tables and the app's routes once started; before then they say the server is still starting.
299
343
  let services = no_services;
300
- // The server is one sync peer among the devices, kept beside the data so a restore leaves its pairings be.
301
- const sync = create_sync_peer({
344
+ const changes = new EventStream({ change_data: data_change_text(app, opened.database, (change) => services.after_change?.(change)) });
345
+ // A mistake in a channel, or a secret file that cannot be read, stops the server starting.
346
+ const channels = read_channels(config.notify_channels, { name: "notify_channels" });
347
+ // The server is one sync peer among the devices, kept beside the data so a restore leaves its pairings be; an app
348
+ // whose server is the only copy keeps none.
349
+ const sync = app.sync === false ? null : create_sync_peer({
302
350
  app: app.id,
303
351
  engine: app.sync_engine,
304
352
  database: opened.database,
@@ -310,10 +358,19 @@ export async function run_server(app, options) {
310
358
  services.after_remote_change?.();
311
359
  },
312
360
  });
313
- const server = await build_server(app, { database: opened.database, accounts, web_folder: server_config.web_folder, sync, changes, backup_methods: opened.backup_methods, services: () => services, ...(options.routes ? { routes: options.routes } : {}) });
361
+ const server = await build_server(app, {
362
+ database: opened.database, accounts, web_folder: server_config.web_folder, changes, backup_methods: opened.backup_methods, services: () => services,
363
+ ...(sync ? { sync } : {}),
364
+ ...(options.routes ? { routes: options.routes } : {}),
365
+ ...(oidc_settings ? { oidc: new OidcClient(oidc_settings) } : {}),
366
+ ...(config.session_seconds !== undefined ? { session_seconds: config.session_seconds } : {}),
367
+ ...(config.remembered_seconds !== undefined ? { remembered_seconds: config.remembered_seconds } : {}),
368
+ theme: read_server_theme(config.theme),
369
+ plugins_folder: config.plugins_folder ? resolve(config.plugins_folder) : null,
370
+ });
314
371
  const stop_watching = watch_outside_changes(opened.database, () => changes.announce_change());
315
372
  const address = await server.listen({ host: server_config.host, port: server_config.port });
316
- sync.start();
373
+ sync?.start();
317
374
  const sides = side_databases(database_path);
318
375
  services = options.services
319
376
  ? await options.services({
@@ -322,6 +379,12 @@ export async function run_server(app, options) {
322
379
  profile: dirname(database_path),
323
380
  device_name: `${app.name} server on ${hostname()}`,
324
381
  config: config,
382
+ config_file: resolve(server_config.values.config),
383
+ declared_tokens: () => declared_tokens,
384
+ reread_declared_tokens: (from) => {
385
+ declared_tokens = declare_tokens(from);
386
+ accounts.set_declared_tokens(declared_tokens.filter((token) => token.role !== null));
387
+ },
325
388
  plugins_folder: config.plugins_folder ? resolve(config.plugins_folder) : null,
326
389
  declared_file: declared_file_of(app, options.env ?? process.env),
327
390
  announce: (client_id) => changes.announce_change(client_id),
@@ -334,8 +397,13 @@ export async function run_server(app, options) {
334
397
  back_up: opened.back_up,
335
398
  window_in_front: () => false,
336
399
  icon_path: null,
337
- // The server shows no notice itself; the pages and phones working on it show them.
338
- notify: (notice) => changes.send(JSON.stringify(notice), { event: notice_event }),
400
+ // The server shows no notice itself: it goes out through the config's channels, and the pages and phones
401
+ // working on the server show it.
402
+ notify: (notice) => {
403
+ notify_through(channels, notice);
404
+ changes.send(JSON.stringify(notice), { event: notice_event });
405
+ },
406
+ withdraw: (key) => changes.send(JSON.stringify(key), { event: notice_withdrawn_event }),
339
407
  })
340
408
  : no_services;
341
409
  opened.on_restore({ before: () => services.before_restore?.(), after: () => services.after_restore?.() });
@@ -344,7 +412,7 @@ export async function run_server(app, options) {
344
412
  const stop = () => (stopping ??= server.close().then(async () => {
345
413
  await services.stop();
346
414
  stop_watching();
347
- sync.stop();
415
+ sync?.stop();
348
416
  sides.close_all();
349
417
  opened.close();
350
418
  accounts_database.close();
@@ -1,5 +1,8 @@
1
1
  import { DatabaseSync } from "node:sqlite";
2
2
  import type { FastifyInstance } from "fastify";
3
+ import type { Need } from "../server/account_sign_in.ts";
4
+ import type { DeclaredToken } from "../server/declared_tokens.ts";
5
+ import type { DataChange } from "../sync_protocol.ts";
3
6
  import type { App } from "./define.ts";
4
7
  import type { AppNotice } from "./protocol.ts";
5
8
  export interface HostContext {
@@ -8,6 +11,9 @@ export interface HostContext {
8
11
  profile: string;
9
12
  device_name: string;
10
13
  config: Readonly<Record<string, unknown>>;
14
+ config_file: string | null;
15
+ declared_tokens: () => readonly DeclaredToken[];
16
+ reread_declared_tokens: (config: Readonly<Record<string, unknown>>) => void;
11
17
  plugins_folder: string | null;
12
18
  declared_file: string;
13
19
  announce: (client_id?: string) => void;
@@ -18,22 +24,27 @@ export interface HostContext {
18
24
  window_in_front: () => boolean;
19
25
  icon_path: string | null;
20
26
  notify: (notice: AppNotice) => void;
27
+ withdraw: (key: string) => void;
21
28
  }
22
29
  export interface ServedTable {
23
30
  methods: object;
24
31
  elsewhere?: object;
25
32
  }
26
33
  export interface HostServices {
27
- before_restore?: () => void;
28
- after_restore?: () => void;
34
+ before_restore?: () => void | Promise<void>;
35
+ after_restore?: () => void | Promise<void>;
29
36
  stop: () => void | Promise<void>;
30
37
  tables?: Readonly<Record<string, ServedTable>>;
31
38
  own?: unknown;
32
39
  after_remote_change?: () => void;
40
+ after_change?: (change: DataChange | null) => void;
33
41
  }
34
42
  export type StartServices = (context: HostContext) => HostServices | Promise<HostServices>;
35
43
  export interface AppRoutes {
36
44
  open_paths?: readonly string[];
45
+ open_prefixes?: readonly string[];
46
+ guarded_paths?: readonly string[];
47
+ needed?: (method: string, path: string) => Need | null;
37
48
  register: (server: FastifyInstance, services: () => HostServices) => void | Promise<void>;
38
49
  }
39
50
  export declare function declared_file_of(app: Pick<App, "id" | "env_prefix">, env: NodeJS.ProcessEnv): string;
@@ -2,7 +2,7 @@ import "@x-tech-laboratories/halon/halon-tokens.css";
2
2
  import "@x-tech-laboratories/halon/halon.css";
3
3
  import type { App } from "../define.ts";
4
4
  import { type AppPages } from "./settings_page.tsx";
5
- export type { AppPage, AppPages, AppSubpage, PageSettingsProps } from "./settings_page.tsx";
5
+ export type { AppChrome, AppPage, AppPages, AppSubpage, PageSettingsProps } from "./settings_page.tsx";
6
6
  export declare const default_sidebar_width: {
7
7
  default_width: number;
8
8
  min: number;
@@ -14,7 +14,7 @@ import { PageHeading } from "../../web/react/layout.js";
14
14
  import { Shell, use_route } from "../../web/react/shell.js";
15
15
  import { SignInForm, use_account } from "../../web/react/sign_in.js";
16
16
  import { SyncButton } from "../../web/react/sync_settings.js";
17
- import { local_theme_storage, theme_choice } from "../../web/theme.js";
17
+ import { apply_theme_colors, local_theme_storage, pinned_theme_choice, read_server_theme, theme_choice } from "../../web/theme.js";
18
18
  import { desktop_api, is_android, is_desktop, web_api } from "./hosts.js";
19
19
  import { calls, data_watch, page, set_page_api, set_page_reach, use_settings } from "./page.js";
20
20
  import { SettingsView } from "./settings_page.js";
@@ -40,13 +40,27 @@ function is_theme(value) {
40
40
  }
41
41
  // The theme kept in this browser, or for an app with synced_theme in its synced setting, which a change on another
42
42
  // device applies here too; this browser's copy shows it before the settings arrive.
43
+ // The look a browser's server pins, read once before the page draws.
44
+ async function read_theme_of_server() {
45
+ try {
46
+ const reply = await fetch("api/theme", { cache: "no-store" });
47
+ return reply.ok ? read_server_theme(await reply.json()) : read_server_theme(null);
48
+ }
49
+ catch {
50
+ return read_server_theme(null);
51
+ }
52
+ }
53
+ // A scheme the server pins wins over both, and the page then offers no way to change it.
43
54
  function use_theme(app) {
55
+ const pinned = page().server_theme?.scheme ?? null;
44
56
  const settings = use_settings();
45
57
  const synced = app.synced_theme === true;
46
58
  const stored = synced ? settings.data?.theme : undefined;
47
59
  const latest = useRef(undefined);
48
60
  latest.current = stored;
49
61
  const theme = useMemo(() => {
62
+ if (pinned)
63
+ return pinned_theme_choice(pinned);
50
64
  const local = local_theme_storage(`${app.id}-theme`);
51
65
  if (!synced)
52
66
  return theme_choice(local);
@@ -58,7 +72,7 @@ function use_theme(app) {
58
72
  void calls().set_setting("theme", chosen).catch(() => undefined);
59
73
  },
60
74
  });
61
- }, [app.id, synced]);
75
+ }, [app.id, synced, pinned]);
62
76
  // The desktop window's own parts, such as menus, follow the page's theme.
63
77
  useEffect(() => {
64
78
  const tell = (chosen) => void page().desktop?.set_window_theme(chosen).catch(() => undefined);
@@ -66,11 +80,11 @@ function use_theme(app) {
66
80
  return theme.on_change(tell);
67
81
  }, [theme]);
68
82
  useEffect(() => {
69
- if (!is_theme(stored))
83
+ if (pinned || !is_theme(stored))
70
84
  return;
71
85
  local_theme_storage(`${app.id}-theme`).write(stored);
72
86
  theme.apply(stored);
73
- }, [stored, theme]);
87
+ }, [stored, theme, pinned]);
74
88
  return theme;
75
89
  }
76
90
  function Pages({ pages, account }) {
@@ -82,7 +96,13 @@ function Pages({ pages, account }) {
82
96
  // A page with pages of its own shows the one the route names, or its first; with only one it is the page itself.
83
97
  const children = shown?.children && shown.children.length > 1 ? shown.children : [];
84
98
  const subpage = children.find((child) => child.id === rest[0]) ?? children[0];
85
- const label = shown ? (subpage ? `${subpage.label} · ${shown.label}` : shown.label) : is_account ? "Your account" : "Settings";
99
+ // Each listed page's items, such as paired devices, from its hook, called in the same order every time.
100
+ const listed = pages.pages.filter((each) => each.in_sidebar !== false);
101
+ const items = listed.map((each) => each.use_items?.() ?? null);
102
+ const shown_items = shown ? (items[listed.indexOf(shown)] ?? []) : [];
103
+ const item = subpage ? undefined : shown_items.find((each) => each.id === rest[0]);
104
+ const named = subpage ?? item;
105
+ const label = shown ? (named ? `${named.label} · ${shown.label}` : shown.label) : is_account ? "Your account" : "Settings";
86
106
  const view_key = shown?.view_key ? [section, shown.view_key(rest)].join("/") : route.parts.join("/");
87
107
  const chrome = pages.use_chrome?.(route.parts) ?? {};
88
108
  const theme = use_theme(app);
@@ -90,22 +110,22 @@ function Pages({ pages, account }) {
90
110
  document.title = `${label} · ${app.name}`;
91
111
  }, [label, app.name]);
92
112
  // Each listed page's badge, such as how many things wait, from its hook, called in the same order every time.
93
- const listed = pages.pages.filter((each) => each.in_sidebar !== false);
94
113
  const badges = listed.map((each) => each.use_badge?.() ?? null);
95
114
  const row_label = (index) => (badges[index] ? `${listed[index].label} · ${badges[index]}` : listed[index].label);
96
115
  const with_icons = listed.some((each) => each.icon);
97
- const sections = listed.map((each, index) => ({
98
- id: each.id,
99
- label: row_label(index),
100
- href: `#/${each.id}`,
101
- ...(each.children && each.children.length > 1 ? { children: each.children.map((child) => ({ id: child.id, label: child.label, href: `#/${each.id}/${child.id}` })) } : {}),
102
- }));
116
+ // An app's own sidebar content, such as a tree, takes the place of plain sections, so the pages show as rows above it.
117
+ const rows_under = (each, index) => (each.children && each.children.length > 1 ? each.children : (items[index] ?? []));
118
+ const folding = listed.some((each, index) => rows_under(each, index).length > 0);
119
+ const sections = listed.map((each, index) => {
120
+ const under = rows_under(each, index);
121
+ return { id: each.id, label: row_label(index), href: `#/${each.id}`, ...(under.length ? { children: under.map((child) => ({ id: child.id, label: child.label, href: `#/${each.id}/${child.id}` })) } : {}) };
122
+ });
103
123
  const views = listed.map((each, index) => ({ id: each.id, label: row_label(index), href: `#/${each.id}`, ...(each.icon ? { icon: each.icon } : {}) }));
104
- const view = shown ? shown.view(rest) : is_account ? _jsx(AccountPage, { account: account }) : _jsx(SettingsView, { pages: pages, is_admin: account === null || is_admin(account.me) });
124
+ const view = shown ? shown.view(rest) : is_account ? _jsx(AccountPage, { account: account }) : _jsx(SettingsView, { pages: pages, is_admin: account === null || is_admin(account.me), viewer: account ? { client: accounts, me: account.me } : null });
105
125
  const framed = _jsx(Fragment, { children: view }, view_key);
106
126
  if (chrome.bare)
107
127
  return _jsx(_Fragment, { children: chrome.around ? chrome.around(framed) : framed });
108
- return (_jsx(Shell, { brand: app.name, brand_icon: pages.brand_icon ?? "icon.svg", ...(with_icons ? { views } : { sections }), active: shown?.active_as ?? section, active_item: subpage?.id ?? null, sections_pref: `${app.id}-sidebar-collapsed`, ...(chrome.sidebar ? { sidebar: chrome.sidebar } : {}), ...(chrome.tools ? { tools: chrome.tools } : {}), ...(chrome.side_pane ? { side_pane: chrome.side_pane } : {}), ...(chrome.contained ? { contained: true } : {}), ...(chrome.main_class ? { main_class: chrome.main_class } : {}), theme: theme, sidebar_width: chrome.sidebar_width ?? { ...default_sidebar_width, storage_key: `${app.id}-sidebar-width` }, view_key: view_key, user: account ? account.me.name : undefined, user_href: account ? "#/account" : undefined, on_logout: account ? () => void account.sign_out() : undefined, sidebar_foot: _jsx(SidebarFoot, {}), settings: { href: "#/settings" }, children: chrome.around ? chrome.around(framed) : framed }));
128
+ return (_jsx(Shell, { brand: app.name, brand_icon: pages.brand_icon ?? "icon.svg", ...(with_icons || (chrome.sidebar && !folding) ? { views } : { sections }), active: shown?.active_as ?? section, active_item: named?.id ?? null, sections_pref: `${app.id}-sidebar-collapsed`, ...(chrome.sidebar ? { sidebar: chrome.sidebar } : {}), ...(chrome.tools ? { tools: chrome.tools } : {}), ...(chrome.side_pane ? { side_pane: chrome.side_pane } : {}), ...(chrome.contained ? { contained: true } : {}), ...(chrome.main_class ? { main_class: chrome.main_class } : {}), theme: theme, sidebar_width: chrome.sidebar_width ?? { ...default_sidebar_width, storage_key: `${app.id}-sidebar-width` }, view_key: view_key, user: account ? account.me.name : undefined, user_href: account ? "#/account" : undefined, on_logout: account ? () => void account.sign_out() : undefined, sidebar_foot: _jsx(SidebarFoot, {}), settings: { href: "#/settings" }, children: chrome.around ? chrome.around(framed) : framed }));
109
129
  }
110
130
  // ── App ──────────────────────────────────────────────────────────────────────
111
131
  // A browser reaches the server's data, so it signs in; the desktop and phone apps keep their own and sign in only to sync.
@@ -173,6 +193,14 @@ async function host_api(app, pages) {
173
193
  // Starts the page on whichever host it runs: the desktop app, the phone app or a browser.
174
194
  export async function render_app(pages, root = document.getElementById("app")) {
175
195
  const api = await host_api(pages.app, pages);
196
+ // A browser takes the look its server pins before anything draws, the sign-in page included.
197
+ if (api.host === "web") {
198
+ const server_theme = await read_theme_of_server();
199
+ api.server_theme = server_theme;
200
+ apply_theme_colors(server_theme.colors);
201
+ if (server_theme.scheme)
202
+ pinned_theme_choice(server_theme.scheme).apply();
203
+ }
176
204
  if (api.reread_abilities)
177
205
  Object.assign(api, await api.reread_abilities());
178
206
  set_page_api(api);
@@ -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">): PageApi;
5
+ export declare function web_api(app: Pick<App, "bridges"> & Partial<Pick<App, "sync">>): PageApi;
6
6
  export declare function is_desktop(app: Pick<App, "bridges">): boolean;
7
7
  export declare function desktop_api(app: Pick<App, "bridges"> & Partial<Pick<App, "local_mcp" | "remote_access">>): Promise<PageApi>;
8
8
  export declare function is_android(): boolean;
@@ -102,8 +102,8 @@ export function web_api(app) {
102
102
  admin: false,
103
103
  reread_abilities: async () => reach(await read_abilities()),
104
104
  calls: bridges.calls.web_rpc((method, args) => post_call(call_path, method, args)),
105
- // The server's own sync peer and backups, which only an admin reaches.
106
- device: bridges.device.web_rpc((method, args) => post_call(device_path, method, args)),
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
+ 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
108
  on_change: (listener) => {
109
109
  listeners.add(listener);
@@ -4,6 +4,7 @@ import { type AppNotice, type PageApi } from "../protocol.ts";
4
4
  import type { PhoneLifecycle } from "./android.ts";
5
5
  export declare function read_notice_switches(app: Pick<App, "desktop_settings">, saved: string | null): Record<string, boolean>;
6
6
  export declare function phone_notice_shower(plugin: LocalNotificationsLike, open_link: (url: string) => void): (notice: AppNotice) => void;
7
+ export declare function phone_notice_withdrawer(plugin: LocalNotificationsLike): (key: string) => void;
7
8
  export interface PortalOptions {
8
9
  lifecycle: PhoneLifecycle;
9
10
  notifications?: LocalNotificationsLike;
@@ -9,7 +9,7 @@ import { phone_certificates } from "../../phone_certificates.js";
9
9
  import { local_connection_storage } from "../../web/connection_storage.js";
10
10
  import { call_remote, follow_remote } from "../../web/remote_daemon.js";
11
11
  import { route_of_link } from "../links.js";
12
- import { data_change_of, notice_event, notice_is_on } from "../protocol.js";
12
+ import { data_change_of, notice_event, notice_is_on, notice_withdrawn_event } from "../protocol.js";
13
13
  import { host_tables_of, read_host_abilities } from "./hosts.js";
14
14
  // ── Switches ─────────────────────────────────────────────────────────────────
15
15
  // The notice switches this phone keeps, each of the app's `notify_` desktop switches at its default where unset.
@@ -36,6 +36,14 @@ export function phone_notice_shower(plugin, open_link) {
36
36
  void plugin.checkPermissions().then(({ display }) => (display === "granted" || display === "denied" ? undefined : plugin.requestPermissions()));
37
37
  return (notice) => void plugin.schedule({ notifications: [{ id: notice_id(notice.key), title: notice.title, body: notice.body, extra: { url: notice.url }, isExactNotification: false }] }).catch((error) => console.error("could not show a notice", error));
38
38
  }
39
+ // Takes a notice the host withdrew off the screen, and out of those still to show.
40
+ export function phone_notice_withdrawer(plugin) {
41
+ return (key) => {
42
+ const notifications = [{ id: notice_id(key), title: "", body: "" }];
43
+ void plugin.cancel({ notifications }).catch(() => undefined);
44
+ void plugin.removeDeliveredNotifications?.({ notifications }).catch(() => undefined);
45
+ };
46
+ }
39
47
  export async function portal_api(app, options) {
40
48
  const storage = options.storage ?? localStorage;
41
49
  const switches_key = `${app.id}-notice-kinds`;
@@ -67,6 +75,7 @@ export async function portal_api(app, options) {
67
75
  location.hash = route;
68
76
  };
69
77
  const show = options.notifications ? phone_notice_shower(options.notifications, open_link) : null;
78
+ const withdraw = options.notifications ? phone_notice_withdrawer(options.notifications) : null;
70
79
  if (link.daemon()) {
71
80
  follow_remote(link, (event, data) => {
72
81
  if (event === "hello")
@@ -77,6 +86,8 @@ export async function portal_api(app, options) {
77
86
  const parsed = data === "" ? null : JSON.parse(data);
78
87
  if (event === notice_event && show && notice_is_on(parsed.kind, switches()))
79
88
  show(parsed);
89
+ if (event === notice_withdrawn_event && withdraw && typeof parsed === "string")
90
+ withdraw(parsed);
80
91
  for (const listener of named.get(event) ?? [])
81
92
  listener(parsed);
82
93
  }
@@ -1,4 +1,5 @@
1
1
  import type { IconGlyph } from "../../web/react/icons.tsx";
2
+ import type { AccountsClient, Me } from "../../web/accounts.ts";
2
3
  import { type SettingsCategory, type SettingsSection } from "../../web/react/layout.tsx";
3
4
  import type { ShellSidePane, SidebarWidth } from "../../web/react/shell.tsx";
4
5
  import type { LocalNotificationsLike } from "../../phone_notices.ts";
@@ -19,6 +20,7 @@ export interface AppPage {
19
20
  active_as?: string;
20
21
  view_key?: (parts: string[]) => string;
21
22
  children?: readonly AppSubpage[];
23
+ use_items?: () => readonly AppSubpage[] | null;
22
24
  }
23
25
  export interface AppSubpage {
24
26
  id: string;
@@ -45,8 +47,14 @@ export interface AppPages {
45
47
  phone_services?: () => Promise<StartPhoneServices>;
46
48
  phone_notifications?: () => Promise<LocalNotificationsLike>;
47
49
  remote_access_reach?: string;
50
+ role_text?: Readonly<Record<string, string>>;
48
51
  }
49
- export declare function SettingsView({ pages, is_admin }: {
52
+ export interface SettingsViewer {
53
+ client: AccountsClient;
54
+ me: Me;
55
+ }
56
+ export declare function SettingsView({ pages, is_admin, viewer }: {
50
57
  pages: AppPages;
51
58
  is_admin?: boolean;
59
+ viewer?: SettingsViewer | null;
52
60
  }): import("react").JSX.Element;