@g9tm/app-diagnostic 0.0.0-stage → 0.2.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.
@@ -0,0 +1,145 @@
1
+ // The tester's drafts (G9AppDiagnostic.Maui TesterReportDraftStore): one folder per report — `report.json` at its root
2
+ // and one folder per attachment kind — so a force-close or a crash mid-session never costs the evidence: the panel
3
+ // re-attaches to the ACTIVE draft (a device-wide pointer; the draft carries its author) on the next launch.
4
+ // The root folder and the pointer's preference key are the app's: an app that had tester mode before keeps its own, or
5
+ // an update forgets the draft its tester was composing.
6
+ import type { DiagnosticFiles, DiagnosticPrefs } from '../host.ts';
7
+ import { isDraft, kindFolder, newReportId, safeFileName, type TesterAttachmentKind, type TesterReportAttachment, type TesterReportDraft, uniqueName } from './model.ts';
8
+
9
+ export interface DraftStoreOptions {
10
+ readonly files: DiagnosticFiles;
11
+ readonly prefs: DiagnosticPrefs;
12
+ /** The drafts' folder (absolute): `<root>/<id>/report.json`. */
13
+ readonly root: () => Promise<string>;
14
+ /** The preference that names the active draft. */
15
+ readonly activeKey: string;
16
+ readonly now?: () => number;
17
+ }
18
+
19
+ export interface AddAttachmentOptions {
20
+ readonly displayName?: string;
21
+ /** Our own temporary file: removed after it was copied in. */
22
+ readonly deleteSource?: boolean;
23
+ /** A recorder wrote the file INTO the kind folder: adopt it by name, never copy it. */
24
+ readonly inPlace?: boolean;
25
+ /** A recording: when it started (ISO). */
26
+ readonly startedUtc?: string;
27
+ /** The screen recording this file belongs to (its sound, its timeline). */
28
+ readonly pairedWith?: string;
29
+ }
30
+
31
+ export class TesterDraftStore {
32
+ private readonly o: DraftStoreOptions;
33
+ private readonly now: () => number;
34
+
35
+ constructor(options: DraftStoreOptions) {
36
+ this.o = options;
37
+ this.now = options.now ?? Date.now;
38
+ }
39
+
40
+ root(): Promise<string> {
41
+ return this.o.root();
42
+ }
43
+
44
+ async reportDir(id: string): Promise<string> {
45
+ return `${await this.o.root()}/${id}`;
46
+ }
47
+
48
+ async kindDir(id: string, kind: TesterAttachmentKind): Promise<string> {
49
+ return `${await this.reportDir(id)}/${kindFolder(kind)}`;
50
+ }
51
+
52
+ /** A report is started by its first piece of evidence: its title is the app's, written at send. */
53
+ async create(fields: Partial<Pick<TesterReportDraft, 'title' | 'description' | 'kind' | 'autoTitle' | 'autoDescription' | 'screen' | 'screenContext'>>, username: string | null): Promise<TesterReportDraft> {
54
+ const draft: TesterReportDraft = {
55
+ id: newReportId(),
56
+ title: (fields.title ?? '').trim(),
57
+ description: (fields.description ?? '').trim(),
58
+ createdUtc: new Date(this.now()).toISOString(),
59
+ attachments: [],
60
+ includeDatabaseBackup: false,
61
+ username,
62
+ ...(fields.kind ? { kind: fields.kind } : {}),
63
+ ...(fields.autoTitle ? { autoTitle: fields.autoTitle } : {}),
64
+ ...(fields.autoDescription ? { autoDescription: fields.autoDescription } : {}),
65
+ ...(fields.screen ? { screen: fields.screen } : {}),
66
+ ...(fields.screenContext ? { screenContext: fields.screenContext } : {}),
67
+ };
68
+ await this.save(draft);
69
+ this.o.prefs.set(this.o.activeKey, draft.id);
70
+ return draft;
71
+ }
72
+
73
+ /** The draft the panel should show, or null (a pointer to a vanished folder is cleared). */
74
+ async active(): Promise<TesterReportDraft | null> {
75
+ const id = this.o.prefs.get(this.o.activeKey);
76
+ if (!id) return null;
77
+ const draft = await this.read(id);
78
+ if (!draft) this.o.prefs.set(this.o.activeKey, null);
79
+ return draft;
80
+ }
81
+
82
+ async read(id: string): Promise<TesterReportDraft | null> {
83
+ try {
84
+ const parsed = JSON.parse(await this.o.files.readText(`${await this.reportDir(id)}/report.json`, 4 * 1024 * 1024)) as unknown;
85
+ return isDraft(parsed) ? parsed : null;
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+
91
+ async save(draft: TesterReportDraft): Promise<void> {
92
+ await this.o.files.writeText(`${await this.reportDir(draft.id)}/report.json`, JSON.stringify(draft, null, 2));
93
+ }
94
+
95
+ /**
96
+ * Adds a file to the draft. A recorder that wrote straight into the kind folder is only registered; anything else is
97
+ * COPIED in (a picked file belongs to the user) and the source removed only with `deleteSource` (our own temp files).
98
+ */
99
+ async addAttachment(draft: TesterReportDraft, kind: TesterAttachmentKind, source: string, options: AddAttachmentOptions = {}): Promise<TesterReportDraft> {
100
+ const files = this.o.files;
101
+ const dir = await this.kindDir(draft.id, kind);
102
+ const existing = new Set((await files.list(dir)).map((f) => f.name));
103
+ const sourceName = source.split('/').pop() ?? 'file';
104
+ let fileName: string;
105
+ // inPlace: adopt by NAME. Hosts canonicalise the folder they are given (Android /data/user/0 → /data/data, iOS
106
+ // /var → /private/var), so the returned path need not start with `dir`; a prefix test alone copied every recording
107
+ // next to itself ("screen-… (2).mp4", the bytes twice).
108
+ if (existing.has(sourceName) && (options.inPlace === true || source.startsWith(`${dir}/`))) {
109
+ fileName = sourceName;
110
+ } else {
111
+ fileName = uniqueName(safeFileName(options.displayName ?? sourceName), (c) => existing.has(c));
112
+ await files.copy(source, `${dir}/${fileName}`);
113
+ if (options.deleteSource) await files.remove(source).catch(() => {});
114
+ }
115
+ const sizeBytes = await files.size(`${dir}/${fileName}`).catch(() => 0);
116
+ const attachment: TesterReportAttachment = {
117
+ id: newReportId(),
118
+ kind,
119
+ fileName,
120
+ displayName: options.displayName ?? fileName,
121
+ sizeBytes,
122
+ capturedUtc: new Date(this.now()).toISOString(),
123
+ ...(options.startedUtc ? { startedUtc: options.startedUtc } : {}),
124
+ ...(options.pairedWith ? { pairedWith: options.pairedWith } : {}),
125
+ };
126
+ const next: TesterReportDraft = { ...draft, attachments: [...draft.attachments, attachment] };
127
+ await this.save(next);
128
+ return next;
129
+ }
130
+
131
+ async removeAttachment(draft: TesterReportDraft, attachmentId: string): Promise<TesterReportDraft> {
132
+ const a = draft.attachments.find((x) => x.id === attachmentId);
133
+ if (!a) return draft;
134
+ await this.o.files.remove(`${await this.kindDir(draft.id, a.kind)}/${a.fileName}`).catch(() => {});
135
+ const next: TesterReportDraft = { ...draft, attachments: draft.attachments.filter((x) => x.id !== attachmentId) };
136
+ await this.save(next);
137
+ return next;
138
+ }
139
+
140
+ /** Deletes the draft folder (after it was archived, or the tester discarded it). */
141
+ async discard(id: string): Promise<void> {
142
+ await this.o.files.remove(await this.reportDir(id));
143
+ if (this.o.prefs.get(this.o.activeKey) === id) this.o.prefs.set(this.o.activeKey, null);
144
+ }
145
+ }
@@ -0,0 +1,98 @@
1
+ // The app's own account of a screen recording (G9AppDiagnostic.Maui TesterTimelineRecorder): every log line the app
2
+ // wrote and every finger that landed, each with its offset in seconds from the recording's start, written beside the
3
+ // video as `timeline-*.json` and attached `pairedWith` the video. The lab's local AI takes a frame exactly where something
4
+ // HAPPENED, and an agent reads «0:42 tapped, 0:43 sync failed». Cheap: it listens to the app's log, appends to a bounded
5
+ // list and writes once at the end. The JSON is the .NET one, key for key.
6
+ import type { Unsubscribe } from '../host.ts';
7
+
8
+ /** One line of the app's log, as the timeline keeps it. */
9
+ export interface TesterLogLine {
10
+ readonly timeMs: number;
11
+ /** trace | debug | info | warn | error | critical (written as the .NET names), or a .NET name already. */
12
+ readonly level: string;
13
+ readonly category: string;
14
+ readonly message: string;
15
+ }
16
+
17
+ export type SubscribeLog = (listener: (line: TesterLogLine) => void) => Unsubscribe;
18
+
19
+ /** Hard cap — a 10-minute recording of a busy screen stays a few hundred kilobytes. */
20
+ const MAX_EVENTS = 4000;
21
+ const MAX_MESSAGE = 400;
22
+
23
+ export interface TimelineEvent {
24
+ readonly t: number;
25
+ readonly kind: 'log' | 'touch';
26
+ readonly level?: string;
27
+ readonly source?: string;
28
+ readonly text?: string;
29
+ readonly x?: number;
30
+ readonly y?: number;
31
+ readonly fingers?: number;
32
+ }
33
+
34
+ /** The .NET LogLevel names (the gateway, the live console and the timeline all read these). */
35
+ export const LOG_LEVEL_NAMES: Readonly<Record<string, string>> = { trace: 'Trace', debug: 'Debug', info: 'Information', warn: 'Warning', error: 'Error', critical: 'Critical' };
36
+
37
+ export const levelName = (level: string): string => LOG_LEVEL_NAMES[level] ?? level;
38
+
39
+ export class TesterTimeline {
40
+ private events: TimelineEvent[] = [];
41
+ private startedMs = 0;
42
+ private running = false;
43
+ private off: Unsubscribe | null = null;
44
+
45
+ get isRunning(): boolean {
46
+ return this.running;
47
+ }
48
+
49
+ start(startedMs: number, subscribe: SubscribeLog | null | undefined): void {
50
+ if (this.running) return;
51
+ this.events = [];
52
+ this.startedMs = startedMs;
53
+ this.running = true;
54
+ this.off =
55
+ subscribe?.((e) => {
56
+ const text = e.message.length > MAX_MESSAGE ? `${e.message.slice(0, MAX_MESSAGE)}…` : e.message;
57
+ this.push({ t: this.offset(e.timeMs), kind: 'log', level: levelName(e.level), source: e.category, text });
58
+ }) ?? null;
59
+ }
60
+
61
+ /** A finger landing, as fractions of the window (0..1). */
62
+ touch(x: number, y: number, fingers: number, atMs: number = Date.now()): void {
63
+ if (!this.running) return;
64
+ this.push({ t: this.offset(atMs), kind: 'touch', x: round(x, 3), y: round(y, 3), fingers });
65
+ }
66
+
67
+ /** Stops listening and answers the file's JSON, or null when nothing happened. */
68
+ stop(): string | null {
69
+ if (!this.running) return null;
70
+ this.running = false;
71
+ this.off?.();
72
+ this.off = null;
73
+ if (this.events.length === 0) return null;
74
+ const events = this.events.slice().sort((a, b) => a.t - b.t);
75
+ this.events = [];
76
+ return JSON.stringify({ startedUtc: new Date(this.startedMs).toISOString(), events });
77
+ }
78
+
79
+ private push(event: TimelineEvent): void {
80
+ if (this.events.length < MAX_EVENTS) this.events.push(event);
81
+ }
82
+
83
+ private offset(ms: number): number {
84
+ return round(Math.max(0, (ms - this.startedMs) / 1000), 2);
85
+ }
86
+ }
87
+
88
+ function round(v: number, digits: number): number {
89
+ const k = 10 ** digits;
90
+ return Math.round(v * k) / k;
91
+ }
92
+
93
+ /** `timeline-20261023-141502.json` (the .NET name, UTC). */
94
+ export function timelineFileName(startedMs: number): string {
95
+ const d = new Date(startedMs);
96
+ const p = (n: number) => String(n).padStart(2, '0');
97
+ return `timeline-${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}-${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}.json`;
98
+ }
package/src/upload.ts ADDED
@@ -0,0 +1,236 @@
1
+ // The tester-report upload contract (shared/schema/tester-report-upload.schema.json) and its resumable upload — the
2
+ // TypeScript twin of G9AppDiagnostic.Client (Wire.cs, TesterReportUploader.cs). No platform code: the archive's bytes
3
+ // come from the host, either through `read(offset, length)` (Node: fs) or as a native range request (a Lynx app: the
4
+ // chunk never crosses the bridge as base64).
5
+ import { type DiagnosticFetch, type DiagnosticSendRange, errorText, headerOf, withTimeout } from './host.ts';
6
+
7
+ export const UPLOAD_ROUTE = '/api/tester-reports/upload';
8
+ /** GET: every report on the gateway, for a device that has sent one (403 before that). */
9
+ export const FEED_ROUTE = `${UPLOAD_ROUTE}/feed`;
10
+ export const CLIENT_ID_HEADER = 'X-G9-Client-Id';
11
+ export const DEVICE_AUTH_HEADER = 'X-G9-Device-Auth';
12
+ export const RECEIVED_BYTES_HEADER = 'X-Received-Bytes';
13
+ export const MANIFEST_ENTRY = 'report.json';
14
+ /** A file's kind: its number in report.json is the index here, and its folder in the archive is the name. */
15
+ export const KINDS = ['Screenshot', 'Recording', 'Voice', 'File', 'Diagnostic', 'DatabaseBackup'] as const;
16
+ export type Kind = (typeof KINDS)[number];
17
+
18
+ export const isHexId = (v: string | null | undefined): boolean => !!v && v.length <= 64 && /^[0-9a-fA-F]+$/.test(v);
19
+
20
+ export interface DeviceIdentity {
21
+ clientId: string;
22
+ deviceSecret?: string | null;
23
+ }
24
+
25
+ /** The device headers the gateway reads. The neutral names by default; an app whose gateway predates them keeps its own. */
26
+ export interface DeviceHeaderNames {
27
+ readonly clientId: string;
28
+ readonly deviceAuth: string;
29
+ }
30
+
31
+ export const NEUTRAL_DEVICE_HEADERS: DeviceHeaderNames = { clientId: CLIENT_ID_HEADER, deviceAuth: DEVICE_AUTH_HEADER };
32
+
33
+ /** The headers that say who the device is, in the names the gateway reads. */
34
+ export function deviceHeaders(device: DeviceIdentity, names: DeviceHeaderNames = NEUTRAL_DEVICE_HEADERS): Record<string, string> {
35
+ const h: Record<string, string> = { [names.clientId]: device.clientId };
36
+ if (device.deviceSecret) h[names.deviceAuth] = device.deviceSecret;
37
+ return h;
38
+ }
39
+
40
+ export interface UploadInit {
41
+ reportId: string;
42
+ fileName: string;
43
+ totalBytes: number;
44
+ sha256: string;
45
+ title?: string;
46
+ description?: string;
47
+ username?: string;
48
+ platform?: string;
49
+ appVersion?: string;
50
+ environment?: string;
51
+ attachmentCount?: number;
52
+ includesDatabaseBackup?: boolean;
53
+ capturedUtc?: string;
54
+ /** bug, feature, improvement, investigation (the product's list); absent = bug. */
55
+ kind?: string;
56
+ /** The git branch the app was built from (Didban puts the report on that branch's track). */
57
+ branch?: string;
58
+ /** The commit the app was built from. */
59
+ commit?: string;
60
+ }
61
+
62
+ export interface UploadState {
63
+ reportId: string;
64
+ totalBytes: number;
65
+ receivedBytes: number;
66
+ chunkSize: number;
67
+ complete: boolean;
68
+ /** TR-0042: how people mention the report (absent from an older gateway). */
69
+ code?: string;
70
+ }
71
+
72
+ export interface UploadResult {
73
+ sent: boolean;
74
+ code: string;
75
+ error?: string;
76
+ status?: number;
77
+ }
78
+
79
+ export interface ArchiveAttachment {
80
+ id: string;
81
+ kind: number;
82
+ fileName: string;
83
+ displayName?: string;
84
+ sizeBytes?: number;
85
+ capturedUtc?: string;
86
+ startedUtc?: string;
87
+ pairedWith?: string;
88
+ }
89
+
90
+ export interface ArchiveManifest {
91
+ id: string;
92
+ title: string;
93
+ description?: string;
94
+ createdUtc?: string;
95
+ attachments: ArchiveAttachment[];
96
+ screenContext?: string[];
97
+ aiPack?: boolean;
98
+ }
99
+
100
+ /** The zip entry a file lives at — where the gateway looks for it. */
101
+ export const entryName = (a: Pick<ArchiveAttachment, 'kind' | 'fileName'>): string => `${KINDS[a.kind] ?? 'File'}/${a.fileName}`;
102
+
103
+ /** Reads `length` bytes of the archive from `offset` (fewer only at its end). */
104
+ export type ReadChunk = (offset: number, length: number) => Promise<Uint8Array>;
105
+
106
+ /** Where the archive's bytes come from: a reader (sent with `fetch`), or a file the host sends ranges of natively. */
107
+ export type UploadBody = ReadChunk | { readonly path: string };
108
+
109
+ export interface UploaderOptions {
110
+ gateway: string;
111
+ device: DeviceIdentity;
112
+ /** The device headers' names (default: the neutral X-G9-*). */
113
+ headers?: DeviceHeaderNames;
114
+ /** Extra headers on every request (a test tunnel's key), by URL. */
115
+ extraHeaders?: (url: string) => Readonly<Record<string, string>>;
116
+ /** One step's limit: a half-open socket fails the step, not the queue. Default 60 s. */
117
+ stepTimeoutMs?: number;
118
+ /** Default: the global fetch. */
119
+ fetch?: DiagnosticFetch;
120
+ /** The native range request for a `{ path }` body (required for one). */
121
+ sendRange?: DiagnosticSendRange;
122
+ }
123
+
124
+ const DEFAULT_CHUNK = 512 * 1024;
125
+
126
+ interface Step {
127
+ readonly status: number;
128
+ readonly body: string;
129
+ header(name: string): string | null;
130
+ }
131
+
132
+ const parseState = (text: string): UploadState | null => {
133
+ try {
134
+ const v = JSON.parse(text) as Partial<UploadState> | null;
135
+ return v && typeof v.receivedBytes === 'number' ? (v as UploadState) : null;
136
+ } catch {
137
+ return null;
138
+ }
139
+ };
140
+
141
+ /**
142
+ * The resumable upload: init → append chunks (Content-Range) → finalize. Safe to retry forever — init is idempotent by
143
+ * report id and says how many bytes the gateway holds; a 416 says where it really is. A failure is a result, never a
144
+ * throw, so an outbox drain keeps the archive and tries again later. `sent` only when the gateway has the WHOLE report:
145
+ * an outbox deletes the archive on it, and a premature success would destroy the tester's evidence.
146
+ */
147
+ export class TesterReportUploader {
148
+ private readonly base: string;
149
+ private readonly options: UploaderOptions;
150
+ private readonly stepTimeoutMs: number;
151
+
152
+ constructor(options: UploaderOptions) {
153
+ this.options = options;
154
+ this.base = options.gateway.replace(/\/+$/, '');
155
+ this.stepTimeoutMs = options.stepTimeoutMs ?? 60_000;
156
+ }
157
+
158
+ async upload(init: UploadInit, body: UploadBody): Promise<UploadResult> {
159
+ if (!isHexId(this.options.device.clientId)) return { sent: false, code: '', error: 'The device id must be hex.' };
160
+ if (!isHexId(init.reportId)) return { sent: false, code: '', error: 'The report id must be hex.' };
161
+ let code = '';
162
+ try {
163
+ let r = await this.json('POST', UPLOAD_ROUTE, JSON.stringify(init));
164
+ if (!ok(r)) return fail(r, '');
165
+ let state = parseState(r.body);
166
+ if (!state) return { sent: false, code: '', status: r.status, error: 'The gateway answered no upload state.' };
167
+ code = state.code ?? '';
168
+ let offset = Math.max(0, Math.min(state.receivedBytes, init.totalBytes));
169
+ const chunk = state.chunkSize > 0 ? state.chunkSize : DEFAULT_CHUNK;
170
+ while (!state.complete && offset < init.totalBytes) {
171
+ const length = Math.min(chunk, init.totalBytes - offset);
172
+ r = await this.append(init, body, offset, length);
173
+ if (r.status === 0) return { sent: false, code, error: 'The archive is shorter than declared.' };
174
+ if (r.status === 416) {
175
+ // The chunk landed while its answer was lost, or the gateway restarted: go on from where it is.
176
+ const header = Number(r.header(RECEIVED_BYTES_HEADER) ?? Number.NaN);
177
+ const at = parseState(r.body)?.receivedBytes ?? (Number.isFinite(header) ? header : -1);
178
+ if (!(at >= 0) || at === offset) return fail(r, code);
179
+ offset = at;
180
+ continue;
181
+ }
182
+ if (!ok(r)) return fail(r, code);
183
+ const next = parseState(r.body);
184
+ offset = next?.receivedBytes ?? offset + length;
185
+ if (next) state = next;
186
+ }
187
+ if (state.complete) return { sent: true, code };
188
+ r = await this.json('POST', `${UPLOAD_ROUTE}/${init.reportId}/finalize`);
189
+ // 409 = the bytes failed their digest and the gateway reset: the archive stays, the next attempt resends.
190
+ if (!ok(r)) return fail(r, code);
191
+ return parseState(r.body)?.complete === true ? { sent: true, code } : { sent: false, code, status: r.status, error: 'The gateway did not mark the report complete.' };
192
+ } catch (e) {
193
+ const text = errorText(e);
194
+ return { sent: false, code, error: /timed out|TimeoutError/i.test(text) || (e as Error)?.name === 'TimeoutError' ? 'A step timed out.' : text };
195
+ }
196
+ }
197
+
198
+ private headers(url: string, extra: Record<string, string>): Record<string, string> {
199
+ return { ...(this.options.extraHeaders?.(url) ?? {}), ...extra, ...deviceHeaders(this.options.device, this.options.headers ?? NEUTRAL_DEVICE_HEADERS) };
200
+ }
201
+
202
+ private async json(method: 'POST', path: string, body?: string): Promise<Step> {
203
+ const url = `${this.base}${path}`;
204
+ const headers = this.headers(url, { Accept: 'application/json', ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}) });
205
+ return this.fetchStep(url, { method, headers, ...(body !== undefined ? { body } : {}) });
206
+ }
207
+
208
+ private async append(init: UploadInit, body: UploadBody, offset: number, length: number): Promise<Step> {
209
+ const url = `${this.base}${UPLOAD_ROUTE}/${init.reportId}`;
210
+ const range = (n: number) => `bytes ${offset}-${offset + n - 1}/${init.totalBytes}`;
211
+ if (typeof body !== 'function') {
212
+ const send = this.options.sendRange;
213
+ if (!send) throw new Error('A file upload needs the host\'s sendRange.');
214
+ const r = await withTimeout(
215
+ send({ url, method: 'PUT', path: body.path, offset, length, contentType: 'application/octet-stream', headers: this.headers(url, { 'Content-Range': range(length) }), timeoutMs: this.stepTimeoutMs }),
216
+ this.stepTimeoutMs + 5000,
217
+ );
218
+ return { status: r.status, body: r.body, header: (n) => headerOf(r, n) };
219
+ }
220
+ const bytes = await body(offset, length);
221
+ if (!bytes.length) return { status: 0, body: '', header: () => null };
222
+ return this.fetchStep(url, { method: 'PUT', headers: this.headers(url, { 'Content-Type': 'application/octet-stream', 'Content-Range': range(bytes.length) }), body: bytes });
223
+ }
224
+
225
+ private async fetchStep(url: string, init: { method: 'POST' | 'PUT'; headers: Record<string, string>; body?: string | Uint8Array }): Promise<Step> {
226
+ const f = this.options.fetch ?? (globalThis as { fetch?: DiagnosticFetch }).fetch;
227
+ if (!f) throw new Error('No fetch: pass options.fetch.');
228
+ const r = await withTimeout(f(url, init), this.stepTimeoutMs);
229
+ const text = await withTimeout(r.text(), this.stepTimeoutMs).catch(() => '');
230
+ return { status: r.status, body: text, header: (n) => headerOf(r, n) };
231
+ }
232
+ }
233
+
234
+ const ok = (r: Step): boolean => r.status >= 200 && r.status < 300;
235
+
236
+ const fail = (r: Step, code: string): UploadResult => ({ sent: false, code, status: r.status, error: r.body.slice(0, 300) });
package/src/wire.ts ADDED
@@ -0,0 +1,133 @@
1
+ // The live channel's wire (shared/schema/live-channel.schema.json): the profile both sides must agree on byte for byte,
2
+ // the device hub's method and listener names, the capabilities, the transfer sizes. The TypeScript twin of
3
+ // G9AppDiagnostic.Shared (DiagnosticWire, ProtocolVersion, Hubs/HubMethodNames, IDeviceHubListeners, DeviceCapabilities).
4
+
5
+ /**
6
+ * The strings a device and its gateway must agree on: the protocol tag Hello is judged by (and every signature is bound
7
+ * to), the device hub's route, the magic of a password-encrypted backup, the bootstrap envelope's kind. A product that ran
8
+ * an earlier gateway keeps its own values (its devices carry them); a new product takes {@link NEUTRAL_WIRE}.
9
+ */
10
+ export interface DiagnosticWireProfile {
11
+ /** Printable ASCII, 8-40 characters. */
12
+ readonly protocolTag: string;
13
+ /** Relative to the gateway's base address, no slash. */
14
+ readonly deviceHubRoute: string;
15
+ /** Exactly 16 printable ASCII characters. */
16
+ readonly backupMagic: string;
17
+ readonly bootstrapKind: string;
18
+ }
19
+
20
+ export const NEUTRAL_WIRE: DiagnosticWireProfile = {
21
+ protocolTag: 'G9_LIVE_DIAG_v1',
22
+ deviceHubRoute: 'device-hub',
23
+ backupMagic: 'G9_APPD_BPASS_v2',
24
+ bootstrapKind: 'G9_LIVE_DIAG_BOOTSTRAP_v1',
25
+ };
26
+
27
+ /** The neutral header the hub connection carries the protocol tag in (an earlier product keeps its own). */
28
+ export const NEUTRAL_PROTOCOL_HEADER = 'X-G9-Protocol';
29
+
30
+ /** The protocol major a client of this package speaks (ProtocolVersion.CurrentMajor). */
31
+ export const PROTOCOL_MAJOR = 1;
32
+
33
+ const ascii = (s: string): boolean => s.length > 0 && /^[\x21-\x7e]+$/.test(s);
34
+
35
+ /** Throws when a value cannot work on the wire (the .NET DiagnosticWireProfile.Validate, rule for rule). */
36
+ export function validateWire(p: DiagnosticWireProfile): void {
37
+ if (!ascii(p.protocolTag) || p.protocolTag.length < 8 || p.protocolTag.length > 40) throw new Error('protocolTag: 8-40 printable ASCII characters.');
38
+ if (!ascii(p.deviceHubRoute) || p.deviceHubRoute.indexOf('/') >= 0) throw new Error('deviceHubRoute: printable ASCII, no slash.');
39
+ if (!ascii(p.backupMagic) || p.backupMagic.length !== 16) throw new Error('backupMagic: exactly 16 printable ASCII characters.');
40
+ if (!ascii(p.bootstrapKind)) throw new Error('bootstrapKind: printable ASCII.');
41
+ }
42
+
43
+ const same = (a: DiagnosticWireProfile, b: DiagnosticWireProfile): boolean =>
44
+ a.protocolTag === b.protocolTag && a.deviceHubRoute === b.deviceHubRoute && a.backupMagic === b.backupMagic && a.bootstrapKind === b.bootstrapKind;
45
+
46
+ let current: DiagnosticWireProfile = NEUTRAL_WIRE;
47
+ let set = false;
48
+
49
+ /** The profile in force: {@link NEUTRAL_WIRE} until {@link useWire} is called. */
50
+ export const currentWire = (): DiagnosticWireProfile => current;
51
+
52
+ /** Sets the profile, once, at startup. A second call with other values throws: a process speaks one profile. */
53
+ export function useWire(profile: DiagnosticWireProfile): void {
54
+ validateWire(profile);
55
+ if (set && !same(current, profile)) throw new Error('The diagnostic wire profile is already set to other values.');
56
+ current = { ...profile };
57
+ set = true;
58
+ }
59
+
60
+ /** Tests only: back to the neutral profile. */
61
+ export function resetWireForTests(): void {
62
+ current = NEUTRAL_WIRE;
63
+ set = false;
64
+ }
65
+
66
+ /** The device hub's URL for a gateway base address ("https://gw.example/" → "https://gw.example/device-hub"). */
67
+ export function hubUrlOf(gateway: string, profile: DiagnosticWireProfile = current): string {
68
+ return `${gateway.replace(/\/+$/, '')}/${profile.deviceHubRoute}`;
69
+ }
70
+
71
+ /** Device → gateway (DeviceHubMethods; the schema's x-methods). */
72
+ export const DeviceHubMethods = {
73
+ hello: 'Hello',
74
+ announcePresence: 'AnnouncePresence',
75
+ announceForeground: 'AnnounceForeground',
76
+ pong: 'Pong',
77
+ pushLogBatch: 'PushLogBatch',
78
+ pushScreenshot: 'PushScreenshot',
79
+ reportScreenshotError: 'ReportScreenshotError',
80
+ pushCpuSample: 'PushCpuSample',
81
+ pushSqlResult: 'PushSqlResult',
82
+ pushQaResult: 'PushQaResult',
83
+ pushLogFileList: 'PushLogFileList',
84
+ pushLogFileContent: 'PushLogFileContent',
85
+ pushSyncHealth: 'PushSyncHealth',
86
+ pushSyncCacheCleared: 'PushSyncCacheCleared',
87
+ pushSyncRunResult: 'PushSyncRunResult',
88
+ pushNfcWriteResult: 'PushNfcWriteResult',
89
+ pushRestoreResult: 'PushRestoreResult',
90
+ pushRestoreReady: 'PushRestoreReady',
91
+ backupUploadInit: 'BackupUploadInit',
92
+ backupUploadStream: 'BackupUploadStream',
93
+ backupUploadComplete: 'BackupUploadComplete',
94
+ } as const;
95
+
96
+ /** Gateway → device (IDeviceHubListeners; the schema's x-listeners). */
97
+ export const DeviceHubListeners = {
98
+ roleChallengeIssued: 'OnRoleChallengeIssuedAsync',
99
+ peerConnected: 'OnPeerConnectedAsync',
100
+ peerDisconnected: 'OnPeerDisconnectedAsync',
101
+ sealedFromPeer: 'OnSealedFromPeerAsync',
102
+ expandOverlay: 'OnExpandOverlayRequestAsync',
103
+ uploadProgress: 'OnUploadProgressAsync',
104
+ downloadProgress: 'OnDownloadProgressAsync',
105
+ screenshotRequest: 'OnScreenshotRequestAsync',
106
+ backupRequest: 'OnBackupRequestAsync',
107
+ backupCancelled: 'OnBackupCancelledAsync',
108
+ sqlRequest: 'OnSqlRequestAsync',
109
+ logFileListRequest: 'OnLogFileListRequestAsync',
110
+ logFileReadRequest: 'OnLogFileReadRequestAsync',
111
+ ping: 'OnPingAsync',
112
+ restoreBegin: 'OnRestoreBeginAsync',
113
+ restoreResume: 'OnRestoreResumeAsync',
114
+ restoreChunk: 'OnRestoreChunkAsync',
115
+ restoreComplete: 'OnRestoreCompleteAsync',
116
+ remoteInput: 'OnRemoteInputAsync',
117
+ syncHealthRequest: 'OnSyncHealthRequestAsync',
118
+ clearSyncCacheRequest: 'OnClearSyncCacheRequestAsync',
119
+ runSyncRequest: 'OnRunSyncRequestAsync',
120
+ nfcWriteRequest: 'OnNfcWriteRequestAsync',
121
+ qaCommand: 'OnQaCommandAsync',
122
+ deviceSettingsChanged: 'OnDeviceSettingsChangedAsync',
123
+ } as const;
124
+
125
+ /**
126
+ * What this client build serves (DeviceCapabilities.Current). The contract: absent = the client predates the tag = not
127
+ * capable, so a request it cannot answer fails fast at the gateway instead of timing out.
128
+ */
129
+ export const DeviceCapabilities = { logFiles: 'logfiles' } as const;
130
+ export const CURRENT_CAPABILITIES: readonly string[] = [DeviceCapabilities.logFiles];
131
+
132
+ /** The archive upload over the hub (x-transfer): 256 KiB per stream item, 4 MiB per stream call. */
133
+ export const TRANSFER = { chunkBytes: 256 * 1024, segmentBytes: 4 * 1024 * 1024, busyRetries: 6, busyDelayMs: 1500 } as const;
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.