@mentra/cloud-client 3.2.1 → 3.3.0-beta.1001

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/node/index.ts CHANGED
@@ -50,5 +50,7 @@ export {
50
50
  CloudClientError,
51
51
  HttpError,
52
52
  AuthExpiredError,
53
+ AuthUnavailableError,
54
+ SessionRevocationError,
53
55
  noopLogger,
54
56
  } from "@mentra/cloud-client";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mentra/cloud-client",
3
- "version": "3.2.1",
3
+ "version": "3.3.0-beta.1001",
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.2.1",
15
+ "@mentra/cloud-protocol": "3.3.0-beta.1001",
16
16
  "tweetnacl": "^1.0.3"
17
17
  },
18
18
  "devDependencies": {
package/src/client.ts CHANGED
@@ -216,6 +216,7 @@ export class CloudClient {
216
216
  audio: {
217
217
  codec: config.audio?.codec ?? DEFAULT_AUDIO_CODEC,
218
218
  sampleRate: config.audio?.sampleRate ?? DEFAULT_AUDIO_SAMPLE_RATE,
219
+ frameTimelineVersion: 1,
219
220
  // Only LC3 carries a frame size; the config type forces LC3 hosts to
220
221
  // state theirs explicitly (decoder is sized from this — no safe guess).
221
222
  ...(config.audio?.codec === "lc3" ? {frameSizeBytes: config.audio.frameSizeBytes} : {}),
@@ -239,7 +240,14 @@ export class CloudClient {
239
240
  const camera = new Camera({http: runtimeHttp, timers})
240
241
  const tts = new Tts({http: runtimeHttp})
241
242
  const maps = new Maps({http: runtimeHttp})
242
- const audio = new UdpAudio({udp: config.transports.udp})
243
+ const audio = new UdpAudio({
244
+ udp: config.transports.udp,
245
+ audio: {
246
+ codec: config.audio?.codec ?? DEFAULT_AUDIO_CODEC,
247
+ sampleRate: config.audio?.sampleRate ?? DEFAULT_AUDIO_SAMPLE_RATE,
248
+ ...(config.audio?.codec === "lc3" ? {frameSizeBytes: config.audio.frameSizeBytes} : {}),
249
+ },
250
+ })
243
251
 
244
252
  const runtime = new Runtime({
245
253
  connection,
package/src/errors.ts CHANGED
@@ -25,17 +25,20 @@ export class CloudClientError extends Error {
25
25
  * `status` is the HTTP status so a caller can branch (for example a 401 triggers
26
26
  * one refresh-and-retry). `code` is the optional machine-readable error code the
27
27
  * cloud puts in the JSON body, when present, for finer branching than status
28
- * alone allows.
28
+ * alone allows. `retryAfterSeconds` is the server's `Retry-After` delay in whole
29
+ * seconds, set only when the response carried the delta-seconds form.
29
30
  */
30
31
  export class HttpError extends CloudClientError {
31
32
  status!: number;
32
33
  code?: string;
34
+ retryAfterSeconds?: number;
33
35
 
34
- constructor(message: string, status: number, code?: string) {
36
+ constructor(message: string, status: number, code?: string, retryAfterSeconds?: number) {
35
37
  super(message);
36
38
  this.name = "HttpError";
37
39
  this.status = status;
38
40
  this.code = code;
41
+ this.retryAfterSeconds = retryAfterSeconds;
39
42
  Object.setPrototypeOf(this, new.target.prototype);
40
43
  }
41
44
  }
@@ -70,3 +73,25 @@ export class AuthExpiredError extends CloudClientError {
70
73
  Object.setPrototypeOf(this, new.target.prototype);
71
74
  }
72
75
  }
76
+
77
+ /**
78
+ * Thrown when a credential request could not be completed for a reason that does
79
+ * not show the credentials are dead: the network failed or timed out, Core
80
+ * answered 408, 429 or 5xx, or the answer was not a Core answer at all (a body
81
+ * that is not JSON, an unrecognized 4xx). The stored credentials were kept, so
82
+ * the same call may well succeed later; a host retries instead of re-authenticating,
83
+ * and `onExpired` does not fire. `status` is the HTTP status when something
84
+ * answered, and `cause` is the underlying failure.
85
+ */
86
+ export class AuthUnavailableError extends CloudClientError {
87
+ readonly status?: number;
88
+ readonly cause: unknown;
89
+
90
+ constructor(message: string, options?: { status?: number; cause?: unknown }) {
91
+ super(message);
92
+ this.name = "AuthUnavailableError";
93
+ this.status = options?.status;
94
+ this.cause = options?.cause;
95
+ Object.setPrototypeOf(this, new.target.prototype);
96
+ }
97
+ }
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. */
@@ -67,6 +69,25 @@ const MAX_RETRIES = 2;
67
69
  /** Base backoff in milliseconds; doubles per attempt (250, 500, ...). */
68
70
  const RETRY_BASE_MS = 250;
69
71
 
72
+ /** Recognize only fixed native categories; never log an exception message, stack or arbitrary code. */
73
+ function nativeFailureCode(error: unknown): string | undefined {
74
+ if (typeof error !== "object" || error === null || !("code" in error)) return undefined;
75
+ const code = error.code;
76
+ return typeof code === "string" &&
77
+ [
78
+ "E_NATIVE_HTTP_DNS",
79
+ "E_NATIVE_HTTP_CONNECT",
80
+ "E_NATIVE_HTTP_TIMEOUT",
81
+ "E_NATIVE_HTTP_TLS",
82
+ "E_NATIVE_HTTP_SOCKET",
83
+ "E_NATIVE_HTTP_INTERRUPTED",
84
+ "E_NATIVE_HTTP_IO",
85
+ "E_NATIVE_HTTP_OTHER",
86
+ ].includes(code)
87
+ ? code
88
+ : undefined;
89
+ }
90
+
70
91
  /**
71
92
  * Join a base URL and a path without producing a double slash or dropping one.
72
93
  *
@@ -79,6 +100,34 @@ function joinUrl(baseUrl: string, path: string): string {
79
100
  return `${base}/${suffix}`;
80
101
  }
81
102
 
103
+ function abortReason(signal: AbortSignal): unknown {
104
+ if (signal.reason !== undefined) return signal.reason;
105
+ const error = new Error("The request was aborted");
106
+ error.name = "AbortError";
107
+ return error;
108
+ }
109
+
110
+ function throwIfAborted(signal?: AbortSignal): void {
111
+ if (signal?.aborted) throw abortReason(signal);
112
+ }
113
+
114
+ function isAbortError(error: unknown): boolean {
115
+ return typeof error === "object" && error !== null && "name" in error && error.name === "AbortError";
116
+ }
117
+
118
+ /**
119
+ * Read a `Retry-After` header in its delta-seconds form (a non-negative whole
120
+ * number of seconds). The HTTP-date form, signs, fractions, exponents and any
121
+ * other text are ignored: a caller that wants a delay gets a number or nothing,
122
+ * never a guess. A value too large to be an exact integer is also ignored.
123
+ */
124
+ function parseRetryAfterSeconds(headers: Headers | undefined): number | undefined {
125
+ const raw = headers?.get("Retry-After")?.trim();
126
+ if (!raw || !/^\d+$/.test(raw)) return undefined;
127
+ const seconds = Number(raw);
128
+ return Number.isSafeInteger(seconds) ? seconds : undefined;
129
+ }
130
+
82
131
  export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
83
132
  const { baseUrl, getToken, logger } = deps;
84
133
  const executeFetch = deps.fetch ?? globalThis.fetch;
@@ -90,11 +139,46 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
90
139
  * logs everywhere in this library.
91
140
  */
92
141
  async function resolveBearer(opts?: ReqOpts): Promise<string | undefined> {
142
+ throwIfAborted(opts?.signal);
93
143
  if (opts?.bearer) return opts.bearer;
94
- if (getToken) return await getToken();
144
+ if (getToken) {
145
+ const bearer = await getToken();
146
+ throwIfAborted(opts?.signal);
147
+ return bearer;
148
+ }
95
149
  return undefined;
96
150
  }
97
151
 
152
+ async function retryDelay(delayMs: number, signal?: AbortSignal): Promise<void> {
153
+ throwIfAborted(signal);
154
+ await new Promise<void>((resolve, reject) => {
155
+ let handle: unknown;
156
+ let timerCreated = false;
157
+ let settled = false;
158
+ const onAbort = () => {
159
+ if (settled) return;
160
+ settled = true;
161
+ signal?.removeEventListener("abort", onAbort);
162
+ if (timerCreated) timers.clearTimeout(handle);
163
+ reject(abortReason(signal!));
164
+ };
165
+ signal?.addEventListener("abort", onAbort, { once: true });
166
+ handle = timers.setTimeout(() => {
167
+ if (settled) return;
168
+ settled = true;
169
+ signal?.removeEventListener("abort", onAbort);
170
+ resolve();
171
+ }, delayMs);
172
+ timerCreated = true;
173
+ if (signal?.aborted) {
174
+ // An injected scheduler can run synchronously before returning its handle.
175
+ if (settled) timers.clearTimeout(handle);
176
+ else onAbort();
177
+ }
178
+ });
179
+ throwIfAborted(signal);
180
+ }
181
+
98
182
  /**
99
183
  * The one retry loop behind every request shape (JSON, form, bodyless).
100
184
  *
@@ -112,29 +196,36 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
112
196
  headers: Record<string, string>;
113
197
  body: string | FormData | undefined;
114
198
  idempotent: boolean;
199
+ signal?: AbortSignal;
115
200
  }): Promise<Response> {
116
- const { method, path, headers, body, idempotent } = args;
201
+ const { method, path, headers, body, idempotent, signal } = args;
117
202
  const url = joinUrl(baseUrl, path);
118
203
 
119
204
  for (let attempt = 0; attempt <= (idempotent ? MAX_RETRIES : 0); attempt++) {
205
+ throwIfAborted(signal);
120
206
  if (attempt > 0) {
121
207
  const backoff = RETRY_BASE_MS * 2 ** (attempt - 1);
122
208
  logger.debug("http retrying request", { method, path, attempt });
123
- await new Promise<void>((resolve) => timers.setTimeout(resolve, backoff));
209
+ await retryDelay(backoff, signal);
124
210
  }
125
211
 
126
212
  let res: Response;
127
213
  try {
128
- res = await executeFetch(url, { method, headers, body });
129
- } catch {
214
+ throwIfAborted(signal);
215
+ res = await executeFetch(url, { method, headers, body, signal });
216
+ throwIfAborted(signal);
217
+ } catch (error) {
218
+ throwIfAborted(signal);
219
+ if (isAbortError(error)) throw error;
130
220
  // Transient network failure: let the loop retry.
131
- logger.warn("http network error", { method, path, attempt });
221
+ const nativeCode = nativeFailureCode(error);
222
+ logger.warn("http network error", { method, path, attempt, ...(nativeCode ? { nativeCode } : {}) });
132
223
  continue;
133
224
  }
134
225
 
135
226
  if (!res.ok) {
136
227
  // Definite answer from the server: map to a typed error, no retry.
137
- throw await toHttpError(res, method, path);
228
+ throw await toHttpError(res, method, path, signal);
138
229
  }
139
230
 
140
231
  return res;
@@ -151,6 +242,7 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
151
242
  opts?: ReqOpts,
152
243
  ): Promise<Response> {
153
244
  const bearer = await resolveBearer(opts);
245
+ throwIfAborted(opts?.signal);
154
246
 
155
247
  const headers: Record<string, string> = {};
156
248
  if (bearer) headers["Authorization"] = `Bearer ${bearer}`;
@@ -165,7 +257,7 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
165
257
  // verbs opt in via the flag.
166
258
  const idempotent = opts?.idempotent ?? (method === "GET" || method === "DELETE" || method === "HEAD");
167
259
 
168
- return await fetchWithRetry({ method, path, headers, body: payload, idempotent });
260
+ return await fetchWithRetry({ method, path, headers, body: payload, idempotent, signal: opts?.signal });
169
261
  }
170
262
 
171
263
  async function request<T>(
@@ -175,11 +267,12 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
175
267
  opts?: ReqOpts,
176
268
  ): Promise<T> {
177
269
  const res = await requestRaw(method, path, body, opts);
178
- return await parseJson<T>(res);
270
+ return await parseJson<T>(res, opts?.signal);
179
271
  }
180
272
 
181
273
  async function requestForm<T>(path: string, form: FormData, opts?: ReqOpts): Promise<T> {
182
274
  const bearer = await resolveBearer(opts);
275
+ throwIfAborted(opts?.signal);
183
276
 
184
277
  // No Content-Type here: fetch/FormData must generate the multipart
185
278
  // boundary. POST is not idempotent, so retries stay opt-in.
@@ -192,8 +285,9 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
192
285
  headers,
193
286
  body: form,
194
287
  idempotent: opts?.idempotent ?? false,
288
+ signal: opts?.signal,
195
289
  });
196
- return await parseJson<T>(res);
290
+ return await parseJson<T>(res, opts?.signal);
197
291
  }
198
292
 
199
293
  /**
@@ -202,7 +296,8 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
202
296
  * parse failure here because the status is the load-bearing signal and we do
203
297
  * not want a malformed error body to mask the real status.
204
298
  */
205
- async function toHttpError(res: Response, method: string, path: string): Promise<HttpError> {
299
+ async function toHttpError(res: Response, method: string, path: string, signal?: AbortSignal): Promise<HttpError> {
300
+ throwIfAborted(signal);
206
301
  let code: string | undefined;
207
302
  let detail = "";
208
303
  try {
@@ -212,23 +307,36 @@ export function createHttpClient(deps: CreateHttpClientDeps): HttpClient {
212
307
  error?: string;
213
308
  error_description?: string;
214
309
  };
310
+ throwIfAborted(signal);
215
311
  code = data?.code ?? data?.error;
216
312
  const message = data?.message ?? data?.error_description;
217
313
  detail = message ? `: ${message}` : "";
218
- } catch {
314
+ } catch (error) {
315
+ throwIfAborted(signal);
316
+ if (isAbortError(error)) throw error;
219
317
  // No JSON body, or unparseable: fall back to status alone.
220
318
  }
221
- return new HttpError(`HTTP ${res.status} on ${method} ${path}${detail}`, res.status, code);
319
+ throwIfAborted(signal);
320
+ return new HttpError(
321
+ `HTTP ${res.status} on ${method} ${path}${detail}`,
322
+ res.status,
323
+ code,
324
+ parseRetryAfterSeconds(res.headers),
325
+ );
222
326
  }
223
327
 
224
328
  /**
225
329
  * Parse a successful response as JSON, tolerating an empty body (a 204 or an
226
330
  * endpoint that returns nothing) by resolving to `undefined`.
227
331
  */
228
- async function parseJson<T>(res: Response): Promise<T> {
332
+ async function parseJson<T>(res: Response, signal?: AbortSignal): Promise<T> {
333
+ throwIfAborted(signal);
229
334
  const text = await res.text();
335
+ throwIfAborted(signal);
230
336
  if (text.length === 0) return undefined as T;
231
- return JSON.parse(text) as T;
337
+ const result = JSON.parse(text) as T;
338
+ throwIfAborted(signal);
339
+ return result;
232
340
  }
233
341
 
234
342
  return {
package/src/index.ts CHANGED
@@ -41,20 +41,19 @@ export {
41
41
  CloudClientError,
42
42
  HttpError,
43
43
  AuthExpiredError,
44
+ AuthUnavailableError,
44
45
  SessionRevocationError,
45
46
  } from "./errors";
46
47
 
48
+ // Reads a Core token's claims (`sub` is the Mentra user ID) without verifying it; the cloud verifies every call.
49
+ export { decodeClaims } from "./modules/auth/jwt";
50
+ export type { JwtClaims } from "./modules/auth/jwt";
51
+
47
52
  // The logging hook a host can implement to route library logs.
48
53
  export { noopLogger } from "./logger";
49
54
  export type { Logger } from "./logger";
50
55
 
51
56
  // Runtime lifecycle state exposed to hosts for UI/debugging and fallback policy.
52
- export type {
53
- PreinstalledInstallPolicy,
54
- PreinstalledMiniappRegistry,
55
- PreinstalledMiniappRegistryEntry,
56
- } from "./modules/core/core";
57
-
58
57
  export type {
59
58
  RuntimeAudioTransport,
60
59
  RuntimeSnapshot,
@@ -65,11 +64,19 @@ export type {
65
64
 
66
65
  export type {
67
66
  AddReportArtifactsResult,
67
+ AddReportLogsOptions,
68
+ FleetAck,
69
+ FleetAckResult,
70
+ FleetReportOutcome,
68
71
  ReportAttachmentInput,
69
72
  ReportContext,
70
73
  ReportDetails,
71
74
  ReportKind,
72
75
  ReportLogEntry,
76
+ ReportLogCollectionUpdate,
77
+ ReportLogCollection,
78
+ ReportLogCollectionSnapshot,
79
+ ReportLogSource,
73
80
  ReportStatus,
74
81
  ReportSystemPriority,
75
82
  ReportTrigger,