-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.ts
More file actions
277 lines (233 loc) · 10.5 KB
/
Copy pathapi.ts
File metadata and controls
277 lines (233 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import { TwistApi, type User, type Workspace, type WorkspaceUser } from '@doist/twist-sdk'
import { getApiToken } from './auth.js'
import { getConfig, updateConfig } from './config.js'
import { ensureWriteAllowed, isMutatingMethod } from './permissions.js'
import { getProgressTracker } from './progress.js'
import { withSpinner } from './spinner.js'
// Mapping of API method paths to user-friendly spinner messages
const API_SPINNER_MESSAGES: Record<string, { text: string; color?: 'blue' | 'green' | 'yellow' }> =
{
// User operations
'users.getSessionUser': { text: 'Checking authentication...', color: 'blue' },
'users.update': { text: 'Updating user...', color: 'yellow' },
// Workspace operations
'workspaces.getWorkspaces': { text: 'Loading workspaces...', color: 'blue' },
'workspaceUsers.getWorkspaceUsers': { text: 'Loading workspace users...', color: 'blue' },
'workspaceUsers.getUserById': { text: 'Loading user details...', color: 'blue' },
// Thread operations
'threads.getThread': { text: 'Loading thread...', color: 'blue' },
'threads.getUnread': { text: 'Loading unread threads...', color: 'blue' },
// Comment operations
'comments.getComment': { text: 'Loading comment...', color: 'blue' },
'comments.getComments': { text: 'Loading comments...', color: 'blue' },
'comments.createComment': { text: 'Creating comment...', color: 'green' },
'comments.updateComment': { text: 'Updating comment...', color: 'yellow' },
'comments.deleteComment': { text: 'Deleting comment...', color: 'yellow' },
// Channel operations
'channels.getChannel': { text: 'Loading channel...', color: 'blue' },
'channels.getChannels': { text: 'Loading channels...', color: 'blue' },
'channels.createChannel': { text: 'Creating channel...', color: 'green' },
'channels.updateChannel': { text: 'Updating channel...', color: 'yellow' },
'channels.deleteChannel': { text: 'Deleting channel...', color: 'yellow' },
// Conversation operations
'conversations.getConversations': { text: 'Loading conversations...', color: 'blue' },
'conversations.getConversation': { text: 'Loading conversation...', color: 'blue' },
'conversations.getUnread': { text: 'Loading unread conversations...', color: 'blue' },
'conversations.createConversation': { text: 'Creating conversation...', color: 'green' },
'conversations.archiveConversation': { text: 'Archiving conversation...', color: 'yellow' },
'conversations.unarchiveConversation': {
text: 'Unarchiving conversation...',
color: 'yellow',
},
// Conversation message operations
'conversationMessages.getMessage': { text: 'Loading message...', color: 'blue' },
'conversationMessages.getMessages': { text: 'Loading messages...', color: 'blue' },
'conversationMessages.createMessage': { text: 'Sending message...', color: 'green' },
'conversationMessages.updateMessage': { text: 'Updating message...', color: 'yellow' },
'conversationMessages.deleteMessage': { text: 'Deleting message...', color: 'yellow' },
// Inbox operations
'inbox.getInbox': { text: 'Loading inbox...', color: 'blue' },
'inbox.archiveThread': { text: 'Archiving thread...', color: 'yellow' },
// Batch operations
batch: { text: 'Processing batch operations...', color: 'blue' },
}
function createSpinnerWrappedApi(api: TwistApi): TwistApi {
return new Proxy(api, {
get(target, property, receiver) {
const value = Reflect.get(target, property, receiver)
// If this is a nested object (like workspaces, users, etc.), wrap it too
if (
value &&
typeof value === 'object' &&
!Array.isArray(value) &&
typeof property === 'string'
) {
return createNestedSpinnerProxy(value, property)
}
return value
},
})
}
function createNestedSpinnerProxy<T extends object>(obj: T, basePath: string): T {
return new Proxy(obj, {
get(target, property, receiver) {
const originalMethod = Reflect.get(target, property, receiver)
if (typeof originalMethod !== 'function' || typeof property !== 'string') {
return originalMethod
}
const fullPath = `${basePath}.${property}`
const spinnerConfig = API_SPINNER_MESSAGES[fullPath]
const shouldCheckPermissions = isMutatingMethod(fullPath)
if (!spinnerConfig && !shouldCheckPermissions) {
return originalMethod
}
return <T extends unknown[]>(...args: T) => {
const progressTracker = getProgressTracker()
// Extract cursor from args for paginated methods
let cursor: string | null = null
if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {
const options = args[0] as Record<string, unknown>
if ('cursor' in options && typeof options.cursor === 'string') {
cursor = options.cursor
}
}
// Emit progress event for API call start
if (progressTracker.isEnabled()) {
progressTracker.emitApiCall(property, cursor)
}
// For mutating methods, check permissions before calling the API
if (shouldCheckPermissions) {
return ensureWriteAllowed().then(() => {
const result = originalMethod.apply(target, args)
return wrapResult(result, progressTracker, spinnerConfig)
})
}
const result = originalMethod.apply(target, args)
return wrapResult(result, progressTracker, spinnerConfig)
}
},
})
}
function wrapResult(
result: unknown,
progressTracker: ReturnType<typeof getProgressTracker>,
spinnerConfig: (typeof API_SPINNER_MESSAGES)[string] | undefined,
): unknown {
// If the method returns a non-thenable (e.g. batch request builder), return as-is
if (!result || typeof (result as { then?: unknown }).then !== 'function') {
return result
}
const wrappedPromise = (result as Promise<unknown>)
.then((response: unknown) => {
if (progressTracker.isEnabled()) {
analyzeAndEmitApiResponse(progressTracker, response)
}
return response
})
.catch((error: Error) => {
if (progressTracker.isEnabled()) {
progressTracker.emitError(error.name || 'API_ERROR', error.message)
}
throw error
})
if (spinnerConfig) {
return withSpinner(spinnerConfig, () => wrappedPromise)
}
return wrappedPromise
}
function analyzeAndEmitApiResponse(
progressTracker: ReturnType<typeof getProgressTracker>,
response: unknown,
): void {
// For paginated responses, extract metadata
if (response && typeof response === 'object' && response !== null) {
const resp = response as Record<string, unknown>
// Check if it's a paginated response with results array
if ('results' in resp && Array.isArray(resp.results)) {
progressTracker.emitApiResponse(
resp.results.length,
Boolean(resp.nextCursor),
typeof resp.nextCursor === 'string' ? resp.nextCursor : null,
)
return
}
// For array responses (legacy or simple lists)
if (Array.isArray(response)) {
progressTracker.emitApiResponse(response.length, false, null)
return
}
}
// For other responses, emit minimal info
progressTracker.emitApiResponse(1, false, null)
}
let apiClient: TwistApi | null = null
export async function getTwistClient(): Promise<TwistApi> {
if (!apiClient) {
const token = await getApiToken()
const rawApi = new TwistApi(token)
apiClient = createSpinnerWrappedApi(rawApi)
}
return apiClient
}
let workspaceCache: Workspace[] | null = null
let sessionUserCache: User | null = null
export async function fetchWorkspaces(): Promise<Workspace[]> {
if (workspaceCache) {
return workspaceCache
}
const client = await getTwistClient()
workspaceCache = await client.workspaces.getWorkspaces()
return workspaceCache
}
export function clearWorkspaceCache(): void {
workspaceCache = null
}
export async function getCurrentWorkspaceId(flagValue?: number): Promise<number> {
if (flagValue) {
return flagValue
}
const config = await getConfig()
if (config.currentWorkspace) {
return config.currentWorkspace
}
const sessionUser = await getSessionUser()
if (sessionUser.defaultWorkspace) {
await updateConfig({ currentWorkspace: sessionUser.defaultWorkspace })
return sessionUser.defaultWorkspace
}
const workspaces = await fetchWorkspaces()
if (workspaces.length === 0) {
throw new Error('No workspaces found for this user')
}
const defaultWorkspace = workspaces[0]
await updateConfig({ currentWorkspace: defaultWorkspace.id })
return defaultWorkspace.id
}
export async function getSessionUser(): Promise<User> {
if (sessionUserCache) {
return sessionUserCache
}
const client = await getTwistClient()
sessionUserCache = await client.users.getSessionUser()
return sessionUserCache
}
export async function getWorkspaceUsers(workspaceId: number): Promise<WorkspaceUser[]> {
const client = await getTwistClient()
return client.workspaceUsers.getWorkspaceUsers({ workspaceId })
}
export function clearUserCache(): void {
sessionUserCache = null
}
/**
* Validates a batch response and returns the data, throwing on errors.
* Also handles the case where the SDK fails to validate the response schema
* (e.g. when the batch API wraps entities in a key like `{comment: {...}}`).
* In that case, the raw transformed data is returned — check for expected fields.
*/
export function assertBatchData<T>(response: { code: number; data: T }, label: string): T {
if (response.code >= 400 || response.data == null) {
throw new Error(`Failed to fetch ${label}.`)
}
return response.data
}
export type { Workspace, WorkspaceUser, User }