moi-computer 0.13.0 → 0.13.1-next.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.
Files changed (51) hide show
  1. package/client/api/query-client.ts +5 -0
  2. package/client/app/app-router.tsx +1 -1
  3. package/client/app/routes/workspace-route.tsx +2 -0
  4. package/client/features/account/account-provider.tsx +28 -77
  5. package/client/features/account/account-test-utils.tsx +95 -93
  6. package/client/features/account/api.ts +32 -109
  7. package/client/features/account/profile-actions.ts +31 -0
  8. package/client/features/app-settings/settings-page.tsx +0 -4
  9. package/client/features/collab/client.ts +38 -13
  10. package/client/features/collab/hooks.tsx +9 -8
  11. package/client/features/collab/host-state.ts +45 -85
  12. package/client/features/collab/testing/fake-engine.ts +13 -1
  13. package/client/features/collab/users.ts +0 -12
  14. package/client/features/dev/cloud-avatar-upload.tsx +58 -0
  15. package/client/features/dev/cloud-page.tsx +363 -0
  16. package/client/features/dev/dev-index-page.tsx +6 -0
  17. package/client/features/dev/dev-routes.tsx +2 -0
  18. package/client/features/identity/host-api.ts +34 -0
  19. package/client/features/identity/store.ts +32 -0
  20. package/client/features/identity/types.ts +41 -0
  21. package/client/features/identity/use-identity.ts +6 -0
  22. package/client/features/workspace-members/api.ts +20 -0
  23. package/client/features/workspace-members/hooks.ts +127 -0
  24. package/client/features/workspace-members/keys.ts +6 -0
  25. package/client/features/workspace-members/store.ts +123 -0
  26. package/client/features/workspace-members/types.ts +53 -0
  27. package/client/index.html +1 -1
  28. package/client/index.tsx +5 -9
  29. package/client/main.tsx +2 -2
  30. package/dist/{chunk-cqt3s31j.js → chunk-00s35r33.js} +68 -68
  31. package/dist/{chunk-bncc7heg.js → chunk-7rz6g7g7.js} +1 -1
  32. package/dist/chunk-af2jyddf.js +2 -0
  33. package/dist/chunk-cekekc3f.css +1 -0
  34. package/dist/chunk-ep5vh16c.js +75 -0
  35. package/dist/{chunk-2y59vrxg.js → chunk-kdgk4dac.js} +1 -1
  36. package/dist/chunk-s5s1vzdw.js +2 -0
  37. package/dist/{chunk-58dyt9bk.js → chunk-svxhxfeq.js} +2 -2
  38. package/dist/chunk-t0r0bds1.js +1 -0
  39. package/dist/chunk-vp2qzc0d.js +1 -0
  40. package/dist/{chunk-q37knr3m.js → chunk-wz5qv1bn.js} +2 -2
  41. package/dist/index.html +2 -2
  42. package/package.json +5 -4
  43. package/server/app-config.ts +3 -1
  44. package/client/features/account/identity.ts +0 -23
  45. package/client/features/app-settings/users-settings.tsx +0 -195
  46. package/dist/chunk-dcmks9sm.js +0 -75
  47. package/dist/chunk-md45evr2.css +0 -1
  48. package/dist/chunk-n0nab26d.js +0 -1
  49. package/dist/chunk-nmzhgyp9.js +0 -2
  50. package/dist/chunk-s90m4qkz.js +0 -1
  51. package/dist/chunk-wjvd4byz.js +0 -2
@@ -0,0 +1,5 @@
1
+ import { QueryClient } from '@tanstack/query-core'
2
+
3
+ // Shared with the host API so it can populate workspace members before React mounts
4
+ // and clear cached members when the account changes.
5
+ export const queryClient = new QueryClient()
@@ -14,7 +14,7 @@ import { WorkspaceRoute } from './routes/workspace-route'
14
14
  // separate lazy chunk. The NODE_ENV gate is statically false in the prod
15
15
  // build (scripts/build-client.ts defines it), so the bundler drops the
