@g9tm/app-diagnostic 0.2.0 → 0.2.1

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,426 +1,426 @@
1
- // What an operator can ask of every device (G9AppDiagnostic.Maui LiveScreenshotServerPusher, LiveSqlServerHandler,
2
- // LiveLogFileServerHandler, LiveBackupServerHandler, the restore stream, LiveRemoteInputHandler), each answered through
3
- // its Push… method with the same requestId. Everything that looks INTO the device needs the user's consent
4
- // (channel.admit); a refusal still answers, so the console never waits for a timeout. No handler throws at the
5
- // connection. Product commands (sync control, NFC, a QA bridge) are the app's extensions.
6
- import { base64ToBytes, utf8Decode } from '../bytes.ts';
7
- import { type DiagnosticFiles, type DiagnosticZipEntry, errorText } from '../host.ts';
8
- import { DeviceHubListeners, DeviceHubMethods } from '../wire.ts';
9
- import { BUNDLE_ENTRY, bundleFileName, bundleManifest, type BundleKind, normalizeScopes } from './bundle.ts';
10
- import type { ILiveKeepAlive, LiveChannel } from './channel.ts';
11
- import type { BackupBuildRequestPayload, LogFileReadRequestPayload, RemoteInputCommand, SqlExecRequestPayload, SqlResultPayload } from './models.ts';
12
- import { BackupSource } from './models.ts';
13
- import { type BundleUploadOutcome, uploadBundle } from './upload.ts';
14
-
15
- /** The operator's SQL console on the app's database (ILiveSqlTarget): raw I/O; the channel keeps the policy. */
16
- export interface ILiveSqlTarget {
17
- /** False when no database is open (signed out). */
18
- available(): boolean;
19
- query(sql: string): Promise<{ readonly columns: readonly string[]; readonly rows: ReadonlyArray<ReadonlyArray<unknown>> }>;
20
- execute(sql: string): Promise<{ readonly changes: number }>;
21
- }
22
-
23
- /** The app's diagnostic bundle (ILiveBackupSource): what goes in for the scopes asked; the channel adds its own entries. */
24
- export interface ILiveBackupSource {
25
- /** Zips the app's entries for `scopes` plus `extra` (bundle.json, a report) into `out`. */
26
- build(request: { readonly kind: BundleKind; readonly scopes: BackupBuildRequestPayload; readonly out: string; readonly extra: readonly DiagnosticZipEntry[] }): Promise<{ readonly path: string; readonly containsSensitive: boolean }>;
27
- /** The password envelope (the wire profile's backupMagic): `source` → `destination`. */
28
- encrypt?(source: string, destination: string, password: string): Promise<void>;
29
- }
30
-
31
- /** Applies a verified restore archive (ILiveRestoreTarget); the host closes or restarts the app after. */
32
- export interface ILiveRestoreTarget {
33
- /** `scopesCsv`: the operator's sections ("" = everything in the archive). */
34
- restore(zipPath: string, scopesCsv: string): Promise<void>;
35
- }
36
-
37
- /** A remote-input action on the app's own window, in fractions of the window (0..1). */
38
- export type RemoteAction =
39
- | { readonly kind: 'tap' | 'longPress'; readonly x: number; readonly y: number }
40
- | { readonly kind: 'drag'; readonly x: number; readonly y: number; readonly toX: number; readonly toY: number; readonly durationMs: number }
41
- | { readonly kind: 'text'; readonly text: string };
42
-
43
- /** The platform's input injection (Android: real touches into the app's window; iOS: a logical tap). */
44
- export interface ILiveRemoteInput {
45
- perform(action: RemoteAction): Promise<void>;
46
- }
47
-
48
- /** The window as a JPEG for the operator (the platform package's capture). */
49
- export type LiveScreenshot = (maxEdge: number, quality: number) => Promise<{ readonly widthPx: number; readonly heightPx: number; readonly dataBase64: string; readonly mimeType?: string }>;
50
-
51
- export interface LiveHandlerOptions {
52
- readonly channel: LiveChannel;
53
- readonly files: DiagnosticFiles;
54
- readonly screenshot?: LiveScreenshot;
55
- /** The visible screen's name in a screenshot frame. */
56
- readonly pageName?: () => string | null;
57
- readonly sql?: ILiveSqlTarget;
58
- readonly backup?: ILiveBackupSource;
59
- readonly restore?: ILiveRestoreTarget;
60
- readonly remoteInput?: ILiveRemoteInput;
61
- readonly keepAlive?: ILiveKeepAlive;
62
- /** Where built bundles and received restores wait (absolute folders). */
63
- readonly folders: { readonly outgoing: () => Promise<string>; readonly restore: () => Promise<string> };
64
- /** Bundle names and manifest (BundleFilePrefix, ProductName). */
65
- readonly product: { readonly name: string; readonly filePrefix: string; readonly appVersion: string; readonly appBuild: string; readonly platform: string };
66
- /** The keep-alive's texts. */
67
- readonly texts?: { readonly backupTitle: string; readonly backupSubtitle: string };
68
- readonly now?: () => number;
69
- }
70
-
71
- export const MAX_SQL_ROWS = 5000;
72
- const READ_ONLY_SQL = /^\s*(select|pragma|explain|with)\b/i;
73
- /** One screenshot per second at most (the 1 Hz cap). */
74
- export const SCREENSHOT_MIN_GAP_MS = 1000;
75
- const LOG_NAME = /^[A-Za-z0-9._-]+\.log$/;
76
-
77
- function cell(v: unknown): string | null {
78
- if (v === null || v === undefined) return null;
79
- if (typeof v === 'object') return JSON.stringify(v);
80
- return String(v);
81
- }
82
-
83
- const nowIso = (now: () => number) => new Date(now()).toISOString();
84
-
85
- /** The SQL console's policy: read-only unless the operator flipped it, a row cap, a time limit. */
86
- export async function runSql(target: ILiveSqlTarget | undefined, req: SqlExecRequestPayload, now: () => number = Date.now): Promise<SqlResultPayload> {
87
- const started = now();
88
- const result = (patch: Partial<SqlResultPayload>): SqlResultPayload => ({
89
- columnNames: [],
90
- columnTypes: [],
91
- rows: [],
92
- rowsAffected: 0,
93
- rowsReturned: 0,
94
- durationMs: now() - started,
95
- errorMessage: null,
96
- truncated: false,
97
- ...patch,
98
- });
99
- if (!target) return result({ errorMessage: 'This app does not offer the SQL console.' });
100
- if (!target.available()) return result({ errorMessage: 'No user database is open' });
101
- try {
102
- const timeout = Math.max(5, Math.min(300, req.timeoutSeconds || 60)) * 1000;
103
- const work = (async (): Promise<SqlResultPayload> => {
104
- if (req.readOnly !== false) {
105
- if (!READ_ONLY_SQL.test(req.sql)) return result({ errorMessage: 'Read-only mode: only SELECT / PRAGMA / EXPLAIN / WITH' });
106
- const raw = await target.query(req.sql);
107
- const max = Math.max(1, Math.min(MAX_SQL_ROWS, req.maxRows || 1000));
108
- const rows = raw.rows.slice(0, max).map((r) => r.map(cell));
109
- return result({ columnNames: raw.columns.map(String), columnTypes: raw.columns.map(() => ''), rows, rowsReturned: rows.length, truncated: raw.rows.length > max });
110
- }
111
- const r = await target.execute(req.sql);
112
- return result({ rowsAffected: r.changes });
113
- })();
114
- let timer: ReturnType<typeof setTimeout> | undefined;
115
- const limit = new Promise<SqlResultPayload>((r) => {
116
- timer = setTimeout(() => r(result({ errorMessage: `Timed out after ${timeout / 1000} s` })), timeout);
117
- });
118
- try {
119
- return await Promise.race([work, limit]);
120
- } finally {
121
- if (timer !== undefined) clearTimeout(timer);
122
- }
123
- } catch (e) {
124
- return result({ errorMessage: errorText(e) });
125
- }
126
- }
127
-
128
- /** Wires the core operator commands on the channel. Returns what a test or the app needs to reach. */
129
- export function wireLiveHandlers(o: LiveHandlerOptions): { readonly backupInFlight: () => boolean; readonly restoreInFlight: () => string | null } {
130
- const { channel, files } = o;
131
- const now = o.now ?? Date.now;
132
- let lastShotMs = Number.NEGATIVE_INFINITY;
133
- let activeUpload: { token: string | null; abort: { aborted: boolean } } | null = null;
134
- let incoming: { transferId: string; totalBytes: number; sha256Hex: string; scopesCsv: string; path: string; chain: Promise<unknown> } | null = null;
135
- let gesture: { x: number; y: number; lastX: number; lastY: number; at: number } | null = null;
136
-
137
- // ── screenshot (1 Hz) ──
138
- channel.on(DeviceHubListeners.screenshotRequest, (requestId: unknown, maxEdge: unknown, quality: unknown) => {
139
- void (async () => {
140
- const id = String(requestId);
141
- const error = (errorCode: string, message: string) => channel.push(DeviceHubMethods.reportScreenshotError, { requestId: id, errorCode, message, reportedAtUtc: nowIso(now) });
142
- if (!channel.admit('screenshot')) return error('NotConsented', 'Live access not granted');
143
- if (!o.screenshot) return error('Unsupported', 'This app does not capture its screen');
144
- const wait = SCREENSHOT_MIN_GAP_MS - (now() - lastShotMs);
145
- if (wait > 0) await new Promise((r) => setTimeout(r, wait));
146
- lastShotMs = now();
147
- try {
148
- const shot = await o.screenshot(Number(maxEdge) || 1280, Number(quality) || 60);
149
- await channel.push(DeviceHubMethods.pushScreenshot, {
150
- widthPx: shot.widthPx,
151
- heightPx: shot.heightPx,
152
- mimeType: shot.mimeType ?? 'image/jpeg',
153
- dataBase64: shot.dataBase64,
154
- capturedAtUtc: nowIso(now),
155
- pageName: o.pageName?.() ?? null,
156
- });
157
- } catch (e) {
158
- await error('CaptureFailed', errorText(e));
159
- }
160
- })();
161
- });
162
-
163
- // ── SQL console ──
164
- channel.on(DeviceHubListeners.sqlRequest, (requestId: unknown, request: unknown) => {
165
- void (async () => {
166
- const req = request as SqlExecRequestPayload;
167
- const answer = channel.admit('sql') ? await runSql(o.sql, req, now) : await runSql(undefined, req, now).then((r) => ({ ...r, errorMessage: 'Live access not granted' }));
168
- if (req.readOnly === false && !answer.errorMessage) channel.info(`Operator SQL write: ${req.sql.slice(0, 200)}`, 'warn');
169
- await channel.push(DeviceHubMethods.pushSqlResult, String(requestId), answer);
170
- })();
171
- });
172
-
173
- // ── stored log files ──
174
- const logs = () => channel.options.logs;
175
- channel.on(DeviceHubListeners.logFileListRequest, (requestId: unknown) => {
176
- void (async () => {
177
- const source = logs();
178
- const limit = source?.retainedFileLimit ?? 7;
179
- if (!channel.admit('logfiles')) return channel.push(DeviceHubMethods.pushLogFileList, String(requestId), { files: [], fileLoggingEnabled: false, retainedFileLimit: limit, errorMessage: 'Live access not granted' });
180
- if (!source) return channel.push(DeviceHubMethods.pushLogFileList, String(requestId), { files: [], fileLoggingEnabled: false, retainedFileLimit: limit, errorMessage: null });
181
- try {
182
- await source.flush?.();
183
- const active = source.currentFilePath();
184
- const list = (await source.files()).filter((f) => LOG_NAME.test(f.name));
185
- await channel.push(DeviceHubMethods.pushLogFileList, String(requestId), {
186
- files: list.map((f) => ({ name: f.name, sizeBytes: f.size, lastWriteUtc: new Date(f.modifiedMs).toISOString(), isActive: f.path === active })),
187
- fileLoggingEnabled: source.fileLoggingEnabled(),
188
- retainedFileLimit: limit,
189
- errorMessage: null,
190
- });
191
- } catch (e) {
192
- await channel.push(DeviceHubMethods.pushLogFileList, String(requestId), { files: [], fileLoggingEnabled: false, retainedFileLimit: limit, errorMessage: errorText(e) });
193
- }
194
- })();
195
- });
196
-
197
- channel.on(DeviceHubListeners.logFileReadRequest, (requestId: unknown, request: unknown) => {
198
- void (async () => {
199
- const req = request as LogFileReadRequestPayload;
200
- const empty = { name: req.name, content: '', offset: 0, nextOffset: 0, totalBytes: 0, endOfFile: true };
201
- const reply = (p: object) => channel.push(DeviceHubMethods.pushLogFileContent, String(requestId), p);
202
- if (!channel.admit('logfiles')) return reply({ ...empty, errorMessage: 'Live access not granted' });
203
- if (!LOG_NAME.test(req.name)) return reply({ ...empty, errorMessage: 'bad file name' });
204
- try {
205
- // Only a file in the source's list is ever served (never a path the console made up).
206
- const file = (await (logs()?.files() ?? Promise.resolve([]))).find((f) => f.name === req.name);
207
- if (!file) return reply({ ...empty, errorMessage: 'no such log file' });
208
- const total = await files.size(file.path);
209
- const max = Math.max(1024, Math.min(1024 * 1024, req.maxBytes || 256 * 1024));
210
- const offset = req.fromEnd ? Math.max(0, total - max) : Math.max(0, Math.min(total, req.offset || 0));
211
- const content = utf8Decode(base64ToBytes(await files.readChunk(file.path, offset, max)));
212
- const read = Math.min(max, total - offset);
213
- await reply({ name: req.name, content, offset, nextOffset: offset + read, totalBytes: total, endOfFile: offset + read >= total, errorMessage: null });
214
- } catch (e) {
215
- await reply({ ...empty, errorMessage: errorText(e) });
216
- }
217
- })();
218
- });
219
-
220
- // ── a backup the operator asked for (built here, uploaded through the hub) ──
221
- channel.on(DeviceHubListeners.backupRequest, (requestId: unknown, request: unknown, password: unknown, note: unknown) => {
222
- void (async () => {
223
- if (!channel.admit('backup') || !o.backup || !channel.hub) return;
224
- const scopes = normalizeScopes(request as Partial<BackupBuildRequestPayload>);
225
- const abort = { aborted: false };
226
- activeUpload = { token: null, abort };
227
- const hold = await o.keepAlive?.begin({ category: 'backup', title: o.texts?.backupTitle ?? 'Backup', subtitle: o.texts?.backupSubtitle ?? null, showProgress: true }).catch(() => null);
228
- let path: string | null = null;
229
- try {
230
- const outcome = await sendBundle(o, 'backup', scopes, {
231
- note: typeof note === 'string' ? note : null,
232
- password: typeof password === 'string' && password ? password : null,
233
- source: BackupSource.liveDiagnostic,
234
- signal: abort,
235
- onToken: (token) => {
236
- if (activeUpload) activeUpload.token = token;
237
- },
238
- onProgress: (sent, total) => hold?.progress(total > 0 ? sent / total : 0),
239
- onPath: (p) => (path = p),
240
- });
241
- channel.info(`Operator backup ${String(requestId)}: ${outcome.ok ? `uploaded (${outcome.bytes} bytes)` : outcome.error}`, outcome.ok ? 'info' : 'warn');
242
- } catch (e) {
243
- channel.reportError('live.backup', e);
244
- } finally {
245
- if (path) await files.remove(path).catch(() => {});
246
- activeUpload = null;
247
- await Promise.resolve(hold?.end()).catch(() => {});
248
- }
249
- })();
250
- });
251
-
252
- channel.on(DeviceHubListeners.backupCancelled, (token: unknown) => {
253
- if (activeUpload && (activeUpload.token === token || activeUpload.token === null)) activeUpload.abort.aborted = true;
254
- });
255
-
256
- // ── a restore the operator pushes: received in order, verified, applied, then the app closes ──
257
- const restoreResult = (transferId: string, ok: boolean, error: string | null, receivedBytes: number) =>
258
- channel.push(DeviceHubMethods.pushRestoreResult, transferId, { transferId, ok, error, receivedBytes });
259
-
260
- channel.on(DeviceHubListeners.restoreBegin, (transferId: unknown, filename: unknown, totalBytes: unknown, sha256Hex: unknown, scopesCsv: unknown) => {
261
- void (async () => {
262
- const id = String(transferId);
263
- if (!channel.admit('restore')) return restoreResult(id, false, 'Live access not granted', 0);
264
- if (!o.restore) return restoreResult(id, false, 'This app does not accept a restore', 0);
265
- try {
266
- if (!/^[A-Za-z0-9_-]{1,80}$/.test(id)) throw new Error(`bad transfer id ${id}`);
267
- const path = `${await o.folders.restore()}/${id}.zip`;
268
- const total = Number(totalBytes);
269
- let have = await files.size(path).catch(() => 0);
270
- if (have > total) {
271
- await files.remove(path);
272
- have = 0;
273
- }
274
- incoming = { transferId: id, totalBytes: total, sha256Hex: String(sha256Hex ?? '').toLowerCase(), scopesCsv: typeof scopesCsv === 'string' ? scopesCsv : '', path, chain: Promise.resolve() };
275
- channel.info(`Restore ${id} (${String(filename)}): ${total} bytes, ${have} already here`);
276
- await channel.push(DeviceHubMethods.pushRestoreReady, id, have);
277
- } catch (e) {
278
- await restoreResult(id, false, errorText(e), 0);
279
- }
280
- })();
281
- });
282
-
283
- channel.on(DeviceHubListeners.restoreResume, (transferId: unknown, fromOffset: unknown) => {
284
- const target = incoming;
285
- if (!target || target.transferId !== transferId) return;
286
- // The device holds its file at exactly the offset the gateway streams from (a lost ready ack → 0: start clean).
287
- target.chain = target.chain.then(async () => {
288
- const at = Number(fromOffset);
289
- const have = await files.size(target.path).catch(() => 0);
290
- if (at === 0 && have > 0) await files.remove(target.path).catch(() => {});
291
- else if (at !== have) channel.info(`Restore ${target.transferId}: the gateway resumes at ${at}, the device holds ${have}`, 'warn');
292
- });
293
- });
294
-
295
- channel.on(DeviceHubListeners.restoreChunk, (transferId: unknown, data: unknown) => {
296
- const target = incoming;
297
- if (!target || target.transferId !== transferId || typeof data !== 'string') return;
298
- // In order, one after the other: SignalR delivers the chunks in order, appends must land in order too.
299
- target.chain = target.chain.then(() => files.appendChunk(target.path, data)).catch((e: unknown) => channel.reportError('live.restore.chunk', e));
300
- });
301
-
302
- channel.on(DeviceHubListeners.restoreComplete, (transferId: unknown) => {
303
- void (async () => {
304
- const target = incoming;
305
- if (!target || target.transferId !== transferId) return;
306
- incoming = null;
307
- await target.chain.catch(() => {});
308
- try {
309
- const size = await files.size(target.path);
310
- if (size !== target.totalBytes) throw new Error(`incomplete: ${size} of ${target.totalBytes} bytes`);
311
- if (target.sha256Hex && (await files.sha256(target.path)).toLowerCase() !== target.sha256Hex) throw new Error('checksum mismatch: the archive is damaged');
312
- await o.restore!.restore(target.path, target.scopesCsv);
313
- await files.remove(target.path).catch(() => {});
314
- await restoreResult(target.transferId, true, null, size);
315
- channel.info(`Restore ${target.transferId} applied: the app closes`, 'warn');
316
- channel.options.host.closeApp();
317
- } catch (e) {
318
- const received = await files.size(target.path).catch(() => 0);
319
- await restoreResult(target.transferId, false, errorText(e), received);
320
- }
321
- })();
322
- });
323
-
324
- // ── remote input: down / move / up become a tap, a long press or a drag ──
325
- channel.on(DeviceHubListeners.remoteInput, (command: unknown) => {
326
- void (async () => {
327
- const cmd = command as RemoteInputCommand;
328
- if (!channel.admit('remote') || !o.remoteInput) return;
329
- try {
330
- const x = Number(cmd.normX);
331
- const y = Number(cmd.normY);
332
- if (cmd.kind === 'down') gesture = { x, y, lastX: x, lastY: y, at: now() };
333
- else if (cmd.kind === 'move' && gesture) gesture = { ...gesture, lastX: x, lastY: y };
334
- else if (cmd.kind === 'up' && gesture) {
335
- const g = gesture;
336
- gesture = null;
337
- // ~12 px on a 1080 px screen: below it the finger did not move, it tapped.
338
- const moved = Math.hypot(x - g.x, y - g.y) > 0.011;
339
- const held = now() - g.at;
340
- await o.remoteInput.perform(moved ? { kind: 'drag', x: g.x, y: g.y, toX: x, toY: y, durationMs: Math.max(150, held) } : { kind: held > 600 ? 'longPress' : 'tap', x, y });
341
- } else if (cmd.kind === 'tap') await o.remoteInput.perform({ kind: 'tap', x, y });
342
- else if (cmd.kind === 'text' && cmd.text) await o.remoteInput.perform({ kind: 'text', text: cmd.text });
343
- } catch (e) {
344
- channel.reportError('live.remoteInput', e);
345
- }
346
- })();
347
- });
348
-
349
- return { backupInFlight: () => activeUpload !== null, restoreInFlight: () => incoming?.transferId ?? null };
350
- }
351
-
352
- export interface SendBundleOptions {
353
- readonly note?: string | null;
354
- readonly password?: string | null;
355
- readonly source: number;
356
- /** A full report's own entries (report/report.json, report/attachments/…). */
357
- readonly extra?: readonly DiagnosticZipEntry[];
358
- readonly resumeToken?: string | null;
359
- readonly signal?: { readonly aborted: boolean };
360
- readonly onToken?: (token: string) => void;
361
- readonly onProgress?: (sent: number, total: number) => void;
362
- /** The file being sent (the caller removes it when it is done with it). */
363
- readonly onPath?: (path: string) => void;
364
- }
365
-
366
- /** Builds a bundle (the app's entries + bundle.json), seals it when a password is given, and sends it over the hub. */
367
- export async function sendBundle(o: LiveHandlerOptions, kind: BundleKind, scopes: BackupBuildRequestPayload, s: SendBundleOptions): Promise<BundleUploadOutcome> {
368
- const { channel, files } = o;
369
- const hub = channel.hub;
370
- if (!hub) return { ok: false, error: 'not connected', token: null, cancelledByOperator: false, retryable: true };
371
- if (!o.backup) return { ok: false, error: 'This app does not build bundles', token: null, cancelledByOperator: false, retryable: false };
372
- const now = o.now ?? Date.now;
373
- const filename = bundleFileName(o.product.filePrefix, kind, now());
374
- const out = `${await o.folders.outgoing()}/${filename}`;
375
- const manifest = bundleManifest({
376
- kind,
377
- product: o.product.name,
378
- appVersion: o.product.appVersion,
379
- appBuild: o.product.appBuild,
380
- branch: channel.options.branch ?? null,
381
- commit: channel.options.commit ?? null,
382
- platform: o.product.platform,
383
- clientId: channel.clientId,
384
- username: await channel.options.host.username().catch(() => null),
385
- note: s.note ?? null,
386
- scopes,
387
- now,
388
- });
389
- const built = await o.backup.build({ kind, scopes, out, extra: [{ name: BUNDLE_ENTRY, text: manifest }, ...(s.extra ?? [])] });
390
- let path = built.path;
391
- const sealed = !!s.password && !!o.backup.encrypt;
392
- if (sealed) {
393
- const encrypted = `${built.path}.aenc`;
394
- await o.backup.encrypt!(built.path, encrypted, s.password!);
395
- await files.remove(built.path).catch(() => {});
396
- path = encrypted;
397
- }
398
- s.onPath?.(path);
399
- return uploadBundle(
400
- hub,
401
- files,
402
- {
403
- clientId: channel.clientId,
404
- path,
405
- filename: sealed ? `${filename}.aenc` : filename,
406
- source: s.source,
407
- note: s.note ?? null,
408
- isPasswordProtected: sealed,
409
- isSensitive: built.containsSensitive,
410
- include: {
411
- sqlite: scopes.includeSqlite,
412
- logs: scopes.includeLogs,
413
- attachments: scopes.includeAttachments,
414
- geoDatabase: scopes.includeGeoDatabase,
415
- preferences: scopes.includePreferences,
416
- secureStorage: scopes.includeSecureStorage,
417
- },
418
- ...(s.resumeToken !== undefined ? { resumeToken: s.resumeToken } : {}),
419
- },
420
- {
421
- ...(s.signal ? { signal: s.signal } : {}),
422
- ...(s.onToken ? { onToken: s.onToken } : {}),
423
- ...(s.onProgress ? { onProgress: s.onProgress } : {}),
424
- },
425
- );
426
- }
1
+ // What an operator can ask of every device (G9AppDiagnostic.Maui LiveScreenshotServerPusher, LiveSqlServerHandler,
2
+ // LiveLogFileServerHandler, LiveBackupServerHandler, the restore stream, LiveRemoteInputHandler), each answered through
3
+ // its Push… method with the same requestId. Everything that looks INTO the device needs the user's consent
4
+ // (channel.admit); a refusal still answers, so the console never waits for a timeout. No handler throws at the
5
+ // connection. Product commands (sync control, NFC, a QA bridge) are the app's extensions.
6
+ import { base64ToBytes, utf8Decode } from '../bytes.ts';
7
+ import { type DiagnosticFiles, type DiagnosticZipEntry, errorText } from '../host.ts';
8
+ import { DeviceHubListeners, DeviceHubMethods } from '../wire.ts';
9
+ import { BUNDLE_ENTRY, bundleFileName, bundleManifest, type BundleKind, normalizeScopes } from './bundle.ts';
10
+ import type { ILiveKeepAlive, LiveChannel } from './channel.ts';
11
+ import type { BackupBuildRequestPayload, LogFileReadRequestPayload, RemoteInputCommand, SqlExecRequestPayload, SqlResultPayload } from './models.ts';
12
+ import { BackupSource } from './models.ts';
13
+ import { type BundleUploadOutcome, uploadBundle } from './upload.ts';
14
+
15
+ /** The operator's SQL console on the app's database (ILiveSqlTarget): raw I/O; the channel keeps the policy. */
16
+ export interface ILiveSqlTarget {
17
+ /** False when no database is open (signed out). */
18
+ available(): boolean;
19
+ query(sql: string): Promise<{ readonly columns: readonly string[]; readonly rows: ReadonlyArray<ReadonlyArray<unknown>> }>;
20
+ execute(sql: string): Promise<{ readonly changes: number }>;
21
+ }
22
+
23
+ /** The app's diagnostic bundle (ILiveBackupSource): what goes in for the scopes asked; the channel adds its own entries. */
24
+ export interface ILiveBackupSource {
25
+ /** Zips the app's entries for `scopes` plus `extra` (bundle.json, a report) into `out`. */
26
+ build(request: { readonly kind: BundleKind; readonly scopes: BackupBuildRequestPayload; readonly out: string; readonly extra: readonly DiagnosticZipEntry[] }): Promise<{ readonly path: string; readonly containsSensitive: boolean }>;
27
+ /** The password envelope (the wire profile's backupMagic): `source` → `destination`. */
28
+ encrypt?(source: string, destination: string, password: string): Promise<void>;
29
+ }
30
+
31
+ /** Applies a verified restore archive (ILiveRestoreTarget); the host closes or restarts the app after. */
32
+ export interface ILiveRestoreTarget {
33
+ /** `scopesCsv`: the operator's sections ("" = everything in the archive). */
34
+ restore(zipPath: string, scopesCsv: string): Promise<void>;
35
+ }
36
+
37
+ /** A remote-input action on the app's own window, in fractions of the window (0..1). */
38
+ export type RemoteAction =
39
+ | { readonly kind: 'tap' | 'longPress'; readonly x: number; readonly y: number }
40
+ | { readonly kind: 'drag'; readonly x: number; readonly y: number; readonly toX: number; readonly toY: number; readonly durationMs: number }
41
+ | { readonly kind: 'text'; readonly text: string };
42
+
43
+ /** The platform's input injection (Android: real touches into the app's window; iOS: a logical tap). */
44
+ export interface ILiveRemoteInput {
45
+ perform(action: RemoteAction): Promise<void>;
46
+ }
47
+
48
+ /** The window as a JPEG for the operator (the platform package's capture). */
49
+ export type LiveScreenshot = (maxEdge: number, quality: number) => Promise<{ readonly widthPx: number; readonly heightPx: number; readonly dataBase64: string; readonly mimeType?: string }>;
50
+
51
+ export interface LiveHandlerOptions {
52
+ readonly channel: LiveChannel;
53
+ readonly files: DiagnosticFiles;
54
+ readonly screenshot?: LiveScreenshot;
55
+ /** The visible screen's name in a screenshot frame. */
56
+ readonly pageName?: () => string | null;
57
+ readonly sql?: ILiveSqlTarget;
58
+ readonly backup?: ILiveBackupSource;
59
+ readonly restore?: ILiveRestoreTarget;
60
+ readonly remoteInput?: ILiveRemoteInput;
61
+ readonly keepAlive?: ILiveKeepAlive;
62
+ /** Where built bundles and received restores wait (absolute folders). */
63
+ readonly folders: { readonly outgoing: () => Promise<string>; readonly restore: () => Promise<string> };
64
+ /** Bundle names and manifest (BundleFilePrefix, ProductName). */
65
+ readonly product: { readonly name: string; readonly filePrefix: string; readonly appVersion: string; readonly appBuild: string; readonly platform: string };
66
+ /** The keep-alive's texts. */
67
+ readonly texts?: { readonly backupTitle: string; readonly backupSubtitle: string };
68
+ readonly now?: () => number;
69
+ }
70
+
71
+ export const MAX_SQL_ROWS = 5000;
72
+ const READ_ONLY_SQL = /^\s*(select|pragma|explain|with)\b/i;
73
+ /** One screenshot per second at most (the 1 Hz cap). */
74
+ export const SCREENSHOT_MIN_GAP_MS = 1000;
75
+ const LOG_NAME = /^[A-Za-z0-9._-]+\.log$/;
76
+
77
+ function cell(v: unknown): string | null {
78
+ if (v === null || v === undefined) return null;
79
+ if (typeof v === 'object') return JSON.stringify(v);
80
+ return String(v);
81
+ }
82
+
83
+ const nowIso = (now: () => number) => new Date(now()).toISOString();
84
+
85
+ /** The SQL console's policy: read-only unless the operator flipped it, a row cap, a time limit. */
86
+ export async function runSql(target: ILiveSqlTarget | undefined, req: SqlExecRequestPayload, now: () => number = Date.now): Promise<SqlResultPayload> {
87
+ const started = now();
88
+ const result = (patch: Partial<SqlResultPayload>): SqlResultPayload => ({
89
+ columnNames: [],
90
+ columnTypes: [],
91
+ rows: [],
92
+ rowsAffected: 0,
93
+ rowsReturned: 0,
94
+ durationMs: now() - started,
95
+ errorMessage: null,
96
+ truncated: false,
97
+ ...patch,
98
+ });
99
+ if (!target) return result({ errorMessage: 'This app does not offer the SQL console.' });
100
+ if (!target.available()) return result({ errorMessage: 'No user database is open' });
101
+ try {
102
+ const timeout = Math.max(5, Math.min(300, req.timeoutSeconds || 60)) * 1000;
103
+ const work = (async (): Promise<SqlResultPayload> => {
104
+ if (req.readOnly !== false) {
105
+ if (!READ_ONLY_SQL.test(req.sql)) return result({ errorMessage: 'Read-only mode: only SELECT / PRAGMA / EXPLAIN / WITH' });
106
+ const raw = await target.query(req.sql);
107
+ const max = Math.max(1, Math.min(MAX_SQL_ROWS, req.maxRows || 1000));
108
+ const rows = raw.rows.slice(0, max).map((r) => r.map(cell));
109
+ return result({ columnNames: raw.columns.map(String), columnTypes: raw.columns.map(() => ''), rows, rowsReturned: rows.length, truncated: raw.rows.length > max });
110
+ }
111
+ const r = await target.execute(req.sql);
112
+ return result({ rowsAffected: r.changes });
113
+ })();
114
+ let timer: ReturnType<typeof setTimeout> | undefined;
115
+ const limit = new Promise<SqlResultPayload>((r) => {
116
+ timer = setTimeout(() => r(result({ errorMessage: `Timed out after ${timeout / 1000} s` })), timeout);
117
+ });
118
+ try {
119
+ return await Promise.race([work, limit]);
120
+ } finally {
121
+ if (timer !== undefined) clearTimeout(timer);
122
+ }
123
+ } catch (e) {
124
+ return result({ errorMessage: errorText(e) });
125
+ }
126
+ }
127
+
128
+ /** Wires the core operator commands on the channel. Returns what a test or the app needs to reach. */
129
+ export function wireLiveHandlers(o: LiveHandlerOptions): { readonly backupInFlight: () => boolean; readonly restoreInFlight: () => string | null } {
130
+ const { channel, files } = o;
131
+ const now = o.now ?? Date.now;
132
+ let lastShotMs = Number.NEGATIVE_INFINITY;
133
+ let activeUpload: { token: string | null; abort: { aborted: boolean } } | null = null;
134
+ let incoming: { transferId: string; totalBytes: number; sha256Hex: string; scopesCsv: string; path: string; chain: Promise<unknown> } | null = null;
135
+ let gesture: { x: number; y: number; lastX: number; lastY: number; at: number } | null = null;
136
+
137
+ // ── screenshot (1 Hz) ──
138
+ channel.on(DeviceHubListeners.screenshotRequest, (requestId: unknown, maxEdge: unknown, quality: unknown) => {
139
+ void (async () => {
140
+ const id = String(requestId);
141
+ const error = (errorCode: string, message: string) => channel.push(DeviceHubMethods.reportScreenshotError, { requestId: id, errorCode, message, reportedAtUtc: nowIso(now) });
142
+ if (!channel.admit('screenshot')) return error('NotConsented', 'Live access not granted');
143
+ if (!o.screenshot) return error('Unsupported', 'This app does not capture its screen');
144
+ const wait = SCREENSHOT_MIN_GAP_MS - (now() - lastShotMs);
145
+ if (wait > 0) await new Promise((r) => setTimeout(r, wait));
146
+ lastShotMs = now();
147
+ try {
148
+ const shot = await o.screenshot(Number(maxEdge) || 1280, Number(quality) || 60);
149
+ await channel.push(DeviceHubMethods.pushScreenshot, {
150
+ widthPx: shot.widthPx,
151
+ heightPx: shot.heightPx,
152
+ mimeType: shot.mimeType ?? 'image/jpeg',
153
+ dataBase64: shot.dataBase64,
154
+ capturedAtUtc: nowIso(now),
155
+ pageName: o.pageName?.() ?? null,
156
+ });
157
+ } catch (e) {
158
+ await error('CaptureFailed', errorText(e));
159
+ }
160
+ })();
161
+ });
162
+
163
+ // ── SQL console ──
164
+ channel.on(DeviceHubListeners.sqlRequest, (requestId: unknown, request: unknown) => {
165
+ void (async () => {
166
+ const req = request as SqlExecRequestPayload;
167
+ const answer = channel.admit('sql') ? await runSql(o.sql, req, now) : await runSql(undefined, req, now).then((r) => ({ ...r, errorMessage: 'Live access not granted' }));
168
+ if (req.readOnly === false && !answer.errorMessage) channel.info(`Operator SQL write: ${req.sql.slice(0, 200)}`, 'warn');
169
+ await channel.push(DeviceHubMethods.pushSqlResult, String(requestId), answer);
170
+ })();
171
+ });
172
+
173
+ // ── stored log files ──
174
+ const logs = () => channel.options.logs;
175
+ channel.on(DeviceHubListeners.logFileListRequest, (requestId: unknown) => {
176
+ void (async () => {
177
+ const source = logs();
178
+ const limit = source?.retainedFileLimit ?? 7;
179
+ if (!channel.admit('logfiles')) return channel.push(DeviceHubMethods.pushLogFileList, String(requestId), { files: [], fileLoggingEnabled: false, retainedFileLimit: limit, errorMessage: 'Live access not granted' });
180
+ if (!source) return channel.push(DeviceHubMethods.pushLogFileList, String(requestId), { files: [], fileLoggingEnabled: false, retainedFileLimit: limit, errorMessage: null });
181
+ try {
182
+ await source.flush?.();
183
+ const active = source.currentFilePath();
184
+ const list = (await source.files()).filter((f) => LOG_NAME.test(f.name));
185
+ await channel.push(DeviceHubMethods.pushLogFileList, String(requestId), {
186
+ files: list.map((f) => ({ name: f.name, sizeBytes: f.size, lastWriteUtc: new Date(f.modifiedMs).toISOString(), isActive: f.path === active })),
187
+ fileLoggingEnabled: source.fileLoggingEnabled(),
188
+ retainedFileLimit: limit,
189
+ errorMessage: null,
190
+ });
191
+ } catch (e) {
192
+ await channel.push(DeviceHubMethods.pushLogFileList, String(requestId), { files: [], fileLoggingEnabled: false, retainedFileLimit: limit, errorMessage: errorText(e) });
193
+ }
194
+ })();
195
+ });
196
+
197
+ channel.on(DeviceHubListeners.logFileReadRequest, (requestId: unknown, request: unknown) => {
198
+ void (async () => {
199
+ const req = request as LogFileReadRequestPayload;
200
+ const empty = { name: req.name, content: '', offset: 0, nextOffset: 0, totalBytes: 0, endOfFile: true };
201
+ const reply = (p: object) => channel.push(DeviceHubMethods.pushLogFileContent, String(requestId), p);
202
+ if (!channel.admit('logfiles')) return reply({ ...empty, errorMessage: 'Live access not granted' });
203
+ if (!LOG_NAME.test(req.name)) return reply({ ...empty, errorMessage: 'bad file name' });
204
+ try {
205
+ // Only a file in the source's list is ever served (never a path the console made up).
206
+ const file = (await (logs()?.files() ?? Promise.resolve([]))).find((f) => f.name === req.name);
207
+ if (!file) return reply({ ...empty, errorMessage: 'no such log file' });
208
+ const total = await files.size(file.path);
209
+ const max = Math.max(1024, Math.min(1024 * 1024, req.maxBytes || 256 * 1024));
210
+ const offset = req.fromEnd ? Math.max(0, total - max) : Math.max(0, Math.min(total, req.offset || 0));
211
+ const content = utf8Decode(base64ToBytes(await files.readChunk(file.path, offset, max)));
212
+ const read = Math.min(max, total - offset);
213
+ await reply({ name: req.name, content, offset, nextOffset: offset + read, totalBytes: total, endOfFile: offset + read >= total, errorMessage: null });
214
+ } catch (e) {
215
+ await reply({ ...empty, errorMessage: errorText(e) });
216
+ }
217
+ })();
218
+ });
219
+
220
+ // ── a backup the operator asked for (built here, uploaded through the hub) ──
221
+ channel.on(DeviceHubListeners.backupRequest, (requestId: unknown, request: unknown, password: unknown, note: unknown) => {
222
+ void (async () => {
223
+ if (!channel.admit('backup') || !o.backup || !channel.hub) return;
224
+ const scopes = normalizeScopes(request as Partial<BackupBuildRequestPayload>);
225
+ const abort = { aborted: false };
226
+ activeUpload = { token: null, abort };
227
+ const hold = await o.keepAlive?.begin({ category: 'backup', title: o.texts?.backupTitle ?? 'Backup', subtitle: o.texts?.backupSubtitle ?? null, showProgress: true }).catch(() => null);
228
+ let path: string | null = null;
229
+ try {
230
+ const outcome = await sendBundle(o, 'backup', scopes, {
231
+ note: typeof note === 'string' ? note : null,
232
+ password: typeof password === 'string' && password ? password : null,
233
+ source: BackupSource.liveDiagnostic,
234
+ signal: abort,
235
+ onToken: (token) => {
236
+ if (activeUpload) activeUpload.token = token;
237
+ },
238
+ onProgress: (sent, total) => hold?.progress(total > 0 ? sent / total : 0),
239
+ onPath: (p) => (path = p),
240
+ });
241
+ channel.info(`Operator backup ${String(requestId)}: ${outcome.ok ? `uploaded (${outcome.bytes} bytes)` : outcome.error}`, outcome.ok ? 'info' : 'warn');
242
+ } catch (e) {
243
+ channel.reportError('live.backup', e);
244
+ } finally {
245
+ if (path) await files.remove(path).catch(() => {});
246
+ activeUpload = null;
247
+ await Promise.resolve(hold?.end()).catch(() => {});
248
+ }
249
+ })();
250
+ });
251
+
252
+ channel.on(DeviceHubListeners.backupCancelled, (token: unknown) => {
253
+ if (activeUpload && (activeUpload.token === token || activeUpload.token === null)) activeUpload.abort.aborted = true;
254
+ });
255
+
256
+ // ── a restore the operator pushes: received in order, verified, applied, then the app closes ──
257
+ const restoreResult = (transferId: string, ok: boolean, error: string | null, receivedBytes: number) =>
258
+ channel.push(DeviceHubMethods.pushRestoreResult, transferId, { transferId, ok, error, receivedBytes });
259
+
260
+ channel.on(DeviceHubListeners.restoreBegin, (transferId: unknown, filename: unknown, totalBytes: unknown, sha256Hex: unknown, scopesCsv: unknown) => {
261
+ void (async () => {
262
+ const id = String(transferId);
263
+ if (!channel.admit('restore')) return restoreResult(id, false, 'Live access not granted', 0);
264
+ if (!o.restore) return restoreResult(id, false, 'This app does not accept a restore', 0);
265
+ try {
266
+ if (!/^[A-Za-z0-9_-]{1,80}$/.test(id)) throw new Error(`bad transfer id ${id}`);
267
+ const path = `${await o.folders.restore()}/${id}.zip`;
268
+ const total = Number(totalBytes);
269
+ let have = await files.size(path).catch(() => 0);
270
+ if (have > total) {
271
+ await files.remove(path);
272
+ have = 0;
273
+ }
274
+ incoming = { transferId: id, totalBytes: total, sha256Hex: String(sha256Hex ?? '').toLowerCase(), scopesCsv: typeof scopesCsv === 'string' ? scopesCsv : '', path, chain: Promise.resolve() };
275
+ channel.info(`Restore ${id} (${String(filename)}): ${total} bytes, ${have} already here`);
276
+ await channel.push(DeviceHubMethods.pushRestoreReady, id, have);
277
+ } catch (e) {
278
+ await restoreResult(id, false, errorText(e), 0);
279
+ }
280
+ })();
281
+ });
282
+
283
+ channel.on(DeviceHubListeners.restoreResume, (transferId: unknown, fromOffset: unknown) => {
284
+ const target = incoming;
285
+ if (!target || target.transferId !== transferId) return;
286
+ // The device holds its file at exactly the offset the gateway streams from (a lost ready ack → 0: start clean).
287
+ target.chain = target.chain.then(async () => {
288
+ const at = Number(fromOffset);
289
+ const have = await files.size(target.path).catch(() => 0);
290
+ if (at === 0 && have > 0) await files.remove(target.path).catch(() => {});
291
+ else if (at !== have) channel.info(`Restore ${target.transferId}: the gateway resumes at ${at}, the device holds ${have}`, 'warn');
292
+ });
293
+ });
294
+
295
+ channel.on(DeviceHubListeners.restoreChunk, (transferId: unknown, data: unknown) => {
296
+ const target = incoming;
297
+ if (!target || target.transferId !== transferId || typeof data !== 'string') return;
298
+ // In order, one after the other: SignalR delivers the chunks in order, appends must land in order too.
299
+ target.chain = target.chain.then(() => files.appendChunk(target.path, data)).catch((e: unknown) => channel.reportError('live.restore.chunk', e));
300
+ });
301
+
302
+ channel.on(DeviceHubListeners.restoreComplete, (transferId: unknown) => {
303
+ void (async () => {
304
+ const target = incoming;
305
+ if (!target || target.transferId !== transferId) return;
306
+ incoming = null;
307
+ await target.chain.catch(() => {});
308
+ try {
309
+ const size = await files.size(target.path);
310
+ if (size !== target.totalBytes) throw new Error(`incomplete: ${size} of ${target.totalBytes} bytes`);
311
+ if (target.sha256Hex && (await files.sha256(target.path)).toLowerCase() !== target.sha256Hex) throw new Error('checksum mismatch: the archive is damaged');
312
+ await o.restore!.restore(target.path, target.scopesCsv);
313
+ await files.remove(target.path).catch(() => {});
314
+ await restoreResult(target.transferId, true, null, size);
315
+ channel.info(`Restore ${target.transferId} applied: the app closes`, 'warn');
316
+ channel.options.host.closeApp();
317
+ } catch (e) {
318
+ const received = await files.size(target.path).catch(() => 0);
319
+ await restoreResult(target.transferId, false, errorText(e), received);
320
+ }
321
+ })();
322
+ });
323
+
324
+ // ── remote input: down / move / up become a tap, a long press or a drag ──
325
+ channel.on(DeviceHubListeners.remoteInput, (command: unknown) => {
326
+ void (async () => {
327
+ const cmd = command as RemoteInputCommand;
328
+ if (!channel.admit('remote') || !o.remoteInput) return;
329
+ try {
330
+ const x = Number(cmd.normX);
331
+ const y = Number(cmd.normY);
332
+ if (cmd.kind === 'down') gesture = { x, y, lastX: x, lastY: y, at: now() };
333
+ else if (cmd.kind === 'move' && gesture) gesture = { ...gesture, lastX: x, lastY: y };
334
+ else if (cmd.kind === 'up' && gesture) {
335
+ const g = gesture;
336
+ gesture = null;
337
+ // ~12 px on a 1080 px screen: below it the finger did not move, it tapped.
338
+ const moved = Math.hypot(x - g.x, y - g.y) > 0.011;
339
+ const held = now() - g.at;
340
+ await o.remoteInput.perform(moved ? { kind: 'drag', x: g.x, y: g.y, toX: x, toY: y, durationMs: Math.max(150, held) } : { kind: held > 600 ? 'longPress' : 'tap', x, y });
341
+ } else if (cmd.kind === 'tap') await o.remoteInput.perform({ kind: 'tap', x, y });
342
+ else if (cmd.kind === 'text' && cmd.text) await o.remoteInput.perform({ kind: 'text', text: cmd.text });
343
+ } catch (e) {
344
+ channel.reportError('live.remoteInput', e);
345
+ }
346
+ })();
347
+ });
348
+
349
+ return { backupInFlight: () => activeUpload !== null, restoreInFlight: () => incoming?.transferId ?? null };
350
+ }
351
+
352
+ export interface SendBundleOptions {
353
+ readonly note?: string | null;
354
+ readonly password?: string | null;
355
+ readonly source: number;
356
+ /** A full report's own entries (report/report.json, report/attachments/…). */
357
+ readonly extra?: readonly DiagnosticZipEntry[];
358
+ readonly resumeToken?: string | null;
359
+ readonly signal?: { readonly aborted: boolean };
360
+ readonly onToken?: (token: string) => void;
361
+ readonly onProgress?: (sent: number, total: number) => void;
362
+ /** The file being sent (the caller removes it when it is done with it). */
363
+ readonly onPath?: (path: string) => void;
364
+ }
365
+
366
+ /** Builds a bundle (the app's entries + bundle.json), seals it when a password is given, and sends it over the hub. */
367
+ export async function sendBundle(o: LiveHandlerOptions, kind: BundleKind, scopes: BackupBuildRequestPayload, s: SendBundleOptions): Promise<BundleUploadOutcome> {
368
+ const { channel, files } = o;
369
+ const hub = channel.hub;
370
+ if (!hub) return { ok: false, error: 'not connected', token: null, cancelledByOperator: false, retryable: true };
371
+ if (!o.backup) return { ok: false, error: 'This app does not build bundles', token: null, cancelledByOperator: false, retryable: false };
372
+ const now = o.now ?? Date.now;
373
+ const filename = bundleFileName(o.product.filePrefix, kind, now());
374
+ const out = `${await o.folders.outgoing()}/${filename}`;
375
+ const manifest = bundleManifest({
376
+ kind,
377
+ product: o.product.name,
378
+ appVersion: o.product.appVersion,
379
+ appBuild: o.product.appBuild,
380
+ branch: channel.options.branch ?? null,
381
+ commit: channel.options.commit ?? null,
382
+ platform: o.product.platform,
383
+ clientId: channel.clientId,
384
+ username: await channel.options.host.username().catch(() => null),
385
+ note: s.note ?? null,
386
+ scopes,
387
+ now,
388
+ });
389
+ const built = await o.backup.build({ kind, scopes, out, extra: [{ name: BUNDLE_ENTRY, text: manifest }, ...(s.extra ?? [])] });
390
+ let path = built.path;
391
+ const sealed = !!s.password && !!o.backup.encrypt;
392
+ if (sealed) {
393
+ const encrypted = `${built.path}.aenc`;
394
+ await o.backup.encrypt!(built.path, encrypted, s.password!);
395
+ await files.remove(built.path).catch(() => {});
396
+ path = encrypted;
397
+ }
398
+ s.onPath?.(path);
399
+ return uploadBundle(
400
+ hub,
401
+ files,
402
+ {
403
+ clientId: channel.clientId,
404
+ path,
405
+ filename: sealed ? `${filename}.aenc` : filename,
406
+ source: s.source,
407
+ note: s.note ?? null,
408
+ isPasswordProtected: sealed,
409
+ isSensitive: built.containsSensitive,
410
+ include: {
411
+ sqlite: scopes.includeSqlite,
412
+ logs: scopes.includeLogs,
413
+ attachments: scopes.includeAttachments,
414
+ geoDatabase: scopes.includeGeoDatabase,
415
+ preferences: scopes.includePreferences,
416
+ secureStorage: scopes.includeSecureStorage,
417
+ },
418
+ ...(s.resumeToken !== undefined ? { resumeToken: s.resumeToken } : {}),
419
+ },
420
+ {
421
+ ...(s.signal ? { signal: s.signal } : {}),
422
+ ...(s.onToken ? { onToken: s.onToken } : {}),
423
+ ...(s.onProgress ? { onProgress: s.onProgress } : {}),
424
+ },
425
+ );
426
+ }