@mentra/cloud-client 3.3.0-dev.775 → 3.3.0-dev.780

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mentra/cloud-client",
3
- "version": "3.3.0-dev.775",
3
+ "version": "3.3.0-dev.780",
4
4
  "type": "module",
5
5
  "main": "./src/index.ts",
6
6
  "exports": {
@@ -12,7 +12,7 @@
12
12
  "test": "bun test"
13
13
  },
14
14
  "dependencies": {
15
- "@mentra/cloud-protocol": "3.3.0-dev.775",
15
+ "@mentra/cloud-protocol": "3.3.0-dev.780",
16
16
  "tweetnacl": "^1.0.3"
17
17
  },
18
18
  "devDependencies": {
package/src/http.ts CHANGED
@@ -28,10 +28,12 @@ import type { HttpTransport } from "./transports";
28
28
  * `idempotent` marks a call as safe to retry on a transient network error. GET
29
29
  * is always treated as idempotent; the full-replace PUT opts in via this flag.
30
30
  * POST is never retried by default because it may not be safe to repeat.
31
+ * `signal` cancels the request, including a pending retry delay.
31
32
  */
32
33
  export interface ReqOpts {
33
34
  bearer?: string;
34
35
  idempotent?: boolean;
36
+ signal?: AbortSignal;
35
37
  }
36
38
 
37
39
  /** The REST surface the modules consume. */
@@ -79,6 +81,21 @@ function joinUrl(baseUrl: string, path: string): string {
79
81
  return `${base}/${suffix}`;
80
82
  }
81
83
 
84
+ function abortReason(signal: AbortSignal): unknown {
85
+ if (signal.reason !== undefined) return signal.reason;
86
+ const error = new Error("The request was aborted");
87
+ error.name = "AbortError";
88
+ return error;
89
+ }
90
+
91
+ function throwIfAborted(signal?: AbortSignal): void {
92
+ if (signal?.aborted) throw abortReason(signal);
93
+ }
94
+
95
+ function isAbortError(error: unknown): boolean {
96
+ return typeof error === "object" && error !== null && "name" in error && error.name === "AbortError";
97
+ }
98
+
82
99
  export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
83
100
  const { baseUrl, getToken, logger } = deps;
84
101
  const executeFetch = deps.fetch ?? globalThis.fetch;
@@ -90,11 +107,46 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
90
107
  * logs everywhere in this library.
91
108
  */
92
109
  async function resolveBearer(opts?: ReqOpts): Promise<string | undefined> {
110
+ throwIfAborted(opts?.signal);
93
111
  if (opts?.bearer) return opts.bearer;
94
- if (getToken) return await getToken();
112
+ if (getToken) {
113
+ const bearer = await getToken();
114
+ throwIfAborted(opts?.signal);
115
+ return bearer;
116
+ }
95
117
  return undefined;
96
118
  }
97
119
 
120
+ async function retryDelay(delayMs: number, signal?: AbortSignal): Promise<void> {
121
+ throwIfAborted(signal);
122
+ await new Promise<void>((resolve, reject) => {
123
+ let handle: unknown;
124
+ let timerCreated = false;
125
+ let settled = false;
126
+ const onAbort = () => {
127
+ if (settled) return;
128
+ settled = true;
129
+ signal?.removeEventListener("abort", onAbort);
130
+ if (timerCreated) timers.clearTimeout(handle);
131
+ reject(abortReason(signal!));
132
+ };
133
+ signal?.addEventListener("abort", onAbort, { once: true });
134
+ handle = timers.setTimeout(() => {
135
+ if (settled) return;
136
+ settled = true;
137
+ signal?.removeEventListener("abort", onAbort);
138
+ resolve();
139
+ }, delayMs);
140
+ timerCreated = true;
141
+ if (signal?.aborted) {
142
+ // An injected scheduler can run synchronously before returning its handle.
143
+ if (settled) timers.clearTimeout(handle);
144
+ else onAbort();
145
+ }
146
+ });
147
+ throwIfAborted(signal);
148
+ }
149
+
98
150
  /**
99
151
  * The one retry loop behind every request shape (JSON, form, bodyless).
100
152
  *
@@ -112,21 +164,27 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
112
164
  headers: Record<string, string>;
113
165
  body: string | FormData | undefined;
114
166
  idempotent: boolean;
167
+ signal?: AbortSignal;
115
168
  }): Promise<Response> {
116
- const { method, path, headers, body, idempotent } = args;
169
+ const { method, path, headers, body, idempotent, signal } = args;
117
170
  const url = joinUrl(baseUrl, path);
118
171
 
119
172
  for (let attempt = 0; attempt <= (idempotent ? MAX_RETRIES : 0); attempt++) {
173
+ throwIfAborted(signal);
120
174
  if (attempt > 0) {
121
175
  const backoff = RETRY_BASE_MS * 2 ** (attempt - 1);
122
176
  logger.debug("http retrying request", { method, path, attempt });
123
- await new Promise<void>((resolve) => timers.setTimeout(resolve, backoff));
177
+ await retryDelay(backoff, signal);
124
178
  }
125
179
 
126
180
  let res: Response;
127
181
  try {
128
- res = await executeFetch(url, { method, headers, body });
129
- } catch {
182
+ throwIfAborted(signal);
183
+ res = await executeFetch(url, { method, headers, body, signal });
184
+ throwIfAborted(signal);
185
+ } catch (error) {
186
+ throwIfAborted(signal);
187
+ if (isAbortError(error)) throw error;
130
188
  // Transient network failure: let the loop retry.
131
189
  logger.warn("http network error", { method, path, attempt });
132
190
  continue;
@@ -134,7 +192,7 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
134
192
 
135
193
  if (!res.ok) {
136
194
  // Definite answer from the server: map to a typed error, no retry.
137
- throw await toHttpError(res, method, path);
195
+ throw await toHttpError(res, method, path, signal);
138
196
  }
139
197
 
140
198
  return res;
@@ -151,6 +209,7 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
151
209
  opts?: ReqOpts,
152
210
  ): Promise<Response> {
153
211
  const bearer = await resolveBearer(opts);
212
+ throwIfAborted(opts?.signal);
154
213
 
155
214
  const headers: Record<string, string> = {};
156
215
  if (bearer) headers["Authorization"] = `Bearer ${bearer}`;
@@ -165,7 +224,7 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
165
224
  // verbs opt in via the flag.
166
225
  const idempotent = opts?.idempotent ?? (method === "GET" || method === "DELETE" || method === "HEAD");
167
226
 
168
- return await fetchWithRetry({ method, path, headers, body: payload, idempotent });
227
+ return await fetchWithRetry({ method, path, headers, body: payload, idempotent, signal: opts?.signal });
169
228
  }
170
229
 
171
230
  async function request<T>(
@@ -175,11 +234,12 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
175
234
  opts?: ReqOpts,
176
235
  ): Promise<T> {
177
236
  const res = await requestRaw(method, path, body, opts);
178
- return await parseJson<T>(res);
237
+ return await parseJson<T>(res, opts?.signal);
179
238
  }
180
239
 
181
240
  async function requestForm<T>(path: string, form: FormData, opts?: ReqOpts): Promise<T> {
182
241
  const bearer = await resolveBearer(opts);
242
+ throwIfAborted(opts?.signal);
183
243
 
184
244
  // No Content-Type here: fetch/FormData must generate the multipart
185
245
  // boundary. POST is not idempotent, so retries stay opt-in.
@@ -192,8 +252,9 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
192
252
  headers,
193
253
  body: form,
194
254
  idempotent: opts?.idempotent ?? false,
255
+ signal: opts?.signal,
195
256
  });
196
- return await parseJson<T>(res);
257
+ return await parseJson<T>(res, opts?.signal);
197
258
  }
198
259
 
199
260
  /**
@@ -202,7 +263,8 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
202
263
  * parse failure here because the status is the load-bearing signal and we do
203
264
  * not want a malformed error body to mask the real status.
204
265
  */
205
- async function toHttpError(res: Response, method: string, path: string): Promise<HttpError> {
266
+ async function toHttpError(res: Response, method: string, path: string, signal?: AbortSignal): Promise<HttpError> {
267
+ throwIfAborted(signal);
206
268
  let code: string | undefined;
207
269
  let detail = "";
208
270
  try {
@@ -212,12 +274,16 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
212
274
  error?: string;
213
275
  error_description?: string;
214
276
  };
277
+ throwIfAborted(signal);
215
278
  code = data?.code ?? data?.error;
216
279
  const message = data?.message ?? data?.error_description;
217
280
  detail = message ? `: ${message}` : "";
218
- } catch {
281
+ } catch (error) {
282
+ throwIfAborted(signal);
283
+ if (isAbortError(error)) throw error;
219
284
  // No JSON body, or unparseable: fall back to status alone.
220
285
  }
286
+ throwIfAborted(signal);
221
287
  return new HttpError(`HTTP ${res.status} on ${method} ${path}${detail}`, res.status, code);
222
288
  }
223
289
 
@@ -225,10 +291,14 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
225
291
  * Parse a successful response as JSON, tolerating an empty body (a 204 or an
226
292
  * endpoint that returns nothing) by resolving to `undefined`.
227
293
  */
228
- async function parseJson<T>(res: Response): Promise<T> {
294
+ async function parseJson<T>(res: Response, signal?: AbortSignal): Promise<T> {
295
+ throwIfAborted(signal);
229
296
  const text = await res.text();
297
+ throwIfAborted(signal);
230
298
  if (text.length === 0) return undefined as T;
231
- return JSON.parse(text) as T;
299
+ const result = JSON.parse(text) as T;
300
+ throwIfAborted(signal);
301
+ return result;
232
302
  }
233
303
 
234
304
  return {
package/src/index.ts CHANGED
@@ -71,6 +71,8 @@ export type {
71
71
  ReportKind,
72
72
  ReportLogEntry,
73
73
  ReportLogCollectionUpdate,
74
+ ReportLogCollection,
75
+ ReportLogCollectionSnapshot,
74
76
  ReportLogSource,
75
77
  ReportStatus,
76
78
  ReportSystemPriority,
@@ -23,6 +23,7 @@ import {
23
23
  type ReportAttachmentInput,
24
24
  type ReportLogEntry,
25
25
  type ReportLogCollectionUpdate,
26
+ type ReportLogCollectionSnapshot,
26
27
  type ReportLogSource,
27
28
  type ReportStatus,
28
29
  type SubmitReportInput,
@@ -42,6 +43,8 @@ export type {
42
43
  ReportKind,
43
44
  ReportLogEntry,
44
45
  ReportLogCollectionUpdate,
46
+ ReportLogCollection,
47
+ ReportLogCollectionSnapshot,
45
48
  ReportLogSource,
46
49
  ReportStatus,
47
50
  ReportSystemPriority,
@@ -147,6 +150,7 @@ export class Core {
147
150
  getRegistry(opts?: { environment?: string }): Promise<PreinstalledMiniappRegistry>;
148
151
  };
149
152
  readonly reports: {
153
+ getLogCollection(reportId: string, signal?: AbortSignal): Promise<ReportLogCollectionSnapshot>;
150
154
  submit(input: SubmitReportInput): Promise<SubmitReportResult>;
151
155
  updateLogCollection(
152
156
  reportId: string,
@@ -222,6 +226,7 @@ export class Core {
222
226
  };
223
227
  this.reports = {
224
228
  submit: reports.submit.bind(reports),
229
+ getLogCollection: reports.getLogCollection.bind(reports),
225
230
  updateLogCollection: reports.updateLogCollection.bind(reports),
226
231
  addLogs: reports.addLogs.bind(reports),
227
232
  addScreenshots: reports.addScreenshots.bind(reports),
@@ -13,6 +13,20 @@ const REPORTS_PATH = "/api/client/reports";
13
13
  export type ReportKind = "bug" | "feedback" | "automatic";
14
14
  export type ReportStatus = "collecting" | "ready" | "closed";
15
15
  export type ReportLogSource = "phone" | "glasses" | "glasses_firmware" | "cloud" | "miniapp_server";
16
+ /** Core storage receipts, independent of the report's UI readiness status. */
17
+ export interface ReportLogCollection {
18
+ state: "requested" | "received" | "unavailable" | "failed" | "timed-out";
19
+ requestedAt: string;
20
+ deadlineAt: string;
21
+ reason?: string;
22
+ receivedAt?: string;
23
+ artifactId?: string;
24
+ entryCount?: number;
25
+ }
26
+ export interface ReportLogCollectionSnapshot {
27
+ reportId: string;
28
+ logCollection: Partial<Record<ReportLogSource, ReportLogCollection>>;
29
+ }
16
30
  export interface ReportLogCollectionUpdate {
17
31
  state: "requested" | "unavailable" | "failed";
18
32
  reason?: string;
@@ -104,6 +118,37 @@ export class Reports {
104
118
  return this.http.post<SubmitReportResult>(REPORTS_PATH, input);
105
119
  }
106
120
 
121
+ /** Read the current source receipts with the same user session used to submit. */
122
+ async getLogCollection(reportId: string, signal?: AbortSignal): Promise<ReportLogCollectionSnapshot> {
123
+ const snapshot = await this.http.get<ReportLogCollectionSnapshot>(
124
+ `${REPORTS_PATH}/${encodeURIComponent(reportId)}/log-collection`,
125
+ {signal},
126
+ );
127
+ if (!snapshot || snapshot.reportId !== reportId || !snapshot.logCollection ||
128
+ typeof snapshot.logCollection !== "object" || Array.isArray(snapshot.logCollection)) {
129
+ throw new Error("Invalid report collection response");
130
+ }
131
+ const logCollection: ReportLogCollectionSnapshot["logCollection"] = {};
132
+ for (const source of ["phone", "glasses", "glasses_firmware", "cloud", "miniapp_server"] as const) {
133
+ const receipt = snapshot.logCollection[source];
134
+ if (receipt === undefined) continue;
135
+ if (!receipt || !["requested", "received", "unavailable", "failed", "timed-out"].includes(receipt.state) ||
136
+ typeof receipt.requestedAt !== "string" || typeof receipt.deadlineAt !== "string") {
137
+ throw new Error("Invalid report collection receipt");
138
+ }
139
+ logCollection[source] = {
140
+ state: receipt.state,
141
+ requestedAt: receipt.requestedAt,
142
+ deadlineAt: receipt.deadlineAt,
143
+ ...(typeof receipt.reason === "string" ? {reason: receipt.reason.slice(0, 500)} : {}),
144
+ ...(typeof receipt.receivedAt === "string" ? {receivedAt: receipt.receivedAt} : {}),
145
+ ...(typeof receipt.artifactId === "string" ? {artifactId: receipt.artifactId} : {}),
146
+ ...(typeof receipt.entryCount === "number" ? {entryCount: receipt.entryCount} : {}),
147
+ };
148
+ }
149
+ return {reportId: snapshot.reportId, logCollection};
150
+ }
151
+
107
152
  /** Record a local collection attempt; only Core artifact storage confirms receipt. */
108
153
  updateLogCollection(
109
154
  reportId: string,