@mentra/cloud-client 3.4.0-dev.1071 → 3.4.0-dev.1074

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
@@ -52,5 +52,8 @@ export {
52
52
  AuthExpiredError,
53
53
  AuthUnavailableError,
54
54
  SessionRevocationError,
55
+ CoreRequestError,
56
+ CoreResponseError,
57
+ SessionChangedError,
55
58
  noopLogger,
56
59
  } from "@mentra/cloud-client";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mentra/cloud-client",
3
- "version": "3.4.0-dev.1071",
3
+ "version": "3.4.0-dev.1074",
4
4
  "type": "module",
5
5
  "main": "./src/index.ts",
6
6
  "exports": {
@@ -12,10 +12,11 @@
12
12
  "test": "bun test"
13
13
  },
14
14
  "dependencies": {
15
- "@mentra/cloud-protocol": "3.4.0-dev.1071",
15
+ "@mentra/cloud-protocol": "3.4.0-dev.1074",
16
16
  "tweetnacl": "^1.0.3"
17
17
  },
18
18
  "devDependencies": {
19
+ "@mentra/workspace-contract": "workspace:*",
19
20
  "ws": "^8.18.0",
20
21
  "@types/ws": "^8.5.12"
21
22
  },
package/src/client.ts CHANGED
@@ -267,7 +267,7 @@ export class CloudClient {
267
267
  })
268
268
 
269
269
  // Core is last: stateless REST on the core service, Bearer from auth.
270
- const core = coreHttp ? new Core({http: coreHttp}) : undefined
270
+ const core = coreHttp ? new Core({http: coreHttp, auth}) : undefined
271
271
 
272
272
  this.auth = auth
273
273
  this.runtime = runtime
package/src/index.ts CHANGED
@@ -86,3 +86,17 @@ export type {
86
86
  SupportProfileUpdateResult,
87
87
  SupportStateInput,
88
88
  } from "./modules/core/core";
