@arbidocs/react 0.4.167 → 0.4.169

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 (99) hide show
  1. package/dist/artifacts/index.cjs +15 -12
  2. package/dist/artifacts/index.cjs.map +1 -1
  3. package/dist/artifacts/index.js +6 -3
  4. package/dist/artifacts/index.js.map +1 -1
  5. package/dist/calls/livekit/index.cjs +977 -0
  6. package/dist/calls/livekit/index.cjs.map +1 -0
  7. package/dist/calls/livekit/index.d.cts +280 -0
  8. package/dist/calls/livekit/index.d.ts +280 -0
  9. package/dist/calls/livekit/index.js +961 -0
  10. package/dist/calls/livekit/index.js.map +1 -0
  11. package/dist/{chunk-ON4PL6DQ.cjs → chunk-2M4B4FFA.cjs} +48 -4
  12. package/dist/chunk-2M4B4FFA.cjs.map +1 -0
  13. package/dist/chunk-3NVSUYUV.js +528 -0
  14. package/dist/chunk-3NVSUYUV.js.map +1 -0
  15. package/dist/{chunk-QJHCVQ6C.js → chunk-3WIBD44F.js} +4734 -4673
  16. package/dist/chunk-3WIBD44F.js.map +1 -0
  17. package/dist/chunk-5HDC43MF.js +145 -0
  18. package/dist/chunk-5HDC43MF.js.map +1 -0
  19. package/dist/{chunk-D66JCVBB.cjs → chunk-7NHOKV7N.cjs} +4093 -4040
  20. package/dist/chunk-7NHOKV7N.cjs.map +1 -0
  21. package/dist/chunk-7NY2J3TR.js +986 -0
  22. package/dist/chunk-7NY2J3TR.js.map +1 -0
  23. package/dist/chunk-APZZQZ6P.js +147 -0
  24. package/dist/chunk-APZZQZ6P.js.map +1 -0
  25. package/dist/{chunk-I5ZBQ63Y.js → chunk-DGMK3EUN.js} +188 -181
  26. package/dist/chunk-DGMK3EUN.js.map +1 -0
  27. package/dist/chunk-DPYBZDJB.js +18 -0
  28. package/dist/chunk-DPYBZDJB.js.map +1 -0
  29. package/dist/chunk-EEIYXVM4.cjs +181 -0
  30. package/dist/chunk-EEIYXVM4.cjs.map +1 -0
  31. package/dist/chunk-GGYCK5A6.cjs +1035 -0
  32. package/dist/chunk-GGYCK5A6.cjs.map +1 -0
  33. package/dist/{chunk-JSSKEXRR.js → chunk-KGCGA452.js} +2 -2
  34. package/dist/chunk-KGCGA452.js.map +1 -0
  35. package/dist/chunk-N73IMVFF.cjs +21 -0
  36. package/dist/chunk-N73IMVFF.cjs.map +1 -0
  37. package/dist/chunk-NVAIVJID.js +298 -0
  38. package/dist/chunk-NVAIVJID.js.map +1 -0
  39. package/dist/{chunk-GTJ667CP.cjs → chunk-QQ7SCJRY.cjs} +2 -2
  40. package/dist/chunk-QQ7SCJRY.cjs.map +1 -0
  41. package/dist/chunk-S4PCA3ES.cjs +572 -0
  42. package/dist/chunk-S4PCA3ES.cjs.map +1 -0
  43. package/dist/chunk-VAMPYLQ4.cjs +157 -0
  44. package/dist/chunk-VAMPYLQ4.cjs.map +1 -0
  45. package/dist/chunk-VLK52VXC.cjs +307 -0
  46. package/dist/chunk-VLK52VXC.cjs.map +1 -0
  47. package/dist/chunk-VPKFUYGW.cjs +2551 -0
  48. package/dist/chunk-VPKFUYGW.cjs.map +1 -0
  49. package/dist/chunk-W6DYNLA2.js +2362 -0
  50. package/dist/chunk-W6DYNLA2.js.map +1 -0
  51. package/dist/{chunk-SVHGCX25.js → chunk-YWYCEEBF.js} +43 -4
  52. package/dist/chunk-YWYCEEBF.js.map +1 -0
  53. package/dist/{chunk-EUC2BTNS.cjs → chunk-ZI2VJOID.cjs} +206 -199
  54. package/dist/chunk-ZI2VJOID.cjs.map +1 -0
  55. package/dist/document-tools/index.cjs +79 -107
  56. package/dist/document-tools/index.cjs.map +1 -1
  57. package/dist/document-tools/index.d.cts +4 -5
  58. package/dist/document-tools/index.d.ts +4 -5
  59. package/dist/document-tools/index.js +23 -68
  60. package/dist/document-tools/index.js.map +1 -1
  61. package/dist/index.cjs +12650 -9452
  62. package/dist/index.cjs.map +1 -1
  63. package/dist/{index.d-DfCFKora.d.cts → index.d-Bvp6rKNo.d.cts} +139 -1
  64. package/dist/{index.d-DfCFKora.d.ts → index.d-Bvp6rKNo.d.ts} +139 -1
  65. package/dist/{index.d-DCjYj7YK.d.ts → index.d-Dx9sGkW2.d.cts} +20 -8
  66. package/dist/{index.d-DCjYj7YK.d.cts → index.d-Dx9sGkW2.d.ts} +20 -8
  67. package/dist/index.d.cts +5465 -2291
  68. package/dist/index.d.ts +5465 -2291
  69. package/dist/index.js +11047 -8858
  70. package/dist/index.js.map +1 -1
  71. package/dist/query-keys.d-Kw0JMoff.d.cts +308 -0
  72. package/dist/query-keys.d-Kw0JMoff.d.ts +308 -0
  73. package/dist/shell/index.cjs +78 -21
  74. package/dist/shell/index.d.cts +1 -1
  75. package/dist/shell/index.d.ts +1 -1
  76. package/dist/shell/index.js +6 -1
  77. package/dist/ui/index.cjs +191 -186
  78. package/dist/ui/index.d.cts +1 -1
  79. package/dist/ui/index.d.ts +1 -1
  80. package/dist/ui/index.js +3 -2
  81. package/dist/useAudioRecorder.d-CWFDsb_S.d.cts +778 -0
  82. package/dist/useAudioRecorder.d-CWFDsb_S.d.ts +778 -0
  83. package/dist/viewers/index.cjs +22 -13
  84. package/dist/viewers/index.cjs.map +1 -1
  85. package/dist/viewers/index.js +21 -12
  86. package/dist/viewers/index.js.map +1 -1
  87. package/package.json +13 -3
  88. package/dist/chunk-6MTKKT2O.cjs +0 -999
  89. package/dist/chunk-6MTKKT2O.cjs.map +0 -1
  90. package/dist/chunk-CEZCFQ47.js +0 -932
  91. package/dist/chunk-CEZCFQ47.js.map +0 -1
  92. package/dist/chunk-D66JCVBB.cjs.map +0 -1
  93. package/dist/chunk-EUC2BTNS.cjs.map +0 -1
  94. package/dist/chunk-GTJ667CP.cjs.map +0 -1
  95. package/dist/chunk-I5ZBQ63Y.js.map +0 -1
  96. package/dist/chunk-JSSKEXRR.js.map +0 -1
  97. package/dist/chunk-ON4PL6DQ.cjs.map +0 -1
  98. package/dist/chunk-QJHCVQ6C.js.map +0 -1
  99. package/dist/chunk-SVHGCX25.js.map +0 -1