16
16
  // dynamic import and none of features/dev is emitted into dist at all.
17
- // In prod /dev redirects home.
17
+ // In production /dev redirects home.
18
18
  const DevRoutes =
19
19
  process.env.NODE_ENV === 'development'
20
20
  ? lazy(() => import('@/client/features/dev/dev-routes'))
@@ -1,3 +1,4 @@
1
+ import { useWorkspaceMembers } from '@/client/features/workspace-members/hooks'
1
2
  import { useWorkspaceHarnessChanges } from '@/client/features/workspace/harness-transition'
2
3
  import { useWorkspaceTheme } from '@/client/runtime/workspace-theme'
3
4
  import { CollabProvider, useCollabEnabled } from '@/client/features/collab'
@@ -26,6 +27,7 @@ type WorkspaceRouteProps = {
26
27
  // Navigation reads the raw browser address so encoded paths and query params
27
28
  // are decoded exactly once; the route only owns the workspace ID.
28
29
  export function WorkspaceRoute({ id }: WorkspaceRouteProps) {
30
+ useWorkspaceMembers(id)
29
31
  const { collab } = useAppConfig()
30
32
 
31
33
  return (
@@ -1,4 +1,5 @@
1
- import { createContext, useContext, useEffect, useState, useSyncExternalStore } from 'react'
1
+ import { useIdentity } from '../identity/use-identity'
2
+ import { createContext, useContext, useSyncExternalStore } from 'react'
2
3
  import type { ReactNode } from 'react'
3
4
  import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
4
5
  import { useAppConfig } from '@/client/api/app-config'
@@ -6,19 +7,18 @@ import {
6
7
  getCurrentUser,
7
8
  getCurrentUserSource,
8
9
  setLocalUser,
9
- subscribeCurrentUserStore,
10
- publishUsers
10
+ subscribeCurrentUserStore
11
11
  } from '@/client/features/collab/host-state'
12
+ import { setIdentity } from '../identity/store'
13
+ import { saveCloudProfile } from './profile-actions'
12
14
  import {
13
15
  accountKeys,
14
- CloudApiError,
15
- sessionQuery,
16
- teamQuery,
17
- updateCloudName,
16
+ identityRefreshQuery,
17
+ updateCloudProfile,
18
+ uploadCloudAvatar,
19
+ removeCloudAvatar,
18
20
  signOutCloud
19
21
  } from './api'
20
- import type { CloudSession } from './api'
21
- import { syncCloudIdentity } from './identity'
22
22
 
23
23
  function useAccountState() {
24
24
  const { environment, demo } = useAppConfig()
@@ -29,105 +29,56 @@ function useAccountState() {
29
29
  getCurrentUserSource,
30
30
  getCurrentUserSource
31
31
  )
32
+ const identity = useIdentity()
32
33
  const qc = useQueryClient()
33
- const session = useQuery({ ...sessionQuery, enabled: cloud && !demo })
34
- const registered = cloud && !demo && !!session.data && !session.data.user.isAnonymous
35
- const team = useQuery({ ...teamQuery(session.data?.user.id), enabled: registered })
36
- const [removingMemberIds, setRemovingMemberIds] = useState<string[]>([])
37
-
34
+ const query = useQuery({ ...identityRefreshQuery, enabled: cloud && !demo })
35
+ const registered = cloud && !demo && identity?.type === 'user' && !identity.isAnonymous
38
36
  const signOut = useMutation({
39
37
  mutationFn: signOutCloud,
40
38
  onSuccess: async () => {
41
39
  await qc.cancelQueries({ queryKey: accountKeys.all })
42
- publishUsers({ users: [] })
43
- qc.setQueryData(accountKeys.session, null)
44
- qc.removeQueries({ queryKey: accountKeys.team })
40
+ setIdentity(null)
45
41
  window.location.assign('/cloud/login')
46
42
  }
47
43
  })
48
- useEffect(() => {
49
- if (!cloud || demo || !session.isSuccess || signOut.isPending || signOut.isSuccess) return
50
- syncCloudIdentity(session.data, registered ? team.data : undefined)
51
- }, [
52
- cloud,
53
- demo,
54
- session.data,
55
- session.isSuccess,
56
- registered,
57
- team.data,
58
- signOut.isPending,
59
- signOut.isSuccess
60
- ])
61
- useEffect(() => {
62
- if (team.error instanceof CloudApiError && team.error.status === 401)
63
- void qc.invalidateQueries({ queryKey: accountKeys.session })
64
- }, [team.error, qc])
65
-
66
44
  async function saveName(value: string) {
67
45
  const name = value.trim()
68
46
  if (!name || name.length > 80) throw new Error('Enter a name of up to 80 characters')
69
47
  if (cloud) {
70
- if (!registered) throw new Error('Sign in to change your name')
71
- await qc.cancelQueries({ queryKey: accountKeys.session })
72
- await updateCloudName(name).catch(error => {
73
- if (error instanceof CloudApiError && error.status === 401)
74
- void qc.invalidateQueries({ queryKey: accountKeys.session })
75
- throw error
76
- })
77
- const latestSession = qc.getQueryData<CloudSession>(accountKeys.session)
78
- if (
79
- !latestSession ||
80
- latestSession.user.id !== session.data!.user.id ||
81
- latestSession.user.isAnonymous
82
- )
83
- throw new Error('Your account changed. Reload Moi to try again.')
84
- const next: CloudSession = { user: { ...latestSession.user, name } }
85
- qc.setQueryData(accountKeys.session, next)
86
- syncCloudIdentity(next, team.data)
87
- void qc.invalidateQueries({ queryKey: accountKeys.team })
48
+ await saveCloudProfile('name', () => updateCloudProfile({ name }))
88
49
  return name
89
50
  }
90
- const localProfile = getCurrentUser()
91
- if (getCurrentUserSource() !== 'local' || !localProfile || localProfile.id !== profile?.id)
51
+ const local = getCurrentUser()
52
+ if (getCurrentUserSource() !== 'local' || !local || local.id !== profile?.id)
92
53
  throw new Error('This profile is managed by your sign-in provider')
93
- setLocalUser({ ...localProfile, name })
54
+ setLocalUser({ ...local, name })
94
55
  return name
95
56
  }
96
-
57
+ async function saveAvatar(file: File | null) {
58
+ await saveCloudProfile('avatar', () => (file ? uploadCloudAvatar(file) : removeCloudAvatar()))
59
+ }
97
60
  function getStatus() {
98
61
  if (demo) return 'signed-out'
99
62
  if (!cloud) return profile ? 'ready' : 'error'
100
- if (session.isPending) return 'loading'
101
- if (session.isError) return 'error'
102
- if (!registered) return 'signed-out'
103
- if (profile?.id === session.data?.user.id && source === 'external') return 'ready'
104
- return 'loading'
63
+ if (identity === undefined) return query.isError ? 'error' : 'loading'
64
+ if (!identity || (identity.type === 'user' && identity.isAnonymous)) return 'signed-out'
65
+ return 'ready'
105
66
  }
106
-
107
67
  return {
108
68
  cloud,
109
- demo: demo || (cloud && session.data?.user.isAnonymous === true),
69
+ demo: demo || (identity?.type === 'user' && identity.isAnonymous),
110
70
  profile,
71
+ identity,
111
72
  status: getStatus(),
112
- email: registered ? session.data?.user.email : undefined,
73
+ email: registered && identity?.type === 'user' ? identity.email : undefined,
113
74
  canEdit: cloud ? registered : source === 'local',
114
75
  registered,
115
- team,
116
- removingMemberIds,
117
- setRemovingMemberIds,
118
76
  saveName,
77
+ saveAvatar,
119
78
  signOut,
120
- retry: () => {
121
- if (!cloud) {
122
- window.location.reload()
123
- return
124
- }
125
- void session.refetch()
126
- if (registered) void team.refetch()
127
- }
79
+ retry: () => (cloud ? void query.refetch() : window.location.reload())
128
80
  }
129
81
  }
130
-
131
82
  type AccountState = ReturnType<typeof useAccountState>
132
83
  const AccountContext = createContext<AccountState | undefined>(undefined)
133
84
  type AccountProviderProps = { children: ReactNode }
@@ -5,74 +5,48 @@ import * as layoutEffect from '@base-ui/utils/useIsoLayoutEffect'
5
5
  import { Router } from 'wouter'
6
6
  import { memoryLocation } from 'wouter/memory-location'
7
7
  import { parseHTML } from 'linkedom'
8
- import { QueryClient, QueryClientProvider, notifyManager } from '@tanstack/react-query'
8
+ import { QueryClientProvider, notifyManager } from '@tanstack/react-query'
9
9
  import * as config from '@/client/api/app-config'
10
- import { publishUsers } from '@/client/features/collab/host-state'
11
10
  import { AccountProvider, useAccount } from './account-provider'
12
- import { sessionQuery, teamQuery } from './api'
13
- import type { CloudSession, CloudTeam } from './api'
11
+ import { queryClient } from '@/client/api/query-client'
12
+ import type { WorkspaceMembers } from '../workspace-members/types'
13
+ import { setIdentity } from '../identity/store'
14
+ import type { Identity } from '../identity/types'
14
15
 
15
- const session: CloudSession = {
16
- user: { id: 'me', name: 'Alex', email: 'alex@example.com', isAnonymous: false }
17
- }
18
- export const ownerTeam: CloudTeam = {
19
- id: 'team',
20
- name: 'Team',
21
- role: 'owner',
22
- members: [
23
- {
24
- id: 'member-me',
25
- userId: 'me',
26
- name: 'Alex',
27
- email: 'alex@example.com',
28
- role: 'owner',
29
- me: true
30
- },
31
- {
32
- id: 'member-ada',
33
- userId: 'ada',
34
- name: 'Ada',
35
- email: 'ada@example.com',
36
- role: 'admin',
37
- me: false
38
- }
39
- ],
40
- invitations: [
41
- { id: 'invite-1', email: 'grace@example.com', role: 'admin', expiresAt: '2030-01-01' }
42
- ]
16
+ const session: Identity = {
17
+ id: 'me',
18
+ type: 'user',
19
+ name: 'Alex',
20
+ email: 'alex@example.com',
21
+ isAnonymous: false,
22
+ avatar: 'https://example.com/avatar.png'
43
23
  }
44
24
  let cleanup = async () => {}
45
25
  export const cleanupAccount = () => cleanup()
46
26
 
47
27
  export type AccountFixtureOptions = {
48
28
  children?: ReactNode
49
- role?: string
50
29
  anonymous?: boolean
51
30
  signedOut?: boolean
52
31
  demo?: boolean
53
- failTeam?: boolean
54
32
  environment?: 'local' | 'cloud'
55
33
  failSession?: boolean
56
34
  loadingSession?: boolean
57
35
  pendingMutation?: boolean
58
36
  pendingMutationPaths?: string[]
59
37
  injected?: boolean
60
- loadingTeam?: boolean
61
38
  }
62
39
  export async function mountAccount({
63
40
  children = <AccountProbe />,
64
- role = 'owner',
65
41
  anonymous = false,
66
42
  signedOut = false,
67
43
  demo = false,
68
- failTeam = false,
69
44
  environment = 'cloud',
70
45
  failSession = false,
71
46
  loadingSession = false,
72
47
  pendingMutation = false,
73
48
  pendingMutationPaths = [],
74
- injected = true,
75
- loadingTeam = false
49
+ injected = true
76
50
  }: AccountFixtureOptions = {}) {
77
51
  const { window, document } = parseHTML('<html><body><div id="root"></div></body></html>')
78
52
  Object.defineProperty(document, 'oninput', { value: null, configurable: true })
@@ -88,6 +62,7 @@ export async function mountAccount({
88
62
  window,
89
63
  document,
90
64
  HTMLElement: window.HTMLElement,
65
+ CustomEvent: window.CustomEvent,
91
66
  Element: window.Element,
92
67
  requestAnimationFrame: (callback: FrameRequestCallback) =>
93
68
  Number(setTimeout(() => callback(performance.now()), 0)),
@@ -115,34 +90,41 @@ export async function mountAccount({
115
90
  collab: false,
116
91
  demoInstallUrl: '/'
117
92
  })
118
- let cloudSession: CloudSession = signedOut
93
+ let cloudSession: Identity | null = signedOut
119
94
  ? null
120
- : { user: { ...session!.user, isAnonymous: anonymous } }
121
- let team: CloudTeam = structuredClone({ ...ownerTeam, role })
122
- const failures = { signOut: false, mutation: false, team: failTeam, session: failSession }
95
+ : { ...session, type: 'user', email: 'alex@example.com', isAnonymous: anonymous }
96
+ const failures = { signOut: false, mutation: false, session: failSession }
123
97
  const mutationRequest = Promise.withResolvers<void>()
124
- const teamResponse = Promise.withResolvers<Response>()
98
+ let membership: WorkspaceMembers = {
99
+ members: [{ ...session, membershipId: 'member-me' }],
100
+ invitations: []
101
+ }
125
102
  const calls: { path: string; body?: Record<string, unknown> }[] = []
126
103
  const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation(
127
104
  Object.assign(
128
105
  async (input: RequestInfo | URL, init?: RequestInit) => {
129
106
  const path = String(input)
130
107
  const body = init?.body
131
- ? (JSON.parse(String(init.body)) as Record<string, string>)
108
+ ? init.body instanceof FormData
109
+ ? {}
110
+ : (JSON.parse(String(init.body)) as Record<string, string>)
132
111
  : undefined
133
112
  calls.push({ path, body })
134
- if (path.endsWith('/get-session')) {
113
+ if (path === '/api/workspaces')
114
+ return Response.json([
115
+ { id: 'one', name: 'First workspace' },
116
+ { id: 'two', name: 'Second workspace' }
117
+ ])
118
+ if (path.endsWith('/me') && (!init?.method || init.method === 'GET')) {
135
119
  if (loadingSession) return new Promise<Response>(() => {})
136
120
  return failures.session
137
121
  ? Response.json({ error: 'Session unavailable' }, { status: 503 })
138
- : Response.json(cloudSession)
139
- }
140
- if (path.endsWith('/organization')) {
141
- if (loadingTeam) return teamResponse.promise
142
- return failures.team
143
- ? Response.json({ error: 'Team unavailable' }, { status: 503 })
144
- : Response.json(team)
122
+ : cloudSession
123
+ ? Response.json(cloudSession)
124
+ : Response.json({ error: 'No session' }, { status: 401 })
145
125
  }
126
+ if (path.endsWith('/members') && (!init?.method || init.method === 'GET'))
127
+ return Response.json(membership)
146
128
  if (path.endsWith('/sign-out')) {
147
129
  if (failures.signOut)
148
130
  return Response.json({ error: 'Try signing out again.' }, { status: 503 })
@@ -157,49 +139,62 @@ export async function mountAccount({
157
139
  await mutationRequest.promise
158
140
  if (failures.mutation)
159
141
  return Response.json({ error: 'Only the owner can do that.' }, { status: 403 })
142
+ if (init?.method === 'DELETE' && path.includes('/members/')) {
143
+ membership = {
144
+ ...membership,
145
+ members: membership.members.filter(
146
+ member => member.membershipId !== path.split('/').at(-1)
147
+ )
148
+ }
149
+ return new Response(null, { status: 204 })
150
+ }
151
+ if (init?.method === 'DELETE' && path.includes('/invitations/')) {
152
+ membership = {
153
+ ...membership,
154
+ invitations: membership.invitations.filter(
155
+ invitation => invitation.id !== path.split('/').at(-1)
156
+ )
157
+ }
158
+ return new Response(null, { status: 204 })
159
+ }
160
+ if (path.endsWith('/invitations')) {
161
+ membership = {
162
+ ...membership,
163
+ invitations: [
164
+ ...membership.invitations,
165
+ { id: 'invite-new', email: body!.email!, expiresAt: '2030-01-01' }
166
+ ]
167
+ }
168
+ return Response.json({ invitation: membership.invitations.at(-1) }, { status: 201 })
169
+ }
160
170
  if (path === '/api/settings') return Response.json({ autoUpdateSkills: false, ...body })
161
- if (path.endsWith('/profile')) {
162
- cloudSession = { user: { ...session!.user, name: body!.name! } }
163
- team.members[0]!.name = body!.name!
164
- return Response.json({ success: true, name: body!.name })
171
+ if ((path.endsWith('/me') || path.endsWith('/me/avatar')) && cloudSession) {
172
+ cloudSession = {
173
+ ...cloudSession,
174
+ ...(body?.name ? { name: body.name } : {}),
175
+ ...(path.endsWith('/avatar')
176
+ ? { avatar: init?.method === 'DELETE' ? undefined : 'https://example.com/new.png' }
177
+ : {})
178
+ }
179
+ membership = {
180
+ ...membership,
181
+ members: membership.members.map(member =>
182
+ member.id === cloudSession!.id ? { ...member, ...cloudSession! } : member
183
+ )
184
+ }
185
+ return Response.json(cloudSession)
165
186
  }
166
- if (path.endsWith('/members/remove'))
167
- team.members = team.members.filter(member => member.id !== body!.memberId)
168
- if (path.endsWith('/cancel')) team.invitations = []
169
- if (path.endsWith('/invite'))
170
- team.invitations.push({
171
- id: 'invite-new',
172
- email: body!.email!,
173
- role: 'admin',
174
- expiresAt: '2030-01-01'
175
- })
176
187
  return Response.json({ success: true })
177
188
  },
178
189
  { preconnect: fetch.preconnect }
179
190
  )
180
191
  )
181
- const qc = new QueryClient({
182
- defaultOptions: { queries: { retry: false }, mutations: { retry: false } }
183
- })
184
- if (!failSession && !loadingSession)
185
- qc.setQueryData(sessionQuery.queryKey, structuredClone(cloudSession))
186
- if (!failTeam && !loadingTeam)
187
- qc.setQueryData(teamQuery(cloudSession?.user.id).queryKey, structuredClone(team))
188
- publishUsers({ users: [] })
189
- if (injected)
190
- publishUsers({
191
- me: 'me',
192
- users: [
193
- {
194
- id: 'me',
195
- name: 'Alex',
196
- email: 'alex@example.com',
197
- color: 'blue',
198
- avatar: 'https://example.com/avatar.png'
199
- },
200
- { id: 'ada', name: 'Ada', email: 'ada@example.com', color: 'cyan' }
201
- ]
202
- })
192
+ const qc = queryClient
193
+ qc.clear()
194
+ qc.setDefaultOptions({ queries: { retry: false }, mutations: { retry: false } })
195
+ setIdentity(null)
196
+ if (!loadingSession && !failSession && environment === 'cloud') setIdentity(cloudSession)
197
+ if (injected && environment === 'local') setIdentity(session)
203
198
  const { createRoot } = await import('react-dom/client')
204
199
  const root = createRoot(document.getElementById('root')!)
205
200
  notifyManager.setNotifyFunction(callback => {
@@ -221,9 +216,13 @@ export async function mountAccount({
221
216
  })
222
217
  }
223
218
  cleanup = async () => {
224
- await act(async () => root.unmount())
219
+ await qc.cancelQueries()
220
+ await act(async () => {
221
+ root.unmount()
222
+ await new Promise(resolve => setTimeout(resolve, 20))
223
+ })
225
224
  qc.clear()
226
- publishUsers({ users: [] })
225
+ setIdentity(null)
227
226
  layoutEffectSpy.mockRestore()
228
227
  configSpy.mockRestore()
229
228
  fetchSpy.mockRestore()
@@ -239,14 +238,17 @@ export async function mountAccount({
239
238
  calls,
240
239
  failures,
241
240
  mutationRequest,
242
- teamResponse,
243
241
  qc,
242
+ setMembership: (next: WorkspaceMembers) => {
243
+ membership = next
244
+ },
244
245
  navigations,
245
246
  location,
246
247
  settle,
247
248
  async click(label: string) {
248
249
  const button = [...document.querySelectorAll<HTMLElement>('button, [role="menuitem"]')].find(
249
- button => button.getAttribute('aria-label') === label || button.textContent === label
250
+ button =>
251
+ button.getAttribute('aria-label') === label || button.textContent?.trim() === label
250
252
  )
251
253
  expect(button).toBeDefined()
252
254
  await act(async () => {
@@ -1,33 +1,14 @@
1
1
  import { queryOptions } from '@tanstack/react-query'
2
2
  import { jsonRequest } from '@/client/api/http'
3
- import { isRecord, isUserProfile } from '@/lib/collab/protocol'
4
-
5
- export type CloudSession = {
6
- user: { id: string; email: string; name: string; isAnonymous: boolean }
7
- } | null
8
- export type TeamMember = {
9
- id: string
10
- userId: string
11
- email: string
12
- name: string
13
- role: string
14
- me: boolean
15
- }
16
- export type TeamInvitation = { id: string; email: string; role: string; expiresAt: string }
17
- export type CloudTeam = {
18
- id: string
19
- name: string
20
- role: string
21
- members: TeamMember[]
22
- invitations: TeamInvitation[]
23
- }
3
+ import { isRecord } from '@/lib/collab/protocol'
4
+ import { parseIdentity } from '../identity/types'
5
+ import { getIdentityRevision, setIdentity } from '../identity/store'
6
+ import type { Identity } from '../identity/types'
24
7
 
25
8
  export const accountKeys = {
26
9
  all: ['account'] as const,
27
- session: ['account', 'session'] as const,
28
- team: ['account', 'team'] as const
10
+ identityRefresh: ['account', 'identity-refresh'] as const
29
11
  }
30
-
31
12
  export class CloudApiError extends Error {
32
13
  constructor(
33
14
  message: string,
@@ -36,9 +17,8 @@ export class CloudApiError extends Error {
36
17
  super(message)
37
18
  }
38
19
  }
39
-
40
20
  export async function cloudRequest(path: string, init?: RequestInit): Promise<Response> {
41
- const response = await fetch(`/cloud/api/auth/${path}`, { ...init, credentials: 'same-origin' })
21
+ const response = await fetch(`/cloud/api/${path}`, { ...init, credentials: 'same-origin' })
42
22
  if (!response.ok) {
43
23
  const body: unknown = await response.json().catch(() => undefined)
44
24
  const message = isRecord(body)
@@ -53,90 +33,33 @@ export async function cloudRequest(path: string, init?: RequestInit): Promise<Re
53
33
  }
54
34
  return response
55
35
  }
56
-
57
- function validProfile(id: unknown, name: unknown, email: unknown): boolean {
58
- return (
59
- typeof id === 'string' &&
60
- id === id.trim() &&
61
- typeof name === 'string' &&
62
- typeof email === 'string' &&
63
- isUserProfile({ id, name: name.trim() || undefined, email, color: 'blue' })
64
- )
65
- }
66
-
67
- function parseSession(value: unknown): CloudSession {
68
- if (value === null) return null
69
- if (
70
- !isRecord(value) ||
71
- !isRecord(value.user) ||
72
- !validProfile(value.user.id, value.user.name, value.user.email) ||
73
- typeof value.user.isAnonymous !== 'boolean'
74
- )
75
- throw new Error('Invalid account response')
76
- return value as NonNullable<CloudSession>
77
- }
78
-
79
- function parseTeam(value: unknown): CloudTeam {
80
- if (
81
- !isRecord(value) ||
82
- typeof value.id !== 'string' ||
83
- typeof value.name !== 'string' ||
84
- typeof value.role !== 'string' ||
85
- !Array.isArray(value.members) ||
86
- !Array.isArray(value.invitations) ||
87
- !value.members.every(
88
- member =>
89
- isRecord(member) &&
90
- typeof member.id === 'string' &&
91
- validProfile(member.userId, member.name, member.email) &&
92
- typeof member.role === 'string' &&
93
- typeof member.me === 'boolean'
94
- ) ||
95
- !value.invitations.every(
96
- invitation =>
97
- isRecord(invitation) &&
98
- validProfile(invitation.id, '', invitation.email) &&
99
- typeof invitation.role === 'string' &&
100
- typeof invitation.expiresAt === 'string' &&
101
- Number.isFinite(Date.parse(invitation.expiresAt))
102
- )
103
- )
104
- throw new Error('Invalid users response')
105
- const team = value as CloudTeam
106
- if (
107
- new Set(team.members.map(member => member.userId)).size !== team.members.length ||
108
- new Set(team.members.map(member => member.id)).size !== team.members.length ||
109
- new Set(team.invitations.map(invitation => invitation.id)).size !== team.invitations.length
110
- )
111
- throw new Error('Invalid users response')
112
- return team
113
- }
114
-
115
- export const sessionQuery = queryOptions({
116
- queryKey: accountKeys.session,
117
- queryFn: async ({ signal }) => {
118
- const response = await cloudRequest('get-session', { signal })
119
- return parseSession(await response.json())
36
+ // React Query tracks refresh status only. Identity itself lives in the identity store.
37
+ export const identityRefreshQuery = queryOptions({
38
+ queryKey: accountKeys.identityRefresh,
39
+ queryFn: async ({ signal }): Promise<true> => {
40
+ const identityRevision = getIdentityRevision()
41
+ let identity: Identity | null
42
+ try {
43
+ identity = parseIdentity(await (await cloudRequest('me', { signal })).json())
44
+ } catch (error) {
45
+ if (!(error instanceof CloudApiError) || error.status !== 401) throw error
46
+ identity = null
47
+ }
48
+ // A pushed identity or account switch wins over an older request.
49
+ if (!signal.aborted && getIdentityRevision() === identityRevision) setIdentity(identity)
50
+ return true
120
51
  },
121
52
  retry: false,
122
53
  staleTime: 30_000
123
54
  })
124
- export const teamQuery = (userId?: string) =>
125
- queryOptions({
126
- queryKey: [...accountKeys.team, userId],
127
- queryFn: async ({ signal }) => {
128
- const response = await cloudRequest('organization', { signal })
129
- return parseTeam(await response.json())
130
- },
131
- retry: false,
132
- staleTime: 30_000
133
- })
134
- export const updateCloudName = (name: string) =>
135
- cloudRequest('profile', jsonRequest('POST', { name }))
136
- export const signOutCloud = () => cloudRequest('sign-out', jsonRequest('POST'))
137
- export const inviteMember = (email: string) =>
138
- cloudRequest('invite', jsonRequest('POST', { email }))
139
- export const cancelInvitation = (id: string) =>
140
- cloudRequest(`invitation/${encodeURIComponent(id)}/cancel`, jsonRequest('POST'))
141
- export const removeMember = (memberId: string) =>
142
- cloudRequest('members/remove', jsonRequest('POST', { memberId }))
55
+ type ProfilePatch = { name: string }
56
+ export const updateCloudProfile = async (patch: ProfilePatch) =>
57
+ parseIdentity(await (await cloudRequest('me', jsonRequest('PATCH', patch))).json())
58
+ export async function uploadCloudAvatar(file: File) {
59
+ const body = new FormData()
60
+ body.set('file', file)
61
+ return parseIdentity(await (await cloudRequest('me/avatar', { method: 'PUT', body })).json())
62
+ }
63
+ export const removeCloudAvatar = async () =>
64
+ parseIdentity(await (await cloudRequest('me/avatar', { method: 'DELETE' })).json())
65
+ export const signOutCloud = () => cloudRequest('auth/sign-out', jsonRequest('POST'))