89
+
90
+ // Workspace and Fleet desired-state calls (`cloud.core.workspaces`, `cloud.core.fleet.desiredState`).
91
+ export {CoreRequestError, CoreResponseError, SessionChangedError} from "./modules/core/core";
92
+ export type {AccountCallOptions} from "./modules/core/core";
93
+ export type {
94
+ AcceptInvitationResult,
95
+ ClientWorkspaceRole,
96
+ DeclineInvitationResult,
97
+ InvitationPreview,
98
+ LeaveWorkspaceRequest,
99
+ MyWorkspace,
100
+ MyWorkspaceResponse,
101
+ PendingInvitationsResponse,
102
+ } from "./modules/core/workspace-types";
@@ -0,0 +1,203 @@
1
+ /**
2
+ * @fileoverview Core calls made as one account.
3
+ *
4
+ * A call here belongs to the account whose Core token it was sent with, and to no other. The runner:
5
+ *
6
+ * - gets the token and reads whose it is (`sub`), then sends that exact token as the request's bearer, so the
7
+ * request never reads the token source again and cannot pick up another account's token;
8
+ * - refuses to send when the caller named the account it expects and the token is someone else's;
9
+ * - after the answer (a good one or a failure), asks the token source whose session it holds now. When that is not
10
+ * the account the request was sent for, the answer is discarded as `SessionChangedError`: a switch or sign-out
11
+ * during the request must not hand A's data to a screen that now speaks for B;
12
+ * - on a 401, refreshes the token once, and sends again only when the refreshed token is still the same account's.
13
+ * A second 401 is an error.
14
+ *
15
+ * Every failure of a Core answer is a `CoreRequestError` that keeps the HTTP status and Core's error code. Its message
16
+ * is fixed text built from the status; Core's own wording (`error_description`) never reaches it, because a screen
17
+ * may show the message and the app has its own words for each code.
18
+ */
19
+ import {AuthExpiredError, CloudClientError, HttpError} from "../../errors"
20
+ import {decodeClaims} from "../auth/jwt"
21
+
22
+ /** Core's error codes are short snake_case words; anything else is not safe to surface or branch on. */
23
+ const ERROR_CODE_PATTERN = /^[a-z][a-z0-9_]{0,63}$/
24
+
25
+ /** The part of `cloud.auth` the runner needs. */
26
+ export interface CoreTokenSource {
27
+ getCoreToken(opts?: {forceRefresh?: boolean}): Promise<string>
28
+ }
29
+
30
+ /** Per-call options. */
31
+ export interface AccountCallOptions {
32
+ signal?: AbortSignal
33
+ /**
34
+ * The Mentra user ID the caller is acting for. When the client holds another account's token the call is refused
35
+ * with `SessionChangedError` before anything is sent.
36
+ */
37
+ expectedAccount?: string
38
+ }
39
+
40
+ /** A Core answer that was not a success. `status` is 0 when nothing answered. */
41
+ export class CoreRequestError extends CloudClientError {
42
+ readonly status: number
43
+ /** Core's error code when it gave a well-formed one; `network_error` when nothing answered. */
44
+ readonly code?: string
45
+ readonly retryAfterSeconds?: number
46
+
47
+ constructor(status: number, code?: string, retryAfterSeconds?: number) {
48
+ super(status === 0 ? "Core request failed: no answer" : `Core request failed (HTTP ${status})`)
49
+ this.name = "CoreRequestError"
50
+ this.status = status
51
+ this.code = code
52
+ this.retryAfterSeconds = retryAfterSeconds
53
+ Object.setPrototypeOf(this, new.target.prototype)
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Core answered 2xx, but not with what this client can use: no body, a body of another shape, or (for desired state)
59
+ * a status this client does not know. Never read as an empty or `unmanaged` answer.
60
+ */
61
+ export class CoreResponseError extends CloudClientError {
62
+ readonly reason: "invalid_shape" | "unknown_status"
63
+
64
+ constructor(reason: "invalid_shape" | "unknown_status") {
65
+ super(`Core's answer was not usable (${reason})`)
66
+ this.name = "CoreResponseError"
67
+ this.reason = reason
68
+ Object.setPrototypeOf(this, new.target.prototype)
69
+ }
70
+ }
71
+
72
+ /**
73
+ * The client no longer holds the session the call was made for (another account signed in, or the session ended),
74
+ * so nothing was sent or the answer was dropped. The caller discards it and follows the new session.
75
+ */
76
+ export class SessionChangedError extends CloudClientError {
77
+ readonly reason: "other_account" | "signed_out" | "unreadable_token"
78
+
79
+ constructor(reason: "other_account" | "signed_out" | "unreadable_token") {
80
+ super(`The signed-in account changed during the request (${reason})`)
81
+ this.name = "SessionChangedError"
82
+ this.reason = reason
83
+ Object.setPrototypeOf(this, new.target.prototype)
84
+ }
85
+ }
86
+
87
+ function isAbortError(error: unknown): boolean {
88
+ return typeof error === "object" && error !== null && "name" in error && error.name === "AbortError"
89
+ }
90
+
91
+ function abortReason(signal: AbortSignal): unknown {
92
+ if (signal.reason !== undefined) return signal.reason
93
+ const error = new Error("The request was aborted")
94
+ error.name = "AbortError"
95
+ return error
96
+ }
97
+
98
+ /** The account a Core token belongs to (its `sub`), or null when the token is not readable. */
99
+ function accountOf(token: string): string | null {
100
+ try {
101
+ const sub = decodeClaims(token).sub
102
+ return typeof sub === "string" && sub ? sub : null
103
+ } catch {
104
+ return null
105
+ }
106
+ }
107
+
108
+ function toRequestError(error: HttpError): CoreRequestError {
109
+ const code =
110
+ error.status === 0
111
+ ? "network_error"
112
+ : typeof error.code === "string" && ERROR_CODE_PATTERN.test(error.code)
113
+ ? error.code
114
+ : undefined
115
+ return new CoreRequestError(error.status, code, error.retryAfterSeconds)
116
+ }
117
+
118
+ /** Runs requests as one account. See the file comment. */
119
+ export class AccountCaller {
120
+ constructor(private readonly auth: CoreTokenSource | undefined) {}
121
+
122
+ /**
123
+ * Sends one request with the current account's token. `send` receives the bearer to use and must use exactly it.
124
+ * Rejects with `CoreRequestError` for a Core answer that is not a success, `SessionChangedError` when the account
125
+ * changed, the auth errors from the token source (`AuthExpiredError`, `AuthUnavailableError`) as they are, and the
126
+ * caller's abort reason when `opts.signal` is aborted.
127
+ */
128
+ async run<T>(send: (bearer: string) => Promise<T>, opts: AccountCallOptions = {}): Promise<T> {
129
+ const auth = this.auth
130
+ if (!auth) throw new CloudClientError("This client has no Core sign-in; workspace and Fleet calls need one")
131
+ const {signal} = opts
132
+
133
+ const first = await this.tokenFor(auth, false, signal)
134
+ const account = first.account
135
+ if (opts.expectedAccount !== undefined && opts.expectedAccount !== account) {
136
+ throw new SessionChangedError("other_account")
137
+ }
138
+
139
+ let token = first.token
140
+ for (let attempt = 0; ; attempt++) {
141
+ let result: T
142
+ try {
143
+ result = await send(token)
144
+ } catch (error) {
145
+ if (signal?.aborted) throw abortReason(signal)
146
+ if (isAbortError(error)) throw error
147
+ if (!(error instanceof HttpError)) {
148
+ // Not a Core answer: a 2xx body that is not JSON, or a connection that dropped while the body was read.
149
+ await this.assertStill(auth, account, signal)
150
+ if (error instanceof CloudClientError) throw error
151
+ throw error instanceof SyntaxError
152
+ ? new CoreResponseError("invalid_shape")
153
+ : new CoreRequestError(0, "network_error")
154
+ }
155
+ // Whatever Core answered, it answered A: if the session is not A's any more, nobody here wants the answer,
156
+ // and a 401 must not trigger a refresh of someone else's session.
157
+ await this.assertStill(auth, account, signal)
158
+ if (error.status === 401 && attempt === 0) {
159
+ const refreshed = await this.tokenFor(auth, true, signal)
160
+ if (refreshed.account !== account) throw new SessionChangedError("other_account")
161
+ token = refreshed.token
162
+ continue
163
+ }
164
+ throw toRequestError(error)
165
+ }
166
+ if (signal?.aborted) throw abortReason(signal)
167
+ await this.assertStill(auth, account, signal)
168
+ return result
169
+ }
170
+ }
171
+
172
+ private async tokenFor(
173
+ auth: CoreTokenSource,
174
+ forceRefresh: boolean,
175
+ signal?: AbortSignal,
176
+ ): Promise<{token: string; account: string}> {
177
+ if (signal?.aborted) throw abortReason(signal)
178
+ let token: string
179
+ try {
180
+ token = await auth.getCoreToken(forceRefresh ? {forceRefresh: true} : undefined)
181
+ } catch (error) {
182
+ if (signal?.aborted) throw abortReason(signal)
183
+ throw error
184
+ }
185
+ if (signal?.aborted) throw abortReason(signal)
186
+ const account = accountOf(token)
187
+ if (!account) throw new SessionChangedError("unreadable_token")
188
+ return {token, account}
189
+ }
190
+
191
+ /** Throws `SessionChangedError` unless the client holds `account`'s session right now. */
192
+ private async assertStill(auth: CoreTokenSource, account: string, signal?: AbortSignal): Promise<void> {
193
+ let current: string
194
+ try {
195
+ current = (await this.tokenFor(auth, false, signal)).account
196
+ } catch (error) {
197
+ // A session that ended mid-request is a change; any other trouble reading it is reported as it is.
198
+ if (error instanceof AuthExpiredError) throw new SessionChangedError("signed_out")
199
+ throw error
200
+ }
201
+ if (current !== account) throw new SessionChangedError("other_account")
202
+ }
203
+ }
@@ -16,8 +16,17 @@
16
16
  * ("src/modules/core/core.ts").
17
17
  */
18
18
  import type { HttpClient } from "../../http";
19
- import type { FleetReport } from "@mentra/cloud-protocol";
19
+ import type { FleetDesiredState, FleetReport } from "@mentra/cloud-protocol";
20
+ import type {
21
+ AcceptInvitationResult,
22
+ DeclineInvitationResult,
23
+ LeaveWorkspaceRequest,
24
+ MyWorkspaceResponse,
25
+ PendingInvitationsResponse,
26
+ } from "./workspace-types";
27
+ import type { AccountCallOptions, CoreTokenSource } from "./account-call";
20
28
  import { Fleet, type FleetReportOutcome } from "./fleet";
29
+ import { Workspaces } from "./workspaces";
21
30
  import {
22
31
  Reports,
23
32
  type AddReportArtifactsResult,
@@ -56,6 +65,13 @@ export type {
56
65
  SubmitReportResult,
57
66
  } from "./reports";
58
67
  export type { FleetAck, FleetAckResult, FleetReportOutcome } from "./fleet";
68
+ export {
69
+ CoreRequestError,
70
+ CoreResponseError,
71
+ SessionChangedError,
72
+ type AccountCallOptions,
73
+ type CoreTokenSource,
74
+ } from "./account-call";
59
75
  export type {
60
76
  SupportConnectionState,
61
77
  SupportProfileUpdateResult,
@@ -65,6 +81,11 @@ export type {
65
81
  /** The dependencies `cloud.core` is wired with. */
66
82
  export interface CoreDeps {
67
83
  http: HttpClient;
84
+ /**
85
+ * Where workspace and desired-state calls get the signed-in account's Core token (`cloud.auth`). Without it those
86
+ * calls reject, because they must be made as one account.
87
+ */
88
+ auth?: CoreTokenSource;
68
89
  }
69
90
 
70
91
  /**
@@ -112,13 +133,32 @@ export class Core {
112
133
  * that Core token instead of the token source's.
113
134
  */
114
135
  report(batch: FleetReport, opts?: { signal?: AbortSignal; bearer?: string }): Promise<FleetReportOutcome>;
136
+ /**
137
+ * `GET /api/client/fleet/desired-state`, validated. Resolves only with a complete `managed` or `unmanaged` answer;
138
+ * every failure rejects (`CoreRequestError`, `CoreResponseError`, `SessionChangedError`, auth errors, abort), so
139
+ * none can be read as an empty set.
140
+ */
141
+ desiredState(opts?: AccountCallOptions): Promise<FleetDesiredState>;
142
+ };
143
+ readonly workspaces: {
144
+ /** `GET /api/client/workspaces/mine`. */
145
+ mine(opts?: AccountCallOptions): Promise<MyWorkspaceResponse>;
146
+ /** `GET /api/client/workspaces/invitations/mine`. */
147
+ pendingInvitations(opts?: AccountCallOptions): Promise<PendingInvitationsResponse>;
148
+ /** `POST /api/client/workspaces/invitations/:invitationId/accept`. */
149
+ acceptInvitation(invitationId: string, opts?: AccountCallOptions): Promise<AcceptInvitationResult>;
150
+ /** `POST /api/client/workspaces/invitations/:invitationId/decline`. */
151
+ declineInvitation(invitationId: string, opts?: AccountCallOptions): Promise<DeclineInvitationResult>;
152
+ /** `POST /api/client/workspaces/leave`, naming `opts.workspaceId` when given. */
153
+ leave(opts?: AccountCallOptions & LeaveWorkspaceRequest): Promise<void>;
115
154
  };
116
155
 
117
156
  constructor(deps: CoreDeps) {
118
- const { http } = deps;
157
+ const { http, auth } = deps;
119
158
  const reports = new Reports({ http });
120
159
  const supportProfiles = new SupportProfiles(http);
121
- const fleet = new Fleet(http);
160
+ const fleet = new Fleet(http, auth);
161
+ const workspaces = new Workspaces(http, auth);
122
162
 
123
163
  this.reports = {
124
164
  submit: reports.submit.bind(reports),
@@ -134,6 +174,14 @@ export class Core {
134
174
  };
135
175
  this.fleet = {
136
176
  report: fleet.report.bind(fleet),
177
+ desiredState: fleet.desiredState.bind(fleet),
178
+ };
179
+ this.workspaces = {
180
+ mine: workspaces.mine.bind(workspaces),
181
+ pendingInvitations: workspaces.pendingInvitations.bind(workspaces),
182
+ acceptInvitation: workspaces.acceptInvitation.bind(workspaces),
183
+ declineInvitation: workspaces.declineInvitation.bind(workspaces),
184
+ leave: workspaces.leave.bind(workspaces),
137
185
  };
138
186
  }
139
187
  }
@@ -1,8 +1,16 @@
1
- import {FLEET_NOT_INSTALLED, FLEET_SCHEMA_VERSION, type FleetReport} from "@mentra/cloud-protocol"
1
+ import {
2
+ FLEET_NOT_INSTALLED,
3
+ FLEET_SCHEMA_VERSION,
4
+ FleetDesiredStateSchema,
5
+ type FleetDesiredState,
6
+ type FleetReport,
7
+ } from "@mentra/cloud-protocol"
2
8
  import {AuthExpiredError, HttpError} from "../../errors"
3
9
  import type {HttpClient} from "../../http"
10
+ import {AccountCaller, CoreResponseError, type AccountCallOptions, type CoreTokenSource} from "./account-call"
4
11
 
5
12
  const FLEET_REPORT_PATH = "/api/client/fleet/report"
13
+ const FLEET_DESIRED_STATE_PATH = "/api/client/fleet/desired-state"
6
14
 
7
15
  /** Core's whole-response error codes are short snake_case words; anything else is not safe to surface. */
8
16
  const ERROR_CODE_PATTERN = /^[a-z][a-z0-9_]{0,63}$/
@@ -27,6 +35,8 @@ export interface FleetAckResult {
27
35
  export interface FleetAck {
28
36
  schemaVersion: typeof FLEET_SCHEMA_VERSION
29
37
  results: FleetAckResult[]
38
+ /** The account's desired-state revision at the time of the answer (Phase 11). Absent from an older Fleet. */
39
+ revision?: number
30
40
  }
31
41
 
32
42
  /**
@@ -96,7 +106,45 @@ function outcomeForHttpError(error: HttpError): FleetReportOutcome {
96
106
  }
97
107
 
98
108
  export class Fleet {
99
- constructor(private readonly http: HttpClient) {}
109
+ private readonly caller: AccountCaller
110
+
111
+ constructor(
112
+ private readonly http: HttpClient,
113
+ auth?: CoreTokenSource,
114
+ ) {
115
+ this.caller = new AccountCaller(auth)
116
+ }
117
+
118
+ /**
119
+ * Fetches the account's desired state (`GET /api/client/fleet/desired-state`), validated against
120
+ * `FleetDesiredStateSchema`.
121
+ *
122
+ * Resolves only with a complete, valid `managed` or `unmanaged` answer. Everything else rejects, so a failure can
123
+ * never be read as "nothing assigned" or "unmanaged" and make the phone drop what it holds:
124
+ * - `CoreRequestError`: any non-success answer (the status and Core's code are kept: 503 `fleet_unavailable`,
125
+ * 404 `fleet_not_installed`, 403, 429, ...) and a network failure (`status` 0, code `network_error`).
126
+ * - `CoreResponseError`: Core answered 2xx but the body is not desired state: no body, a missing field (an entry
127
+ * without `url`, a managed answer without `workspace`), an unknown key, or a `status` this client does not know
128
+ * (`reason: "unknown_status"`, for example a later `paused`).
129
+ * - `SessionChangedError`: the account changed while the request was out; the answer is dropped.
130
+ * - `AuthExpiredError` / `AuthUnavailableError` from the token source, and the abort reason on abort.
131
+ *
132
+ * A 401 refreshes the Core token once and sends again. `opts.expectedAccount` refuses the call when the client
133
+ * holds another account's token.
134
+ */
135
+ async desiredState(opts?: AccountCallOptions): Promise<FleetDesiredState> {
136
+ const body = await this.caller.run(
137
+ bearer =>
138
+ this.http.get<unknown>(FLEET_DESIRED_STATE_PATH, {bearer, ...(opts?.signal ? {signal: opts.signal} : {})}),
139
+ opts,
140
+ )
141
+ const parsed = FleetDesiredStateSchema.safeParse(body)
142
+ if (parsed.success) return parsed.data
143
+ const status = typeof body === "object" && body !== null && "status" in body ? body.status : undefined
144
+ throw new CoreResponseError(
145
+ typeof status === "string" && status !== "managed" && status !== "unmanaged" ? "unknown_status" : "invalid_shape",
146
+ )
147
+ }
100
148
 
101
149
  /**
102
150
  * Reports one batch of Fleet records to the phone's own Core.
@@ -171,5 +219,8 @@ function readAck(body: unknown): FleetAck | null {
171
219
  if (isWholeNumber(raw.retryAfterSeconds)) result.retryAfterSeconds = raw.retryAfterSeconds
172
220
  results.push(result)
173
221
  }
174
- return {schemaVersion: FLEET_SCHEMA_VERSION, results}
222
+ const ack: FleetAck = {schemaVersion: FLEET_SCHEMA_VERSION, results}
223
+ // A newer Fleet's revision tells the phone to fetch desired state. Anything but a whole number of 1 or more is not one.
224
+ if (typeof body.revision === "number" && Number.isSafeInteger(body.revision) && body.revision >= 1) ack.revision = body.revision
225
+ return ack
175
226
  }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * @fileoverview The wire shapes of Core's `/api/client/workspaces` router, as the Mentra App reads them.
3
+ *
4
+ * `@mentra/workspace-contract` defines them for Core, but it is a private package and this one is published, so a
5
+ * consumer of `@mentra/cloud-client` could not resolve an import of it. They are restated here instead;
6
+ * `workspace-types.test.ts` holds each one equal to the contract's, so the two cannot drift apart.
7
+ */
8
+
9
+ /** A role in a workspace (`WorkspaceRole` in the contract). */
10
+ export type ClientWorkspaceRole = "member" | "developer" | "admin" | "owner";
11
+
12
+ /** An invitation as the invitee sees it before accepting. It never carries the token or its hash. */
13
+ export interface InvitationPreview {
14
+ invitationId: string;
15
+ workspaceId: string;
16
+ workspaceName: string;
17
+ /** The invited address. */
18
+ email: string;
19
+ role: ClientWorkspaceRole;
20
+ /** Who sent it, by email address; null when the system did, or the address is no longer known. */
21
+ invitedByEmail: string | null;
22
+ expiresAt: string;
23
+ }
24
+
25
+ /** The workspace the signed-in phone's person belongs to (`GET /api/client/workspaces/mine`). */
26
+ export interface MyWorkspace {
27
+ workspaceId: string;
28
+ name: string;
29
+ role: ClientWorkspaceRole;
30
+ membershipId: string;
31
+ }
32
+
33
+ /** `GET /api/client/workspaces/mine`. */
34
+ export interface MyWorkspaceResponse {
35
+ workspace: MyWorkspace | null;
36
+ }
37
+
38
+ /** `GET /api/client/workspaces/invitations/mine`: the invitations addressed to the signed-in person. */
39
+ export interface PendingInvitationsResponse {
40
+ invitations: InvitationPreview[];
41
+ }
42
+
43
+ /** `POST /api/client/workspaces/invitations/:invitationId/accept`. */
44
+ export interface AcceptInvitationResult {
45
+ workspace: MyWorkspace;
46
+ }
47
+
48
+ /** `POST /api/client/workspaces/invitations/:invitationId/decline`. Declining twice is idempotent. */
49
+ export interface DeclineInvitationResult {
50
+ invitationId: string;
51
+ declined: true;
52
+ }
53
+
54
+ /**
55
+ * `POST /api/client/workspaces/leave`. With `workspaceId`, Core leaves that workspace only while the person is in
56
+ * it, and answers `membership_changed` (409) otherwise; without one, the person's workspace.
57
+ */
58
+ export interface LeaveWorkspaceRequest {
59
+ workspaceId?: string;
60
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * @fileoverview `cloud.core.workspaces`: the Mentra App's own view of the workspace the signed-in person belongs to,
3
+ * over Core's `/api/client/workspaces` router.
4
+ *
5
+ * GET /mine the person's workspace, or `{workspace: null}`
6
+ * GET /invitations/mine invitations addressed to their verified email
7
+ * POST /invitations/:invitationId/accept join the workspace the invitation is for
8
+ * POST /invitations/:invitationId/decline turn it down (idempotent)
9
+ * POST /leave leave the workspace (204; the only Owner cannot)
10
+ *
11
+ * Each call is made as the account whose Core token it carries (see `account-call.ts`): an answer that comes back after
12
+ * the account changed is discarded as `SessionChangedError`, and a 401 refreshes the token once. A failure keeps
13
+ * Core's status and error code on a `CoreRequestError` (`already_in_workspace`, `last_owner`, `invitation_expired`,
14
+ * `invitation_not_found`, `email_unverified`, `membership_changed`, ...) and never carries Core's wording.
15
+ */
16
+ import type {
17
+ AcceptInvitationResult,
18
+ DeclineInvitationResult,
19
+ InvitationPreview,
20
+ LeaveWorkspaceRequest,
21
+ MyWorkspace,
22
+ MyWorkspaceResponse,
23
+ PendingInvitationsResponse,
24
+ } from "./workspace-types"
25
+ import type {HttpClient} from "../../http"
26
+ import {AccountCaller, CoreResponseError, type AccountCallOptions, type CoreTokenSource} from "./account-call"
27
+
28
+ const BASE = "/api/client/workspaces"
29
+
30
+ function isObject(value: unknown): value is Record<string, unknown> {
31
+ return typeof value === "object" && value !== null && !Array.isArray(value)
32
+ }
33
+
34
+ function isText(value: unknown): value is string {
35
+ return typeof value === "string" && value.length > 0
36
+ }
37
+
38
+ function readWorkspace(value: unknown): MyWorkspace {
39
+ if (
40
+ !isObject(value) ||
41
+ !isText(value.workspaceId) ||
42
+ typeof value.name !== "string" ||
43
+ !isText(value.role) ||
44
+ !isText(value.membershipId)
45
+ ) {
46
+ throw new CoreResponseError("invalid_shape")
47
+ }
48
+ return {
49
+ workspaceId: value.workspaceId,
50
+ name: value.name,
51
+ role: value.role as MyWorkspace["role"],
52
+ membershipId: value.membershipId,
53
+ }
54
+ }
55
+
56
+ function readInvitation(value: unknown): InvitationPreview {
57
+ if (
58
+ !isObject(value) ||
59
+ !isText(value.invitationId) ||
60
+ !isText(value.workspaceId) ||
61
+ typeof value.workspaceName !== "string" ||
62
+ typeof value.email !== "string" ||
63
+ !isText(value.role) ||
64
+ (value.invitedByEmail !== null && typeof value.invitedByEmail !== "string") ||
65
+ !isText(value.expiresAt)
66
+ ) {
67
+ throw new CoreResponseError("invalid_shape")
68
+ }
69
+ return {
70
+ invitationId: value.invitationId,
71
+ workspaceId: value.workspaceId,
72
+ workspaceName: value.workspaceName,
73
+ email: value.email,
74
+ role: value.role as InvitationPreview["role"],
75
+ invitedByEmail: value.invitedByEmail,
76
+ expiresAt: value.expiresAt,
77
+ }
78
+ }
79
+
80
+ export class Workspaces {
81
+ private readonly caller: AccountCaller
82
+
83
+ constructor(
84
+ private readonly http: HttpClient,
85
+ auth?: CoreTokenSource,
86
+ ) {
87
+ this.caller = new AccountCaller(auth)
88
+ }
89
+
90
+ /** The workspace the signed-in person belongs to, or `{workspace: null}`. */
91
+ async mine(opts?: AccountCallOptions): Promise<MyWorkspaceResponse> {
92
+ const body = await this.caller.run(
93
+ bearer => this.http.get<unknown>(`${BASE}/mine`, {bearer, ...(opts?.signal ? {signal: opts.signal} : {})}),
94
+ opts,
95
+ )
96
+ if (!isObject(body) || !("workspace" in body)) throw new CoreResponseError("invalid_shape")
97
+ return {workspace: body.workspace === null ? null : readWorkspace(body.workspace)}
98
+ }
99
+
100
+ /** The invitations addressed to the signed-in person's verified email that they can still accept. */
101
+ async pendingInvitations(opts?: AccountCallOptions): Promise<PendingInvitationsResponse> {
102
+ const body = await this.caller.run(
103
+ bearer =>
104
+ this.http.get<unknown>(`${BASE}/invitations/mine`, {bearer, ...(opts?.signal ? {signal: opts.signal} : {})}),
105
+ opts,
106
+ )
107
+ if (!isObject(body) || !Array.isArray(body.invitations)) throw new CoreResponseError("invalid_shape")
108
+ return {invitations: body.invitations.map(readInvitation)}
109
+ }
110
+
111
+ /** Joins the workspace the invitation is for. `already_in_workspace` (409) means leave the current one first. */
112
+ async acceptInvitation(invitationId: string, opts?: AccountCallOptions): Promise<AcceptInvitationResult> {
113
+ const body = await this.caller.run(
114
+ bearer =>
115
+ this.http.post<unknown>(`${BASE}/invitations/${encodeURIComponent(invitationId)}/accept`, undefined, {
116
+ bearer,
117
+ ...(opts?.signal ? {signal: opts.signal} : {}),
118
+ }),
119
+ opts,
120
+ )
121
+ if (!isObject(body)) throw new CoreResponseError("invalid_shape")
122
+ return {workspace: readWorkspace(body.workspace)}
123
+ }
124
+
125
+ /** Turns the invitation down. Declining twice is fine; no membership changes. */
126
+ async declineInvitation(invitationId: string, opts?: AccountCallOptions): Promise<DeclineInvitationResult> {
127
+ const body = await this.caller.run(
128
+ bearer =>
129
+ this.http.post<unknown>(`${BASE}/invitations/${encodeURIComponent(invitationId)}/decline`, undefined, {
130
+ bearer,
131
+ // Idempotent on Core, so a transient network failure may be retried.
132
+ idempotent: true,
133
+ ...(opts?.signal ? {signal: opts.signal} : {}),
134
+ }),
135
+ opts,
136
+ )
137
+ if (!isObject(body) || !isText(body.invitationId) || body.declined !== true) {
138
+ throw new CoreResponseError("invalid_shape")
139
+ }
140
+ return {invitationId: body.invitationId, declined: true}
141
+ }
142
+
143
+ /**
144
+ * Leaves the workspace: `opts.workspaceId` when given, which Core refuses with `membership_changed` (409) once the
145
+ * person is no longer in it. `last_owner` (409) means the only Owner cannot leave; `not_found` that there is none.
146
+ */
147
+ async leave(opts?: AccountCallOptions & LeaveWorkspaceRequest): Promise<void> {
148
+ const body: LeaveWorkspaceRequest | undefined = opts?.workspaceId ? {workspaceId: opts.workspaceId} : undefined
149
+ await this.caller.run(
150
+ bearer => this.http.post<unknown>(`${BASE}/leave`, body, {bearer, ...(opts?.signal ? {signal: opts.signal} : {})}),
151
+ opts,
152
+ )
153
+ }
154
+ }