@@ -1,999 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkZWFMFOGP_cjs = require('./chunk-ZWFMFOGP.cjs');
4
- var chunkGTJ667CP_cjs = require('./chunk-GTJ667CP.cjs');
5
- var react = require('react');
6
- var reactQuery = require('@tanstack/react-query');
7
- var zustand = require('zustand');
8
- var browser = require('@arbidocs/sdk/browser');
9
-
10
- // src/usage-metered.ts
11
- function isUsageMetered(usage, subscription) {
12
- const empty = usage.total_spend === 0 && usage.total_tokens === 0 && usage.total_requests === 0;
13
- return !(empty && subscription === "dev");
14
- }
15
- var arbiQueryKeys = {
16
- workspaces: () => ["arbi", "workspaces"],
17
- /** Every workspace's member list: what a workspace switch drops. */
18
- allWorkspaceUsers: () => ["arbi", "workspaceUsers"],
19
- workspaceUsers: (workspaceId) => ["arbi", "workspaceUsers", workspaceId],
20
- /** Every workspace's documents list: the prefix a write patches when it does not know the workspace. */
21
- allDocuments: () => ["arbi", "documents"],
22
- documents: (workspaceId) => ["arbi", "documents", workspaceId],
23
- /** One document (a viewer's); writes keep it current next to the list. */
24
- document: (docId) => ["arbi", "document", docId],
25
- documentsById: (docIds) => ["arbi", "documentsById", [...docIds].sort().join(",")],
26
- /** Every workspace's near-duplicate pairs. */
27
- allSimilarDocuments: () => ["arbi", "similarDocuments"],
28
- similarDocuments: (workspaceId, threshold) => ["arbi", "similarDocuments", workspaceId, threshold],
29
- /** Every version list: the prefix a new version invalidates. */
30
- allDocumentVersions: () => ["arbi", "documentVersions"],
31
- documentVersions: (docId) => ["arbi", "documentVersions", docId],
32
- conversations: (workspaceId) => ["arbi", "conversations", workspaceId],
33
- /** Every workspace's conversation list (and threads): the prefix a conversation write invalidates. */
34
- allConversations: () => ["arbi", "conversations"],
35
- conversationThreads: (workspaceId, conversationId) => ["arbi", "conversations", workspaceId, "threads", conversationId],
36
- /** Every workspace's tags (lists, tables and kinds): what a cross-workspace change refreshes. */
37
- allTags: () => ["arbi", "tags"],
38
- tags: (workspaceId) => ["arbi", "tags", workspaceId],
39
- /** Under the workspace's tags: the kinds' fields (refreshed with the tags). */
40
- tagKinds: (workspaceId) => ["arbi", "tags", workspaceId, "kinds"],
41
- /** Every filtered list (a table of tags): what a tag write refreshes, the whole list aside. */
42
- tagLists: (workspaceId) => ["arbi", "tags", workspaceId, "list"],
43
- /** Under the workspace's tags: a tag, doctag or fact write that invalidates `tags` refreshes it. */
44
- tagList: (workspaceId, query) => ["arbi", "tags", workspaceId, "list", query],
45
- /** A kind's fields, under the workspace's tags. */
46
- tagKind: (workspaceId, kind) => ["arbi", "tags", workspaceId, "kind", kind],
47
- /** A task's history, under the conversations prefix: every conversation write refreshes it. */
48
- conversationActivity: (conversationId) => ["arbi", "conversations", conversationId, "activity"],
49
- /** Under the conversations prefix: every step action or conversation write refreshes it. */
50
- conversationUsage: (conversationId) => ["arbi", "conversations", conversationId, "usage"],
51
- thumbnails: (docIds) => ["arbi", "thumbnails", [...docIds].sort().join(",")],
52
- /** Every stage of a document's parsed content. */
53
- parsedDocument: (docId) => ["arbi", "parsedDoc", docId],
54
- parsedDoc: (docId, stage) => ["arbi", "parsedDoc", docId, stage],
55
- agents: () => ["arbi", "agents"],
56
- sessions: () => ["arbi", "sessions"],
57
- health: () => ["arbi", "health"],
58
- workflows: () => ["arbi", "workflows"],
59
- /** Under `workflows()`: a workflow write or run refreshes its runs too. */
60
- workflowRuns: (workflowId) => ["arbi", "workflows", workflowId, "runs"],
61
- /** Every workspace's facts: the prefix a fact write invalidates. */
62
- allFacts: () => ["arbi", "facts"],
63
- facts: (workspaceId) => ["arbi", "facts", workspaceId],
64
- configs: () => ["arbi", "configs"],
65
- activity: () => ["arbi", "activity"],
66
- /** A workspace's activity feed (all its pages). */
67
- workspaceActivity: (workspaceId) => ["arbi", "workspaceActivity", workspaceId],
68
- projects: () => ["arbi", "projects"],
69
- /** A filtered project list, under `projects()`. */
70
- projectsFiltered: (stage, leadUser) => ["arbi", "projects", "list", stage ?? "", leadUser ?? ""],
71
- /** Under `projects()`: a project update refreshes its events too. */
72
- projectEvents: (projectExtId) => ["arbi", "projects", projectExtId, "events"],
73
- projectUsage: (projectExtId, monthsBack) => ["arbi", "projectUsage", projectExtId, monthsBack],
74
- projectConversationUsage: (projectExtId, monthsBack) => ["arbi", "projectUsage", projectExtId, "byConversation", monthsBack],
75
- projectInvoices: (projectExtId) => ["arbi", "projectInvoices", projectExtId],
76
- /** The plans and add-ons on sale. */
77
- products: () => ["arbi", "products"],
78
- /** Prices of a purchase or a change (quotes, previews); nothing is bought. */
79
- billingQuotes: () => ["arbi", "billingQuote"],
80
- userUsageToday: () => ["arbi", "userUsageToday"],
81
- currentUser: () => ["arbi", "currentUser"],
82
- firmPool: () => ["arbi", "firmPool"],
83
- contacts: () => ["arbi", "contacts"],
84
- /** Every chat query (the list and each open thread). */
85
- chats: () => ["arbi", "chats"],
86
- /** My chats, raw (titles and last messages are ciphertext), most recently active first. */
87
- chatList: () => ["arbi", "chats", "list"],
88
- /** One thread's loaded messages, decrypted, oldest first (`ChatThreadData`). */
89
- chatThread: (chatExtId) => ["arbi", "chats", "thread", chatExtId],
90
- /** My own agent's progress on my last message to it (`agent_dm_status`), per agent. */
91
- agentDmStatus: (agentExtId) => ["arbi", "chats", "agentStatus", agentExtId],
92
- /** The paid features this person may use (`/v1/user/entitlements`). */
93
- entitlements: () => ["arbi", "entitlements"],
94
- skills: () => ["arbi", "skills"],
95
- /** A skill's main file (SKILL.md), as text. */
96
- skillSource: (docExtId) => ["arbi", "skills", "source", docExtId],
97
- /** An agent's pinned config; `undefined` = the library default config. */
98
- agentConfig: (agentExtId) => ["arbi", "agentConfig", agentExtId ?? "default"],
99
- agentWorkspaces: (agentExtId) => ["arbi", "agentWorkspaces", agentExtId],
100
- /** An agent's own login, polled while its controls are open. */
101
- agentSession: (agentExtId) => ["arbi", "agentSession", agentExtId],
102
- agentChats: (agentExtId) => ["arbi", "agentChats", agentExtId],
103
- authorizeLimits: () => ["arbi", "authorizeLimits"],
104
- mcpTools: () => ["arbi", "mcpTools"],
105
- models: () => ["arbi", "models"],
106
- availableModels: () => ["arbi", "availableModels"],
107
- /** The signed-in user's own profile (name, picture, email). */
108
- profile: () => ["arbi", "profile"],
109
- identity: () => ["arbi", "identity"],
110
- /** The signed-in user's settings record (notification preferences, flags). */
111
- userSettings: () => ["arbi", "userSettings"],
112
- /** Every notification list: the prefix a delete, a read receipt or an arrival invalidates. */
113
- allNotifications: () => ["arbi", "notifications"],
114
- /** The newest `limit` notifications, received and sent. */
115
- notifications: (limit) => ["arbi", "notifications", limit],
116
- /** The documents a workspace may use as its Word house template. */
117
- houseTemplateCandidates: (workspaceId) => ["arbi", "houseTemplateCandidates", workspaceId]
118
- };
119
- var arbiMutationKeys = {
120
- /** A member's role changed. */
121
- setWorkspaceMemberRoles: () => ["arbi", "workspaces", "roles"],
122
- runWorkflow: () => ["arbi", "workflows", "run"],
123
- updateTagKindSchema: () => ["arbi", "tags", "kinds", "update"],
124
- createTag: () => ["arbi", "tags", "create"],
125
- updateTag: () => ["arbi", "tags", "update"],
126
- deleteTag: () => ["arbi", "tags", "delete"],
127
- extractEntities: () => ["arbi", "tags", "entities", "extract"],
128
- updateDocuments: () => ["arbi", "documents", "update"],
129
- deleteDocuments: () => ["arbi", "documents", "delete"],
130
- uploadDocuments: () => ["arbi", "documents", "upload"],
131
- uploadUrls: () => ["arbi", "documents", "uploadUrls"],
132
- assignDocTags: () => ["arbi", "doctags", "assign"],
133
- removeDocTags: () => ["arbi", "doctags", "remove"],
134
- updateDocTag: () => ["arbi", "doctags", "update"],
135
- generateDocTags: () => ["arbi", "doctags", "generate"],
136
- /** Members added to or removed from a workspace (leaving included). */
137
- workspaceMembership: () => ["arbi", "workspaces", "members"]
138
- };
139
- function useWorkspaces(options) {
140
- const arbi = chunkGTJ667CP_cjs.useArbi();
141
- return reactQuery.useQuery({
142
- queryKey: arbiQueryKeys.workspaces(),
143
- queryFn: () => arbi.workspaces.list(),
144
- enabled: options?.enabled ?? arbi.isLoggedIn
145
- });
146
- }
147
- function useDocumentVersionList(docId, options) {
148
- const arbi = chunkGTJ667CP_cjs.useArbi();
149
- return reactQuery.useQuery({
150
- queryKey: arbiQueryKeys.documentVersions(docId ?? ""),
151
- queryFn: () => arbi.documents.versions(docId),
152
- enabled: (options?.enabled ?? true) && !!docId && arbi.hasWorkspace
153
- });
154
- }
155
- function useConversations(workspaceId, options) {
156
- const arbi = chunkGTJ667CP_cjs.useArbi();
157
- return reactQuery.useQuery({
158
- queryKey: arbiQueryKeys.conversations(workspaceId ?? ""),
159
- queryFn: () => arbi.conversations.list(),
160
- enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,
161
- refetchInterval: options?.live ? (query) => query.state.data?.some((conversation) => conversation.status === "generating") ? 3e3 : 15e3 : false
162
- });
163
- }
164
- function useConversationThreads(workspaceId, conversationId, options) {
165
- const arbi = chunkGTJ667CP_cjs.useArbi();
166
- return reactQuery.useQuery({
167
- queryKey: arbiQueryKeys.conversationThreads(workspaceId ?? "", conversationId ?? ""),
168
- queryFn: () => arbi.conversations.getThreads(conversationId),
169
- enabled: (options?.enabled ?? true) && !!workspaceId && !!conversationId && arbi.hasWorkspace,
170
- gcTime: 0,
171
- refetchInterval: options?.live ? 3e3 : false
172
- });
173
- }
174
- var tagListKey = (query) => [
175
- query.kind ? `kind:${query.kind}` : "",
176
- query.parentId ? `parent:${query.parentId}` : "",
177
- query.ids?.length ? `ids:${query.ids.join(",")}` : "",
178
- query.include?.length ? `include:${query.include.join(",")}` : "",
179
- query.linksLimit !== void 0 ? `links:${query.linksLimit}` : ""
180
- ].filter(Boolean).join("|");
181
- function useTags(workspaceId, options) {
182
- const arbi = chunkGTJ667CP_cjs.useArbi();
183
- const { enabled, ...query } = options ?? {};
184
- const workspace = workspaceId ?? (arbi.hasWorkspace ? arbi.getWorkspaceId() : "");
185
- const key = tagListKey(query);
186
- return reactQuery.useQuery({
187
- queryKey: key ? arbiQueryKeys.tagList(workspace, key) : arbiQueryKeys.tags(workspace),
188
- queryFn: () => arbi.tags.list(key ? query : void 0),
189
- enabled: (enabled ?? true) && !!workspace && arbi.hasWorkspace && (query.ids === void 0 || query.ids.length > 0),
190
- ...key ? {} : { staleTime: Infinity }
191
- });
192
- }
193
- function useThumbnails(docIds, options) {
194
- const arbi = chunkGTJ667CP_cjs.useArbi();
195
- return reactQuery.useQuery({
196
- queryKey: arbiQueryKeys.thumbnails(docIds),
197
- queryFn: () => arbi.documents.getThumbnails(docIds),
198
- enabled: (options?.enabled ?? true) && docIds.length > 0 && arbi.hasWorkspace,
199
- staleTime: 5 * 6e4
200
- });
201
- }
202
- function useParsedDocument(docId, stage = "final", options) {
203
- const arbi = chunkGTJ667CP_cjs.useArbi();
204
- return reactQuery.useQuery({
205
- queryKey: arbiQueryKeys.parsedDoc(docId ?? "", stage),
206
- queryFn: () => {
207
- const { docId: id, version } = chunkZWFMFOGP_cjs.parseVersionRef(docId);
208
- return arbi.documents.getParsedContent(
209
- id,
210
- stage,
211
- version ?? void 0
212
- );
213
- },
214
- enabled: (options?.enabled ?? true) && !!docId && arbi.hasWorkspace
215
- });
216
- }
217
- function useAssistantQuery() {
218
- const arbi = chunkGTJ667CP_cjs.useArbi();
219
- return reactQuery.useMutation({
220
- mutationFn: ({ question, ...options }) => arbi.assistant.query(question, options)
221
- });
222
- }
223
- function useAgents(options) {
224
- const arbi = chunkGTJ667CP_cjs.useArbi();
225
- return reactQuery.useQuery({
226
- queryKey: arbiQueryKeys.agents(),
227
- queryFn: () => arbi.agents.list(),
228
- enabled: (options?.enabled ?? true) && arbi.isLoggedIn
229
- });
230
- }
231
- function useDeleteAgents() {
232
- const arbi = chunkGTJ667CP_cjs.useArbi();
233
- const qc = reactQuery.useQueryClient();
234
- return reactQuery.useMutation({
235
- mutationFn: ({ agentExtIds }) => arbi.agents.delete(agentExtIds),
236
- onSuccess: (_result, { agentExtIds }) => {
237
- for (const id of agentExtIds) {
238
- qc.removeQueries({ queryKey: arbiQueryKeys.agentConfig(id) });
239
- qc.removeQueries({ queryKey: arbiQueryKeys.agentWorkspaces(id) });
240
- }
241
- return Promise.all([
242
- qc.invalidateQueries({ queryKey: arbiQueryKeys.agents() }),
243
- qc.invalidateQueries({ queryKey: arbiQueryKeys.workflows() }),
244
- qc.invalidateQueries({ queryKey: arbiQueryKeys.allConversations() }),
245
- qc.invalidateQueries({ queryKey: arbiQueryKeys.configs() })
246
- ]);
247
- }
248
- });
249
- }
250
- function useHealth(options) {
251
- const arbi = chunkGTJ667CP_cjs.useArbi();
252
- return reactQuery.useQuery({
253
- queryKey: arbiQueryKeys.health(),
254
- queryFn: () => arbi.health.check(),
255
- enabled: options?.enabled
256
- });
257
- }
258
- function useAvailableModels(options) {
259
- const arbi = chunkGTJ667CP_cjs.useArbi();
260
- return reactQuery.useQuery({
261
- queryKey: arbiQueryKeys.availableModels(),
262
- queryFn: () => arbi.health.models(),
263
- staleTime: Infinity,
264
- enabled: (options?.enabled ?? true) && arbi.isLoggedIn
265
- });
266
- }
267
- function useConfigs(options) {
268
- const arbi = chunkGTJ667CP_cjs.useArbi();
269
- return reactQuery.useQuery({
270
- queryKey: arbiQueryKeys.configs(),
271
- queryFn: () => arbi.agentConfig.list(),
272
- enabled: options?.enabled ?? arbi.isLoggedIn
273
- });
274
- }
275
- function useActivity(options) {
276
- const arbi = chunkGTJ667CP_cjs.useArbi();
277
- return reactQuery.useQuery({
278
- queryKey: arbiQueryKeys.activity(),
279
- queryFn: () => arbi.dm.listActivity({ limit: options?.limit, offset: options?.offset }),
280
- enabled: options?.enabled ?? arbi.isLoggedIn
281
- });
282
- }
283
- function useWorkspaceActivity(workspaceId, options) {
284
- const arbi = chunkGTJ667CP_cjs.useArbi();
285
- return reactQuery.useInfiniteQuery({
286
- queryKey: arbiQueryKeys.workspaceActivity(workspaceId ?? ""),
287
- queryFn: async ({ pageParam }) => {
288
- await options?.beforeFetch?.();
289
- return arbi.workspaces.activity(workspaceId, {
290
- cursor: pageParam,
291
- limit: options?.limit
292
- });
293
- },
294
- initialPageParam: null,
295
- getNextPageParam: (page) => page.next_cursor ?? void 0,
296
- enabled: (options?.enabled ?? true) && !!workspaceId && arbi.isLoggedIn
297
- });
298
- }
299
- function useProjects(options) {
300
- const arbi = chunkGTJ667CP_cjs.useArbi();
301
- return reactQuery.useQuery({
302
- queryKey: arbiQueryKeys.projects(),
303
- queryFn: () => arbi.projects.list(),
304
- enabled: options?.enabled ?? arbi.isLoggedIn
305
- });
306
- }
307
- function useProjectUsage(projectExtId, monthsBack = 0, options) {
308
- const arbi = chunkGTJ667CP_cjs.useArbi();
309
- const usage = reactQuery.useQuery({
310
- queryKey: arbiQueryKeys.projectUsage(projectExtId ?? "", monthsBack),
311
- queryFn: () => arbi.projects.usage(projectExtId, monthsBack),
312
- enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn
313
- });
314
- const projects = useProjects({ enabled: !!projectExtId && (options?.enabled ?? true) });
315
- const subscription = projects.data?.find((p) => p.external_id === projectExtId)?.subscription;
316
- const metered = usage.data ? isUsageMetered(usage.data, subscription) : void 0;
317
- return { ...usage, metered };
318
- }
319
- function useProjectsUsage(projectExtIds, monthsBack = 0, options) {
320
- const arbi = chunkGTJ667CP_cjs.useArbi();
321
- const enabled = (options?.enabled ?? true) && arbi.isLoggedIn;
322
- const projects = useProjects({ enabled: enabled && projectExtIds.length > 0 });
323
- const results = reactQuery.useQueries({
324
- queries: projectExtIds.map((id) => ({
325
- queryKey: arbiQueryKeys.projectUsage(id, monthsBack),
326
- queryFn: () => arbi.projects.usage(id, monthsBack),
327
- enabled: enabled && !!id
328
- }))
329
- });
330
- const signature = results.map((r) => `${r.status}:${r.dataUpdatedAt ?? 0}`).join("|") + `#${projects.dataUpdatedAt}`;
331
- return react.useMemo(() => {
332
- const dailyMap = /* @__PURE__ */ new Map();
333
- const modelMap = /* @__PURE__ */ new Map();
334
- let totalGbp = 0;
335
- let anyData = false;
336
- let anyMetered = false;
337
- let totalTokens = 0;
338
- let totalRequests = 0;
339
- results.forEach((r, i) => {
340
- const d = r.data;
341
- if (!d) return;
342
- anyData = true;
343
- const subscription = projects.data?.find(
344
- (p) => p.external_id === projectExtIds[i]
345
- )?.subscription;
346
- if (isUsageMetered(d, subscription)) anyMetered = true;
347
- totalGbp += d.total_spend ?? 0;
348
- totalTokens += d.total_tokens ?? 0;
349
- totalRequests += d.total_requests ?? 0;
350
- for (const day of d.daily ?? []) {
351
- const cur = dailyMap.get(day.date) ?? {
352
- date: day.date,
353
- gbp: 0,
354
- totalTokens: 0,
355
- apiRequests: 0
356
- };
357
- cur.gbp += day.spend ?? 0;
358
- cur.totalTokens += day.total_tokens ?? 0;
359
- cur.apiRequests += day.api_requests ?? 0;
360
- dailyMap.set(day.date, cur);
361
- }
362
- for (const [model, mg] of Object.entries(d.model_groups ?? {})) {
363
- const cur = modelMap.get(model) ?? {
364
- model,
365
- gbp: 0,
366
- totalTokens: 0,
367
- promptTokens: 0,
368
- completionTokens: 0,
369
- successfulRequests: 0
370
- };
371
- cur.gbp += mg.spend ?? 0;
372
- cur.totalTokens += mg.total_tokens ?? 0;
373
- cur.promptTokens += mg.prompt_tokens ?? 0;
374
- cur.completionTokens += mg.completion_tokens ?? 0;
375
- cur.successfulRequests += mg.successful_requests ?? 0;
376
- modelMap.set(model, cur);
377
- }
378
- });
379
- return {
380
- totalGbp,
381
- totalTokens,
382
- totalRequests,
383
- daily: [...dailyMap.values()].sort((a, b) => a.date.localeCompare(b.date)),
384
- modelGroups: [...modelMap.values()].sort(
385
- (a, b) => b.gbp - a.gbp || b.totalTokens - a.totalTokens
386
- ),
387
- metered: !anyData || anyMetered,
388
- isLoading: results.some((r) => r.isLoading),
389
- isError: results.some((r) => r.isError)
390
- };
391
- }, [signature]);
392
- }
393
- function useProjectInvoices(projectExtId, options) {
394
- const arbi = chunkGTJ667CP_cjs.useArbi();
395
- return reactQuery.useQuery({
396
- queryKey: arbiQueryKeys.projectInvoices(projectExtId ?? ""),
397
- queryFn: () => arbi.projects.invoices(projectExtId),
398
- enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn
399
- });
400
- }
401
- function useCurrentUser(options) {
402
- const arbi = chunkGTJ667CP_cjs.useArbi();
403
- return reactQuery.useQuery({
404
- queryKey: arbiQueryKeys.currentUser(),
405
- queryFn: () => arbi.user.me(),
406
- enabled: options?.enabled ?? arbi.isLoggedIn,
407
- refetchOnWindowFocus: true,
408
- staleTime: 3e4
409
- });
410
- }
411
- function useFirmPool(options) {
412
- const arbi = chunkGTJ667CP_cjs.useArbi();
413
- return reactQuery.useQuery({
414
- queryKey: arbiQueryKeys.firmPool(),
415
- queryFn: () => arbi.firm.pool(),
416
- enabled: options?.enabled ?? arbi.isLoggedIn,
417
- retry: false,
418
- refetchOnWindowFocus: true,
419
- staleTime: 6e4
420
- });
421
- }
422
- function useTopUpFirmPool() {
423
- const arbi = chunkGTJ667CP_cjs.useArbi();
424
- const queryClient = reactQuery.useQueryClient();
425
- return reactQuery.useMutation({
426
- mutationFn: (aiAddons) => arbi.firm.topUp(aiAddons),
427
- onSuccess: (result) => {
428
- queryClient.setQueryData(arbiQueryKeys.firmPool(), result.pool);
429
- }
430
- });
431
- }
432
- var PROJECT_CREATION_DENIED_REASON = "Only members of your firm can create projects and workspaces.";
433
- function useCanCreateProjects() {
434
- const user = useCurrentUser();
435
- const { data: workspaces } = useWorkspaces({ enabled: user.isSuccess });
436
- const membership = workspaces?.map((w) => w.external_id).join(",");
437
- const { refetch } = user;
438
- const seen = react.useRef(void 0);
439
- react.useEffect(() => {
440
- if (membership === void 0 || membership === seen.current) return;
441
- const first = seen.current === void 0;
442
- seen.current = membership;
443
- if (!first) void refetch();
444
- }, [membership, refetch]);
445
- return user.data?.can_create_projects;
446
- }
447
- function useUserUsageToday(options) {
448
- const arbi = chunkGTJ667CP_cjs.useArbi();
449
- return reactQuery.useQuery({
450
- queryKey: arbiQueryKeys.userUsageToday(),
451
- queryFn: () => arbi.user.usageToday(),
452
- enabled: (options?.enabled ?? true) && arbi.isLoggedIn,
453
- refetchOnWindowFocus: true,
454
- refetchOnMount: "always",
455
- staleTime: 15e3
456
- });
457
- }
458
-
459
- // src/documents/documents-cache.ts
460
- var rowListeners = /* @__PURE__ */ new Set();
461
- function subscribeDocumentRows(listener) {
462
- rowListeners.add(listener);
463
- return () => {
464
- rowListeners.delete(listener);
465
- };
466
- }
467
- function getCachedDocuments(qc, workspaceId) {
468
- if (!workspaceId) return void 0;
469
- return qc.getQueryData(arbiQueryKeys.documents(workspaceId));
470
- }
471
- function cachedLists(qc) {
472
- return qc.getQueriesData({ queryKey: arbiQueryKeys.allDocuments() }).flatMap(
473
- ([key, data]) => typeof key[2] === "string" && Array.isArray(data) ? [[key[2], data]] : []
474
- );
475
- }
476
- function diffRows(workspaceId, before, after) {
477
- const beforeById = new Map(before.map((doc) => [doc.external_id, doc]));
478
- const add = [];
479
- const update2 = [];
480
- const seen = /* @__PURE__ */ new Set();
481
- for (const doc of after) {
482
- seen.add(doc.external_id);
483
- const previous = beforeById.get(doc.external_id);
484
- if (!previous) add.push(doc);
485
- else if (previous !== doc) update2.push(doc);
486
- }
487
- const remove = [...beforeById.keys()].filter((id) => !seen.has(id));
488
- return { workspaceId, add, update: update2, remove };
489
- }
490
- function patchDocuments(qc, reducer, workspaceId) {
491
- const lists = workspaceId ? (() => {
492
- const current = getCachedDocuments(qc, workspaceId);
493
- return current ? [[workspaceId, current]] : [];
494
- })() : cachedLists(qc);
495
- for (const [id, before] of lists) {
496
- const after = reducer(before);
497
- if (after === before) continue;
498
- qc.setQueryData(arbiQueryKeys.documents(id), after);
499
- const change = diffRows(id, before, after);
500
- const beforeById = new Map(before.map((doc) => [doc.external_id, doc]));
501
- if (change.update.some(
502
- (doc) => doc.current_version !== beforeById.get(doc.external_id)?.current_version
503
- ))
504
- void qc.invalidateQueries({ queryKey: arbiQueryKeys.allDocumentVersions() });
505
- if (change.add.length || change.update.length || change.remove.length)
506
- for (const listener of rowListeners) listener(change);
507
- }
508
- }
509
- function upsertDocuments(qc, documents, workspaceId) {
510
- if (!documents.length) return;
511
- const byId = new Map(documents.map((doc) => [doc.external_id, doc]));
512
- const byWorkspace = /* @__PURE__ */ new Map();
513
- for (const doc of documents) {
514
- const ws = workspaceId ?? doc.workspace_ext_id;
515
- byWorkspace.set(ws, [...byWorkspace.get(ws) ?? [], doc]);
516
- }
517
- for (const [ws, incoming] of byWorkspace) {
518
- patchDocuments(
519
- qc,
520
- (old) => {
521
- const known = new Set(old.map((doc) => doc.external_id));
522
- return [
523
- ...old.map((doc) => byId.get(doc.external_id) ?? doc),
524
- ...incoming.filter((doc) => !known.has(doc.external_id))
525
- ];
526
- },
527
- ws
528
- );
529
- }
530
- }
531
- function setCachedDocument(qc, doc) {
532
- qc.setQueryData(arbiQueryKeys.document(doc.external_id), doc);
533
- }
534
- function patchCachedDocument(qc, docId, reducer) {
535
- const current = qc.getQueryData(arbiQueryKeys.document(docId));
536
- if (current) qc.setQueryData(arbiQueryKeys.document(docId), reducer(current));
537
- }
538
- function dropTagFromCachedDocuments(qc, tagId) {
539
- const strip = (doc) => {
540
- const doctags = doc.doctags?.filter((dt) => dt.tag_ext_id !== tagId);
541
- return doctags && doctags.length !== doc.doctags?.length ? { ...doc, doctags } : doc;
542
- };
543
- const carriers = [];
544
- patchDocuments(qc, (docs) => {
545
- const next = docs.map(strip);
546
- next.forEach((doc, i) => doc !== docs[i] && carriers.push(doc.external_id));
547
- return carriers.length ? next : docs;
548
- });
549
- for (const id of carriers) patchCachedDocument(qc, id, strip);
550
- }
551
- function forgetDocuments(qc, docIds) {
552
- for (const id of docIds) {
553
- qc.removeQueries({ queryKey: arbiQueryKeys.document(id) });
554
- qc.removeQueries({ queryKey: arbiQueryKeys.documentVersions(id) });
555
- qc.removeQueries({ queryKey: arbiQueryKeys.parsedDocument(id) });
556
- }
557
- }
558
- var useEntityExtractionStore = zustand.create(() => ({ docIds: [] }));
559
- function update(docIds, running) {
560
- if (!docIds.length) return;
561
- useEntityExtractionStore.setState((state) => {
562
- const ids = new Set(state.docIds);
563
- docIds.forEach((id) => running ? ids.add(id) : ids.delete(id));
564
- return { docIds: [...ids] };
565
- });
566
- }
567
- function startEntityExtraction(docIds) {
568
- update(docIds, true);
569
- }
570
- function finishEntityExtraction(docIds) {
571
- update(docIds, false);
572
- }
573
- function useEntityExtractionDocIds() {
574
- return useEntityExtractionStore((state) => state.docIds);
575
- }
576
- function openWorkspaceId(arbi) {
577
- return arbi.hasWorkspace ? arbi.getWorkspaceId() : null;
578
- }
579
- function patchWorkspaceTags(qc, workspaceId, reducer) {
580
- const key = arbiQueryKeys.tags(workspaceId);
581
- const current = qc.getQueryData(key);
582
- if (!current) return;
583
- const next = reducer(current);
584
- if (next !== current) qc.setQueryData(key, next);
585
- }
586
- function invalidateTagTables(qc, workspaceId) {
587
- return qc.invalidateQueries({ queryKey: arbiQueryKeys.tagLists(workspaceId) });
588
- }
589
- function invalidateTagData(qc, workspaceId) {
590
- return Promise.all([
591
- qc.invalidateQueries({ queryKey: arbiQueryKeys.tags(workspaceId) }),
592
- qc.invalidateQueries({ queryKey: arbiQueryKeys.facts(workspaceId) })
593
- ]);
594
- }
595
- function useInvalidateTagData() {
596
- const arbi = chunkGTJ667CP_cjs.useArbi();
597
- const qc = reactQuery.useQueryClient();
598
- return react.useCallback(() => {
599
- const workspaceId = openWorkspaceId(arbi);
600
- return workspaceId ? invalidateTagData(qc, workspaceId) : Promise.resolve();
601
- }, [arbi, qc]);
602
- }
603
- function settleCreatedTag(qc, created) {
604
- const workspaceId = created.workspace_ext_id;
605
- patchWorkspaceTags(
606
- qc,
607
- workspaceId,
608
- (old) => old.some((t) => t.external_id === created.external_id) ? old : [...old, created]
609
- );
610
- return invalidateTagTables(qc, workspaceId);
611
- }
612
- function settleChangedTag(qc, tag) {
613
- const workspaceId = tag.workspace_ext_id;
614
- patchWorkspaceTags(
615
- qc,
616
- workspaceId,
617
- (old) => old.map((t) => t.external_id === tag.external_id ? { ...t, ...tag } : t)
618
- );
619
- return invalidateTagTables(qc, workspaceId);
620
- }
621
- var replayableTagMutations = [
622
- {
623
- mutationKey: arbiMutationKeys.createTag(),
624
- run: (client, input) => browser.tags.createTag(client, input),
625
- settle: (qc, created) => settleCreatedTag(qc, created)
626
- }
627
- ];
628
- function useCreateTag() {
629
- const arbi = chunkGTJ667CP_cjs.useArbi();
630
- const qc = reactQuery.useQueryClient();
631
- return reactQuery.useMutation({
632
- mutationKey: arbiMutationKeys.createTag(),
633
- mutationFn: (input) => arbi.tags.create(input),
634
- onSuccess: (created) => settleCreatedTag(qc, created)
635
- });
636
- }
637
- function useIsCreatingTag() {
638
- const qc = reactQuery.useQueryClient();
639
- return react.useCallback(
640
- (name) => {
641
- const wanted = name.trim().toLowerCase();
642
- return qc.getMutationCache().findAll({
643
- mutationKey: arbiMutationKeys.createTag(),
644
- predicate: (m) => m.state.status === "pending" && m.state.variables?.name.trim().toLowerCase() === wanted
645
- }).length > 0;
646
- },
647
- [qc]
648
- );
649
- }
650
- function useUpdateTag() {
651
- const arbi = chunkGTJ667CP_cjs.useArbi();
652
- const qc = reactQuery.useQueryClient();
653
- return reactQuery.useMutation({
654
- mutationKey: arbiMutationKeys.updateTag(),
655
- mutationFn: ({ tagId, change }) => arbi.tags.update(tagId, change),
656
- onSuccess: (tag) => settleChangedTag(qc, tag)
657
- });
658
- }
659
- function useSetTagValues() {
660
- const arbi = chunkGTJ667CP_cjs.useArbi();
661
- const qc = reactQuery.useQueryClient();
662
- return reactQuery.useMutation({
663
- mutationKey: arbiMutationKeys.updateTag(),
664
- mutationFn: ({
665
- tagId,
666
- values
667
- }) => arbi.tags.setValues(tagId, values),
668
- onSuccess: (tag) => settleChangedTag(qc, tag)
669
- });
670
- }
671
- function useDeleteTag() {
672
- const arbi = chunkGTJ667CP_cjs.useArbi();
673
- const qc = reactQuery.useQueryClient();
674
- return reactQuery.useMutation({
675
- mutationKey: arbiMutationKeys.deleteTag(),
676
- mutationFn: (tagId) => arbi.tags.delete(tagId),
677
- onSuccess: (_data, tagId) => {
678
- dropTagFromCachedDocuments(qc, tagId);
679
- const workspaceId = openWorkspaceId(arbi);
680
- if (!workspaceId) return;
681
- patchWorkspaceTags(
682
- qc,
683
- workspaceId,
684
- (old) => old.filter((t) => t.external_id !== tagId).map((t) => t.parent_ext_id === tagId ? { ...t, parent_ext_id: null } : t)
685
- );
686
- return Promise.all([
687
- invalidateTagTables(qc, workspaceId),
688
- qc.invalidateQueries({ queryKey: arbiQueryKeys.facts(workspaceId) })
689
- ]);
690
- }
691
- });
692
- }
693
- function useExtractEntities() {
694
- const arbi = chunkGTJ667CP_cjs.useArbi();
695
- return reactQuery.useMutation({
696
- mutationKey: arbiMutationKeys.extractEntities(),
697
- mutationFn: (docIds) => arbi.tags.extractEntities(docIds),
698
- onSuccess: (data) => startEntityExtraction(data.doc_ext_ids)
699
- });
700
- }
701
- function useTagKindSchema(kind, options) {
702
- const arbi = chunkGTJ667CP_cjs.useArbi();
703
- const workspaceId = openWorkspaceId(arbi) ?? "";
704
- return reactQuery.useQuery({
705
- queryKey: arbiQueryKeys.tagKind(workspaceId, kind ?? ""),
706
- queryFn: () => arbi.tagKinds.get(kind),
707
- enabled: (options?.enabled ?? true) && !!kind && !!workspaceId
708
- });
709
- }
710
- function useUpdateTagKindSchema() {
711
- const arbi = chunkGTJ667CP_cjs.useArbi();
712
- const qc = reactQuery.useQueryClient();
713
- return reactQuery.useMutation({
714
- mutationKey: arbiMutationKeys.updateTagKindSchema(),
715
- mutationFn: ({
716
- kind,
717
- fields
718
- }) => arbi.tagKinds.update(kind, fields),
719
- onSuccess: (schema) => {
720
- const workspaceId = openWorkspaceId(arbi);
721
- if (!workspaceId) return;
722
- qc.setQueryData(arbiQueryKeys.tagKind(workspaceId, schema.kind), schema);
723
- return invalidateTagData(qc, workspaceId);
724
- }
725
- });
726
- }
727
- var DOCUMENTS_FIRST_PAGE_SIZE = 500;
728
- var DOCUMENTS_PAGE_SIZE = 2e3;
729
- var DOCUMENTS_FIRST_PAGE_MEASURE = "arbi:document-list:page1";
730
- var FIRST_PAGE_MEASURE = DOCUMENTS_FIRST_PAGE_MEASURE;
731
- var FIRST_PAGE_START = "arbi:document-list:start";
732
- function mark(name) {
733
- try {
734
- performance.mark(name);
735
- } catch {
736
- }
737
- }
738
- function measure(name, start) {
739
- try {
740
- performance.measure(name, start);
741
- } catch {
742
- }
743
- }
744
- var backgroundReads = /* @__PURE__ */ new Map();
745
- var loadingListeners = /* @__PURE__ */ new Set();
746
- function emitLoading() {
747
- for (const listener of loadingListeners) listener();
748
- }
749
- function subscribeLoading(listener) {
750
- loadingListeners.add(listener);
751
- return () => {
752
- loadingListeners.delete(listener);
753
- };
754
- }
755
- function isDocumentsLoading() {
756
- return backgroundReads.size > 0;
757
- }
758
- function useDocumentsLoading() {
759
- return react.useSyncExternalStore(subscribeLoading, isDocumentsLoading, () => false);
760
- }
761
- function stopDocumentsLoading(workspaceId) {
762
- const controller = backgroundReads.get(workspaceId);
763
- if (!controller) return;
764
- controller.abort();
765
- backgroundReads.delete(workspaceId);
766
- emitLoading();
767
- }
768
- async function loadDocuments(qc, arbi, workspaceId, signal) {
769
- let stopped = false;
770
- for (const [id, controller2] of backgroundReads) {
771
- if (id === workspaceId) continue;
772
- controller2.abort();
773
- backgroundReads.delete(id);
774
- stopped = true;
775
- }
776
- if (stopped) emitLoading();
777
- const controller = new AbortController();
778
- signal?.addEventListener("abort", () => controller.abort(), { once: true });
779
- const pages = arbi.documents.listPaginated({
780
- pageSize: DOCUMENTS_PAGE_SIZE,
781
- firstPageSize: DOCUMENTS_FIRST_PAGE_SIZE,
782
- signal: controller.signal
783
- });
784
- mark(FIRST_PAGE_START);
785
- const first = await pages.next();
786
- const firstPage = first.done ? [] : first.value;
787
- measure(FIRST_PAGE_MEASURE, FIRST_PAGE_START);
788
- if (first.done || firstPage.length < DOCUMENTS_FIRST_PAGE_SIZE) return firstPage;
789
- if (backgroundReads.has(workspaceId)) {
790
- controller.abort();
791
- return firstPage;
792
- }
793
- backgroundReads.set(workspaceId, controller);
794
- emitLoading();
795
- void appendRemainingPages(qc, workspaceId, pages, controller.signal).finally(() => {
796
- if (backgroundReads.get(workspaceId) !== controller) return;
797
- backgroundReads.delete(workspaceId);
798
- emitLoading();
799
- });
800
- return firstPage;
801
- }
802
- async function appendRemainingPages(qc, workspaceId, pages, signal) {
803
- await Promise.resolve();
804
- try {
805
- for await (const page of pages) {
806
- if (signal.aborted) return;
807
- patchDocuments(
808
- qc,
809
- (old) => {
810
- const known = new Set(old.map((doc) => doc.external_id));
811
- const fresh = page.filter((doc) => !known.has(doc.external_id));
812
- return fresh.length ? [...old, ...fresh] : old;
813
- },
814
- workspaceId
815
- );
816
- }
817
- } catch (error) {
818
- if (!signal.aborted) console.error(`Reading the documents of ${workspaceId} failed:`, error);
819
- }
820
- }
821
- var FINISHED_DOCUMENT_STATUSES = /* @__PURE__ */ new Set([
822
- "completed",
823
- "low-content",
824
- "failed",
825
- "skipped",
826
- "empty"
827
- ]);
828
- function openWorkspaceId2(arbi) {
829
- return arbi.hasWorkspace ? arbi.getWorkspaceId() : null;
830
- }
831
- function useDocuments(workspaceId, options) {
832
- const arbi = chunkGTJ667CP_cjs.useArbi();
833
- const qc = reactQuery.useQueryClient();
834
- const workspace = workspaceId ?? openWorkspaceId2(arbi) ?? "";
835
- return reactQuery.useQuery({
836
- queryKey: arbiQueryKeys.documents(workspace),
837
- queryFn: ({ signal }) => {
838
- if (openWorkspaceId2(arbi) !== workspace)
839
- return Promise.reject(new Error("The selected workspace changed."));
840
- return loadDocuments(qc, arbi, workspace, signal);
841
- },
842
- enabled: (options?.enabled ?? true) && !!workspace && arbi.hasWorkspace,
843
- staleTime: Infinity,
844
- refetchOnMount: false,
845
- refetchOnReconnect: false,
846
- refetchOnWindowFocus: false
847
- });
848
- }
849
- var DOCUMENT_STATUS_POLL_MS = 4e3;
850
- function processingInterval(doc) {
851
- return doc?.status && !FINISHED_DOCUMENT_STATUSES.has(doc.status) ? DOCUMENT_STATUS_POLL_MS : false;
852
- }
853
- function useDocument(docId, options) {
854
- const arbi = chunkGTJ667CP_cjs.useArbi();
855
- return reactQuery.useQuery({
856
- queryKey: arbiQueryKeys.document(docId ?? ""),
857
- queryFn: async () => (await arbi.documents.get([docId]))[0] ?? null,
858
- enabled: (options?.enabled ?? true) && !!docId && arbi.isLoggedIn,
859
- refetchInterval: options?.pollWhileProcessing ? (query) => processingInterval(query.state.data) : false
860
- });
861
- }
862
- function useDocumentsById(docIds, options) {
863
- const arbi = chunkGTJ667CP_cjs.useArbi();
864
- return reactQuery.useQuery({
865
- queryKey: arbiQueryKeys.documentsById(docIds),
866
- queryFn: () => arbi.documents.get(docIds),
867
- enabled: (options?.enabled ?? true) && docIds.length > 0 && arbi.isLoggedIn
868
- });
869
- }
870
- var SIMILARITY_THRESHOLD = 0.98;
871
- function useSimilarDocuments(options) {
872
- const arbi = chunkGTJ667CP_cjs.useArbi();
873
- const workspace = openWorkspaceId2(arbi) ?? "";
874
- return reactQuery.useQuery({
875
- queryKey: arbiQueryKeys.similarDocuments(workspace, SIMILARITY_THRESHOLD),
876
- queryFn: () => arbi.documents.similar({ threshold: SIMILARITY_THRESHOLD }),
877
- enabled: (options?.enabled ?? true) && !!workspace
878
- });
879
- }
880
- var readSeq = 0;
881
- var latestReadByDoc = /* @__PURE__ */ new Map();
882
- async function refreshDocuments(qc, arbi, docIds, options) {
883
- if (!docIds.length) return [];
884
- const seq = ++readSeq;
885
- for (const id of docIds) latestReadByDoc.set(id, seq);
886
- try {
887
- const read = await arbi.documents.get(docIds);
888
- const fresh = read.filter((doc) => latestReadByDoc.get(doc.external_id) === seq).map((doc) => {
889
- const live = options?.processingStatus?.(doc.external_id);
890
- return live && FINISHED_DOCUMENT_STATUSES.has(live) && doc.status !== live ? { ...doc, status: live } : doc;
891
- });
892
- if (!fresh.length) return [];
893
- reconcileTagCounts(qc, fresh);
894
- upsertDocuments(qc, fresh);
895
- for (const doc of fresh) setCachedDocument(qc, doc);
896
- return fresh;
897
- } catch (error) {
898
- console.error("Re-reading documents failed; the cached ones are kept:", error);
899
- return [];
900
- } finally {
901
- for (const id of docIds) if (latestReadByDoc.get(id) === seq) latestReadByDoc.delete(id);
902
- }
903
- }
904
- function reconcileTagCounts(qc, fresh) {
905
- const byWorkspace = /* @__PURE__ */ new Map();
906
- for (const doc of fresh) {
907
- const cached = getCachedDocuments(qc, doc.workspace_ext_id)?.find(
908
- (d) => d.external_id === doc.external_id
909
- );
910
- const before = new Set((cached?.doctags ?? []).map((dt) => dt.tag_ext_id));
911
- const after = new Set((doc.doctags ?? []).map((dt) => dt.tag_ext_id));
912
- const delta = byWorkspace.get(doc.workspace_ext_id) ?? /* @__PURE__ */ new Map();
913
- for (const id of after) if (!before.has(id)) delta.set(id, (delta.get(id) ?? 0) + 1);
914
- for (const id of before) if (!after.has(id)) delta.set(id, (delta.get(id) ?? 0) - 1);
915
- byWorkspace.set(doc.workspace_ext_id, delta);
916
- }
917
- for (const [workspaceId, delta] of byWorkspace) adjustTagCounts(qc, workspaceId, delta);
918
- }
919
- function adjustTagCounts(qc, workspaceId, delta) {
920
- if (![...delta.values()].some(Boolean)) return;
921
- patchWorkspaceTags(
922
- qc,
923
- workspaceId,
924
- (tags) => tags.map((tag) => {
925
- const change = delta.get(tag.external_id);
926
- return change ? { ...tag, doctag_count: Math.max(0, tag.doctag_count + change) } : tag;
927
- })
928
- );
929
- void invalidateTagTables(qc, workspaceId);
930
- }
931
-
932
- exports.DOCUMENTS_FIRST_PAGE_MEASURE = DOCUMENTS_FIRST_PAGE_MEASURE;
933
- exports.DOCUMENTS_FIRST_PAGE_SIZE = DOCUMENTS_FIRST_PAGE_SIZE;
934
- exports.DOCUMENTS_PAGE_SIZE = DOCUMENTS_PAGE_SIZE;
935
- exports.FINISHED_DOCUMENT_STATUSES = FINISHED_DOCUMENT_STATUSES;
936
- exports.PROJECT_CREATION_DENIED_REASON = PROJECT_CREATION_DENIED_REASON;
937
- exports.SIMILARITY_THRESHOLD = SIMILARITY_THRESHOLD;
938
- exports.adjustTagCounts = adjustTagCounts;
939
- exports.arbiMutationKeys = arbiMutationKeys;
940
- exports.arbiQueryKeys = arbiQueryKeys;
941
- exports.dropTagFromCachedDocuments = dropTagFromCachedDocuments;
942
- exports.finishEntityExtraction = finishEntityExtraction;
943
- exports.forgetDocuments = forgetDocuments;
944
- exports.getCachedDocuments = getCachedDocuments;
945
- exports.invalidateTagData = invalidateTagData;
946
- exports.invalidateTagTables = invalidateTagTables;
947
- exports.isDocumentsLoading = isDocumentsLoading;
948
- exports.isUsageMetered = isUsageMetered;
949
- exports.patchCachedDocument = patchCachedDocument;
950
- exports.patchDocuments = patchDocuments;
951
- exports.patchWorkspaceTags = patchWorkspaceTags;
952
- exports.refreshDocuments = refreshDocuments;
953
- exports.replayableTagMutations = replayableTagMutations;
954
- exports.setCachedDocument = setCachedDocument;
955
- exports.startEntityExtraction = startEntityExtraction;
956
- exports.stopDocumentsLoading = stopDocumentsLoading;
957
- exports.subscribeDocumentRows = subscribeDocumentRows;
958
- exports.upsertDocuments = upsertDocuments;
959
- exports.useActivity = useActivity;
960
- exports.useAgents = useAgents;
961
- exports.useAssistantQuery = useAssistantQuery;
962
- exports.useAvailableModels = useAvailableModels;
963
- exports.useCanCreateProjects = useCanCreateProjects;
964
- exports.useConfigs = useConfigs;
965
- exports.useConversationThreads = useConversationThreads;
966
- exports.useConversations = useConversations;
967
- exports.useCreateTag = useCreateTag;
968
- exports.useCurrentUser = useCurrentUser;
969
- exports.useDeleteAgents = useDeleteAgents;
970
- exports.useDeleteTag = useDeleteTag;
971
- exports.useDocument = useDocument;
972
- exports.useDocumentVersionList = useDocumentVersionList;
973
- exports.useDocuments = useDocuments;
974
- exports.useDocumentsById = useDocumentsById;
975
- exports.useDocumentsLoading = useDocumentsLoading;
976
- exports.useEntityExtractionDocIds = useEntityExtractionDocIds;
977
- exports.useExtractEntities = useExtractEntities;
978
- exports.useFirmPool = useFirmPool;
979
- exports.useHealth = useHealth;
980
- exports.useInvalidateTagData = useInvalidateTagData;
981
- exports.useIsCreatingTag = useIsCreatingTag;
982
- exports.useParsedDocument = useParsedDocument;
983
- exports.useProjectInvoices = useProjectInvoices;
984
- exports.useProjectUsage = useProjectUsage;
985
- exports.useProjects = useProjects;
986
- exports.useProjectsUsage = useProjectsUsage;
987
- exports.useSetTagValues = useSetTagValues;
988
- exports.useSimilarDocuments = useSimilarDocuments;
989
- exports.useTagKindSchema = useTagKindSchema;
990
- exports.useTags = useTags;
991
- exports.useThumbnails = useThumbnails;
992
- exports.useTopUpFirmPool = useTopUpFirmPool;
993
- exports.useUpdateTag = useUpdateTag;
994
- exports.useUpdateTagKindSchema = useUpdateTagKindSchema;
995
- exports.useUserUsageToday = useUserUsageToday;
996
- exports.useWorkspaceActivity = useWorkspaceActivity;
997
- exports.useWorkspaces = useWorkspaces;
998
- //# sourceMappingURL=chunk-6MTKKT2O.cjs.map
999
- //# sourceMappingURL=chunk-6MTKKT2O.cjs.map