@g9tm/app-diagnostic 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/upload.ts CHANGED
@@ -1,236 +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) });
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) });