@arbidocs/sdk 0.3.47 → 0.3.48

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/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as ConfigStore, a as CliConfig, b as CliCredentials, c as ChatSession, S as SkippedFile, U as UploadResult, A as AuthHeaders, d as UploadBatchResult, e as UploadOptions, f as UploadDirectOptions, g as UploadDirectResult, h as SUPPORTED_EXTENSIONS, D as DmCryptoContext } from './browser-CtYFcHNd.cjs';
2
- export { i as AgentStepEvent, j as Arbi, k as ArbiApiError, l as ArbiError, m as ArbiOptions, n as ArtifactEvent, o as AuthContext, p as AuthenticatedClient, q as CitationSummary, r as ConnectOptions, s as DOC_TERMINAL_STATUSES, t as DocumentListFields, u as DocumentListOrder, v as DocumentWaiter, w as DocumentWaiterOptions, F as FormattedWsMessage, L as ListAllOptions, x as ListPaginatedOptions, M as MessageLevel, y as MessageMetadataPayload, z as MessageQueuedEvent, O as OutputTokensDetails, Q as QueryOptions, R as ReconnectOptions, B as ReconnectableWsConnection, E as ResolvedCitation, G as ResponseCompletedEvent, H as ResponseContentPartAddedEvent, I as ResponseCreatedEvent, J as ResponseFailedEvent, K as ResponseOutputItemAddedEvent, N as ResponseOutputItemDoneEvent, P as ResponseOutputTextDeltaEvent, T as ResponseOutputTextDoneEvent, V as ResponseUsage, W as SSEEvent, X as SSEStreamCallbacks, Y as SSEStreamResult, Z as SSEStreamStartData, _ as UserInfo, $ as UserInputRequestEvent, a0 as UserMessageEvent, a1 as WorkspaceContext, a2 as WsConnection, a3 as agentconfig, a4 as assistant, a5 as authenticatedFetch, a6 as buildRetrievalChunkTool, a7 as buildRetrievalFullContextTool, a8 as buildRetrievalTocTool, a9 as connectWebSocket, aa as connectWithReconnect, ab as consumeSSEStream, ac as contacts, ad as conversations, ae as countCitations, af as createAuthenticatedClient, ag as createDocumentWaiter, ah as dm, ai as doctags, aj as documents, ak as files, al as formatAgentStepLabel, am as formatFileSize, an as formatStreamSummary, ao as formatUserName, ap as formatWorkspaceChoices, aq as formatWsMessage, ar as generateEncryptedWorkspaceKey, as as generateNewWorkspaceKey, at as getErrorCode, au as getErrorMessage, av as getRawWorkspaceKey, aw as health, ax as parseSSEEvents, ay as performPasswordLogin, az as performSigningKeyLogin, aA as performSsoDeviceFlowLogin, aB as requireData, aC as requireOk, aD as resolveAuth, aE as resolveCitations, aF as resolveWorkspace, aG as responses, aH as selectWorkspace, aI as selectWorkspaceById, aJ as settings, aK as streamSSE, aL as stripCitationMarkdown, aM as summarizeCitations, aN as tags, aO as workspaces } from './browser-CtYFcHNd.cjs';
1
+ import { C as ConfigStore, a as CliConfig, b as CliCredentials, c as ChatSession, S as SkippedFile, U as UploadResult, A as AuthHeaders, d as UploadBatchResult, e as UploadOptions, f as UploadDirectOptions, g as UploadDirectResult, h as SUPPORTED_EXTENSIONS, D as DmCryptoContext } from './browser-EMgd4bP4.cjs';
2
+ export { i as AgentStepEvent, j as Arbi, k as ArbiApiError, l as ArbiError, m as ArbiOptions, n as ArtifactEvent, o as AuthContext, p as AuthenticatedClient, q as CitationSummary, r as ConnectOptions, s as DOC_TERMINAL_STATUSES, t as DocumentListFields, u as DocumentListOrder, v as DocumentWaiter, w as DocumentWaiterOptions, F as FormattedWsMessage, L as ListAllOptions, x as ListPaginatedOptions, M as MessageLevel, y as MessageMetadataPayload, z as MessageQueuedEvent, O as OutputTokensDetails, Q as QueryOptions, R as ReconnectOptions, B as ReconnectableWsConnection, E as ResolvedCitation, G as ResponseCompletedEvent, H as ResponseContentPartAddedEvent, I as ResponseCreatedEvent, J as ResponseFailedEvent, K as ResponseOutputItemAddedEvent, N as ResponseOutputItemDoneEvent, P as ResponseOutputTextDeltaEvent, T as ResponseOutputTextDoneEvent, V as ResponseUsage, W as SSEEvent, X as SSEStreamCallbacks, Y as SSEStreamResult, Z as SSEStreamStartData, _ as UserInfo, $ as UserInputRequestEvent, a0 as UserMessageEvent, a1 as WorkspaceContext, a2 as WsConnection, a3 as agentconfig, a4 as assistant, a5 as authenticatedFetch, a6 as buildRetrievalChunkTool, a7 as buildRetrievalFullContextTool, a8 as buildRetrievalTocTool, a9 as connectWebSocket, aa as connectWithReconnect, ab as consumeSSEStream, ac as contacts, ad as conversations, ae as countCitations, af as createAuthenticatedClient, ag as createDocumentWaiter, ah as dm, ai as doctags, aj as documents, ak as files, al as formatAgentStepLabel, am as formatFileSize, an as formatStreamSummary, ao as formatUserName, ap as formatWorkspaceChoices, aq as formatWsMessage, ar as generateEncryptedWorkspaceKey, as as generateNewWorkspaceKey, at as getErrorCode, au as getErrorMessage, av as getRawWorkspaceKey, aw as health, ax as parseSSEEvents, ay as performPasswordLogin, az as performSigningKeyLogin, aA as performSsoDeviceFlowLogin, aB as requireData, aC as requireOk, aD as resolveAuth, aE as resolveCitations, aF as resolveWorkspace, aG as responses, aH as selectWorkspace, aI as selectWorkspaceById, aJ as settings, aK as streamSSE, aL as stripCitationMarkdown, aM as summarizeCitations, aN as tags, aO as workspaces } from './browser-EMgd4bP4.cjs';
3
3
  import { SessionStorageProvider, ArbiClient, components } from '@arbidocs/client';
4
4
 
5
5
  /**
@@ -168,8 +168,11 @@ interface UploadDirectoryOptions {
168
168
  /**
169
169
  * Upload a local file by path. Handles readFileSync + basename + Blob + uploadFile.
170
170
  * Convenience wrapper for CLI/TUI consumers that work with file system paths.
171
+ *
172
+ * Workspace context is derived server-side from the open session (the caller's
173
+ * JWT + most recent ``/workspace/{id}/open`` call), so no workspace id is sent.
171
174
  */
172
- declare function uploadLocalFile(auth: AuthHeaders, workspaceId: string, filePath: string, options?: UploadOptions): Promise<UploadResult & {
175
+ declare function uploadLocalFile(auth: AuthHeaders, filePath: string, options?: UploadOptions): Promise<UploadResult & {
173
176
  fileName: string;
174
177
  }>;
175
178
  /**
@@ -225,13 +228,13 @@ declare function uploadLocalArchiveDirect(arbi: ArbiClient, workspaceKey: Uint8A
225
228
  * Files are grouped by their relative folder path, then each group is split
226
229
  * into batches of UPLOAD_BATCH_SIZE to avoid overwhelming the backend.
227
230
  */
228
- declare function uploadDirectory(auth: AuthHeaders, workspaceId: string, dirPath: string, options?: UploadDirectoryOptions): Promise<UploadBatchResult>;
231
+ declare function uploadDirectory(auth: AuthHeaders, dirPath: string, options?: UploadDirectoryOptions): Promise<UploadBatchResult>;
229
232
  /**
230
233
  * Upload files from a zip archive, preserving internal folder structure.
231
234
  * Uses jszip via dynamic import so the dependency is optional at load time.
232
235
  * Files are uploaded in batches of UPLOAD_BATCH_SIZE per folder.
233
236
  */
234
- declare function uploadZip(auth: AuthHeaders, workspaceId: string, zipPath: string, options?: UploadDirectoryOptions): Promise<UploadBatchResult>;
237
+ declare function uploadZip(auth: AuthHeaders, zipPath: string, options?: UploadDirectoryOptions): Promise<UploadBatchResult>;
235
238
  /**
236
239
  * Terminal status for a single file after `uploadManifest` processes it.
237
240
  *
@@ -328,7 +331,7 @@ interface UploadManifestResult {
328
331
  * If the backend's response length disagrees with the survivor count, all
329
332
  * survivors are emitted as `error` so the caller can retry.
330
333
  */
331
- declare function uploadManifest(auth: AuthHeaders, workspaceId: string, paths: string[], options?: UploadManifestOptions): Promise<UploadManifestResult>;
334
+ declare function uploadManifest(auth: AuthHeaders, paths: string[], options?: UploadManifestOptions): Promise<UploadManifestResult>;
332
335
  /**
333
336
  * Recursively walk a directory and return all absolute paths of files whose
334
337
  * extension is in SUPPORTED_EXTENSIONS. Useful for turning a directory input
@@ -341,7 +344,7 @@ declare function walkSupportedFiles(dirPath: string): string[];
341
344
  * to `uploadDirectory`. Requires p7zip / 7z to be installed on the system.
342
345
  * Supports: .7z, .rar (anything `7z x` can handle).
343
346
  */
344
- declare function uploadArchive(auth: AuthHeaders, workspaceId: string, archivePath: string, options?: UploadDirectoryOptions): Promise<UploadBatchResult>;
347
+ declare function uploadArchive(auth: AuthHeaders, archivePath: string, options?: UploadDirectoryOptions): Promise<UploadBatchResult>;
345
348
 
346
349
  declare const documentsNode_ARCHIVE_EXTENSIONS: typeof ARCHIVE_EXTENSIONS;
347
350
  type documentsNode_FileOutcome = FileOutcome;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as ConfigStore, a as CliConfig, b as CliCredentials, c as ChatSession, S as SkippedFile, U as UploadResult, A as AuthHeaders, d as UploadBatchResult, e as UploadOptions, f as UploadDirectOptions, g as UploadDirectResult, h as SUPPORTED_EXTENSIONS, D as DmCryptoContext } from './browser-CtYFcHNd.js';
2
- export { i as AgentStepEvent, j as Arbi, k as ArbiApiError, l as ArbiError, m as ArbiOptions, n as ArtifactEvent, o as AuthContext, p as AuthenticatedClient, q as CitationSummary, r as ConnectOptions, s as DOC_TERMINAL_STATUSES, t as DocumentListFields, u as DocumentListOrder, v as DocumentWaiter, w as DocumentWaiterOptions, F as FormattedWsMessage, L as ListAllOptions, x as ListPaginatedOptions, M as MessageLevel, y as MessageMetadataPayload, z as MessageQueuedEvent, O as OutputTokensDetails, Q as QueryOptions, R as ReconnectOptions, B as ReconnectableWsConnection, E as ResolvedCitation, G as ResponseCompletedEvent, H as ResponseContentPartAddedEvent, I as ResponseCreatedEvent, J as ResponseFailedEvent, K as ResponseOutputItemAddedEvent, N as ResponseOutputItemDoneEvent, P as ResponseOutputTextDeltaEvent, T as ResponseOutputTextDoneEvent, V as ResponseUsage, W as SSEEvent, X as SSEStreamCallbacks, Y as SSEStreamResult, Z as SSEStreamStartData, _ as UserInfo, $ as UserInputRequestEvent, a0 as UserMessageEvent, a1 as WorkspaceContext, a2 as WsConnection, a3 as agentconfig, a4 as assistant, a5 as authenticatedFetch, a6 as buildRetrievalChunkTool, a7 as buildRetrievalFullContextTool, a8 as buildRetrievalTocTool, a9 as connectWebSocket, aa as connectWithReconnect, ab as consumeSSEStream, ac as contacts, ad as conversations, ae as countCitations, af as createAuthenticatedClient, ag as createDocumentWaiter, ah as dm, ai as doctags, aj as documents, ak as files, al as formatAgentStepLabel, am as formatFileSize, an as formatStreamSummary, ao as formatUserName, ap as formatWorkspaceChoices, aq as formatWsMessage, ar as generateEncryptedWorkspaceKey, as as generateNewWorkspaceKey, at as getErrorCode, au as getErrorMessage, av as getRawWorkspaceKey, aw as health, ax as parseSSEEvents, ay as performPasswordLogin, az as performSigningKeyLogin, aA as performSsoDeviceFlowLogin, aB as requireData, aC as requireOk, aD as resolveAuth, aE as resolveCitations, aF as resolveWorkspace, aG as responses, aH as selectWorkspace, aI as selectWorkspaceById, aJ as settings, aK as streamSSE, aL as stripCitationMarkdown, aM as summarizeCitations, aN as tags, aO as workspaces } from './browser-CtYFcHNd.js';
1
+ import { C as ConfigStore, a as CliConfig, b as CliCredentials, c as ChatSession, S as SkippedFile, U as UploadResult, A as AuthHeaders, d as UploadBatchResult, e as UploadOptions, f as UploadDirectOptions, g as UploadDirectResult, h as SUPPORTED_EXTENSIONS, D as DmCryptoContext } from './browser-EMgd4bP4.js';
2
+ export { i as AgentStepEvent, j as Arbi, k as ArbiApiError, l as ArbiError, m as ArbiOptions, n as ArtifactEvent, o as AuthContext, p as AuthenticatedClient, q as CitationSummary, r as ConnectOptions, s as DOC_TERMINAL_STATUSES, t as DocumentListFields, u as DocumentListOrder, v as DocumentWaiter, w as DocumentWaiterOptions, F as FormattedWsMessage, L as ListAllOptions, x as ListPaginatedOptions, M as MessageLevel, y as MessageMetadataPayload, z as MessageQueuedEvent, O as OutputTokensDetails, Q as QueryOptions, R as ReconnectOptions, B as ReconnectableWsConnection, E as ResolvedCitation, G as ResponseCompletedEvent, H as ResponseContentPartAddedEvent, I as ResponseCreatedEvent, J as ResponseFailedEvent, K as ResponseOutputItemAddedEvent, N as ResponseOutputItemDoneEvent, P as ResponseOutputTextDeltaEvent, T as ResponseOutputTextDoneEvent, V as ResponseUsage, W as SSEEvent, X as SSEStreamCallbacks, Y as SSEStreamResult, Z as SSEStreamStartData, _ as UserInfo, $ as UserInputRequestEvent, a0 as UserMessageEvent, a1 as WorkspaceContext, a2 as WsConnection, a3 as agentconfig, a4 as assistant, a5 as authenticatedFetch, a6 as buildRetrievalChunkTool, a7 as buildRetrievalFullContextTool, a8 as buildRetrievalTocTool, a9 as connectWebSocket, aa as connectWithReconnect, ab as consumeSSEStream, ac as contacts, ad as conversations, ae as countCitations, af as createAuthenticatedClient, ag as createDocumentWaiter, ah as dm, ai as doctags, aj as documents, ak as files, al as formatAgentStepLabel, am as formatFileSize, an as formatStreamSummary, ao as formatUserName, ap as formatWorkspaceChoices, aq as formatWsMessage, ar as generateEncryptedWorkspaceKey, as as generateNewWorkspaceKey, at as getErrorCode, au as getErrorMessage, av as getRawWorkspaceKey, aw as health, ax as parseSSEEvents, ay as performPasswordLogin, az as performSigningKeyLogin, aA as performSsoDeviceFlowLogin, aB as requireData, aC as requireOk, aD as resolveAuth, aE as resolveCitations, aF as resolveWorkspace, aG as responses, aH as selectWorkspace, aI as selectWorkspaceById, aJ as settings, aK as streamSSE, aL as stripCitationMarkdown, aM as summarizeCitations, aN as tags, aO as workspaces } from './browser-EMgd4bP4.js';
3
3
  import { SessionStorageProvider, ArbiClient, components } from '@arbidocs/client';
4
4
 
5
5
  /**
@@ -168,8 +168,11 @@ interface UploadDirectoryOptions {
168
168
  /**
169
169
  * Upload a local file by path. Handles readFileSync + basename + Blob + uploadFile.
170
170
  * Convenience wrapper for CLI/TUI consumers that work with file system paths.
171
+ *
172
+ * Workspace context is derived server-side from the open session (the caller's
173
+ * JWT + most recent ``/workspace/{id}/open`` call), so no workspace id is sent.
171
174
  */
172
- declare function uploadLocalFile(auth: AuthHeaders, workspaceId: string, filePath: string, options?: UploadOptions): Promise<UploadResult & {
175
+ declare function uploadLocalFile(auth: AuthHeaders, filePath: string, options?: UploadOptions): Promise<UploadResult & {
173
176
  fileName: string;
174
177
  }>;
175
178
  /**
@@ -225,13 +228,13 @@ declare function uploadLocalArchiveDirect(arbi: ArbiClient, workspaceKey: Uint8A
225
228
  * Files are grouped by their relative folder path, then each group is split
226
229
  * into batches of UPLOAD_BATCH_SIZE to avoid overwhelming the backend.
227
230
  */
228
- declare function uploadDirectory(auth: AuthHeaders, workspaceId: string, dirPath: string, options?: UploadDirectoryOptions): Promise<UploadBatchResult>;
231
+ declare function uploadDirectory(auth: AuthHeaders, dirPath: string, options?: UploadDirectoryOptions): Promise<UploadBatchResult>;
229
232
  /**
230
233
  * Upload files from a zip archive, preserving internal folder structure.
231
234
  * Uses jszip via dynamic import so the dependency is optional at load time.
232
235
  * Files are uploaded in batches of UPLOAD_BATCH_SIZE per folder.
233
236
  */
234
- declare function uploadZip(auth: AuthHeaders, workspaceId: string, zipPath: string, options?: UploadDirectoryOptions): Promise<UploadBatchResult>;
237
+ declare function uploadZip(auth: AuthHeaders, zipPath: string, options?: UploadDirectoryOptions): Promise<UploadBatchResult>;
235
238
  /**
236
239
  * Terminal status for a single file after `uploadManifest` processes it.
237
240
  *
@@ -328,7 +331,7 @@ interface UploadManifestResult {
328
331
  * If the backend's response length disagrees with the survivor count, all
329
332
  * survivors are emitted as `error` so the caller can retry.
330
333
  */
331
- declare function uploadManifest(auth: AuthHeaders, workspaceId: string, paths: string[], options?: UploadManifestOptions): Promise<UploadManifestResult>;
334
+ declare function uploadManifest(auth: AuthHeaders, paths: string[], options?: UploadManifestOptions): Promise<UploadManifestResult>;
332
335
  /**
333
336
  * Recursively walk a directory and return all absolute paths of files whose
334
337
  * extension is in SUPPORTED_EXTENSIONS. Useful for turning a directory input
@@ -341,7 +344,7 @@ declare function walkSupportedFiles(dirPath: string): string[];
341
344
  * to `uploadDirectory`. Requires p7zip / 7z to be installed on the system.
342
345
  * Supports: .7z, .rar (anything `7z x` can handle).
343
346
  */
344
- declare function uploadArchive(auth: AuthHeaders, workspaceId: string, archivePath: string, options?: UploadDirectoryOptions): Promise<UploadBatchResult>;
347
+ declare function uploadArchive(auth: AuthHeaders, archivePath: string, options?: UploadDirectoryOptions): Promise<UploadBatchResult>;
345
348
 
346
349
  declare const documentsNode_ARCHIVE_EXTENSIONS: typeof ARCHIVE_EXTENSIONS;
347
350
  type documentsNode_FileOutcome = FileOutcome;
package/dist/index.js CHANGED
@@ -4646,6 +4646,7 @@ __export(documents_exports, {
4646
4646
  listAll: () => listAll,
4647
4647
  listDocuments: () => listDocuments,
4648
4648
  listPaginated: () => listPaginated,
4649
+ mimeFromName: () => mimeFromName,
4649
4650
  sanitizeFolderPath: () => sanitizeFolderPath,
4650
4651
  updateDocuments: () => updateDocuments,
4651
4652
  uploadDocumentsDirect: () => uploadDocumentsDirect,
@@ -4795,11 +4796,11 @@ async function updateDocuments(arbi, documents) {
4795
4796
  "Failed to update documents"
4796
4797
  );
4797
4798
  }
4798
- async function uploadUrl(arbi, urls, workspaceId, shared = false) {
4799
+ async function uploadUrl(arbi, urls, shared = false) {
4799
4800
  return requireData(
4800
4801
  await arbi.fetch.POST("/v1/document/upload-url", {
4801
4802
  params: {
4802
- query: { urls, workspace_ext_id: workspaceId, shared }
4803
+ query: { urls, shared }
4803
4804
  }
4804
4805
  }),
4805
4806
  "Failed to upload from URLs"
@@ -4812,29 +4813,31 @@ async function getParsedContent(auth, docId, stage) {
4812
4813
  });
4813
4814
  return res.json();
4814
4815
  }
4815
- async function uploadFile(auth, workspaceId, fileData, fileName, options) {
4816
+ async function uploadFile(auth, fileData, fileName, options) {
4816
4817
  const formData = new FormData();
4817
4818
  formData.append("files", fileData, fileName);
4818
- const params = new URLSearchParams({ workspace_ext_id: workspaceId });
4819
+ const params = new URLSearchParams();
4819
4820
  if (options?.folder) params.set("folder", sanitizeFolderPath(options.folder));
4820
4821
  if (options?.configExtId) params.set("config_ext_id", options.configExtId);
4822
+ const qs = params.toString();
4821
4823
  const res = await authenticatedFetch({
4822
4824
  ...auth,
4823
- path: `/v1/document/upload?${params.toString()}`,
4825
+ path: qs ? `/v1/document/upload?${qs}` : `/v1/document/upload`,
4824
4826
  method: "POST",
4825
4827
  body: formData
4826
4828
  });
4827
4829
  return res.json();
4828
4830
  }
4829
- async function uploadFiles(auth, workspaceId, files, options) {
4831
+ async function uploadFiles(auth, files, options) {
4830
4832
  const formData = new FormData();
4831
4833
  for (const f2 of files) formData.append("files", f2.data, f2.name);
4832
- const params = new URLSearchParams({ workspace_ext_id: workspaceId });
4834
+ const params = new URLSearchParams();
4833
4835
  if (options?.folder) params.set("folder", sanitizeFolderPath(options.folder));
4834
4836
  if (options?.configExtId) params.set("config_ext_id", options.configExtId);
4837
+ const qs = params.toString();
4835
4838
  const res = await authenticatedFetch({
4836
4839
  ...auth,
4837
- path: `/v1/document/upload?${params.toString()}`,
4840
+ path: qs ? `/v1/document/upload?${qs}` : `/v1/document/upload`,
4838
4841
  method: "POST",
4839
4842
  body: formData
4840
4843
  });
@@ -4846,6 +4849,68 @@ async function downloadDocument(auth, docId) {
4846
4849
  path: `/v1/document/${docId}/download`
4847
4850
  });
4848
4851
  }
4852
+ function mimeFromName(name) {
4853
+ const dot = name.lastIndexOf(".");
4854
+ const ext = dot === -1 ? "" : name.slice(dot).toLowerCase();
4855
+ switch (ext) {
4856
+ case ".pdf":
4857
+ return "application/pdf";
4858
+ case ".txt":
4859
+ return "text/plain";
4860
+ case ".md":
4861
+ return "text/markdown";
4862
+ case ".html":
4863
+ case ".htm":
4864
+ return "text/html";
4865
+ case ".doc":
4866
+ return "application/msword";
4867
+ case ".docx":
4868
+ return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
4869
+ case ".xls":
4870
+ return "application/vnd.ms-excel";
4871
+ case ".xlsx":
4872
+ return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
4873
+ case ".ppt":
4874
+ return "application/vnd.ms-powerpoint";
4875
+ case ".pptx":
4876
+ return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
4877
+ case ".eml":
4878
+ return "message/rfc822";
4879
+ default:
4880
+ return void 0;
4881
+ }
4882
+ }
4883
+ async function presignedPut(url, body, onProgress) {
4884
+ const XhrGlobal = globalThis.XMLHttpRequest;
4885
+ if (XhrGlobal) {
4886
+ await new Promise((resolve2, reject) => {
4887
+ const xhr = new XhrGlobal();
4888
+ xhr.open("PUT", url);
4889
+ if (onProgress) {
4890
+ xhr.upload.addEventListener("progress", (e) => {
4891
+ if (e.lengthComputable) onProgress(e.loaded, e.total);
4892
+ });
4893
+ }
4894
+ xhr.addEventListener("load", () => {
4895
+ if (xhr.status >= 200 && xhr.status < 300) {
4896
+ resolve2();
4897
+ } else {
4898
+ const snippet = (xhr.responseText || "").slice(0, 200);
4899
+ reject(new Error(`Presigned PUT failed: ${xhr.status} ${snippet}`));
4900
+ }
4901
+ });
4902
+ xhr.addEventListener("error", () => reject(new Error("Presigned PUT network error")));
4903
+ xhr.addEventListener("abort", () => reject(new Error("Presigned PUT aborted")));
4904
+ xhr.send(body);
4905
+ });
4906
+ return;
4907
+ }
4908
+ const putRes = await fetch(url, { method: "PUT", body });
4909
+ if (!putRes.ok) {
4910
+ const snippet = await putRes.text().catch(() => "");
4911
+ throw new Error(`Presigned PUT failed: ${putRes.status} ${snippet.slice(0, 200)}`);
4912
+ }
4913
+ }
4849
4914
  async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
4850
4915
  if (files.length === 0) return { doc_ext_ids: [], skipped: [] };
4851
4916
  const SECRETBOX_ENVELOPE_OVERHEAD = 40;
@@ -4878,6 +4943,11 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
4878
4943
  }
4879
4944
  const skipped = [];
4880
4945
  const toCommit = [];
4946
+ const indexByName = /* @__PURE__ */ new Map();
4947
+ files.forEach((f2, i2) => {
4948
+ if (!indexByName.has(f2.name)) indexByName.set(f2.name, []);
4949
+ indexByName.get(f2.name).push(i2);
4950
+ });
4881
4951
  for (const item of items) {
4882
4952
  if (item.status !== "uploading" || !item.upload_url || !item.doc_ext_id) {
4883
4953
  skipped.push({
@@ -4887,21 +4957,34 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
4887
4957
  continue;
4888
4958
  }
4889
4959
  const queue = bytesByName.get(item.file_name);
4890
- if (!queue || queue.length === 0) {
4960
+ const idxQueue = indexByName.get(item.file_name);
4961
+ if (!queue || queue.length === 0 || !idxQueue || idxQueue.length === 0) {
4891
4962
  throw new Error(`upload-init returned slot for unknown file: ${item.file_name}`);
4892
4963
  }
4893
4964
  const raw = queue.shift();
4965
+ const fileIndex = idxQueue.shift();
4894
4966
  const ciphertext = encryptFile(raw, workspaceKey);
4895
- const putRes = await fetch(item.upload_url, {
4896
- method: "PUT",
4897
- body: ciphertext
4898
- });
4899
- if (!putRes.ok) {
4900
- const body = await putRes.text().catch(() => "");
4967
+ const total = ciphertext.length;
4968
+ try {
4969
+ await presignedPut(item.upload_url, ciphertext, (loaded, putTotal) => {
4970
+ options?.onBytesProgress?.({
4971
+ fileIndex,
4972
+ fileName: item.file_name,
4973
+ loaded,
4974
+ total: putTotal
4975
+ });
4976
+ });
4977
+ } catch (err) {
4901
4978
  throw new Error(
4902
- `Presigned PUT for ${item.doc_ext_id} failed: ${putRes.status} ${body.slice(0, 200)}`
4979
+ `Presigned PUT for ${item.doc_ext_id} failed: ${err instanceof Error ? err.message : String(err)}`
4903
4980
  );
4904
4981
  }
4982
+ options?.onBytesProgress?.({
4983
+ fileIndex,
4984
+ fileName: item.file_name,
4985
+ loaded: total,
4986
+ total
4987
+ });
4905
4988
  toCommit.push(item.doc_ext_id);
4906
4989
  }
4907
4990
  if (toCommit.length === 0) {
@@ -5757,19 +5840,19 @@ var Arbi = class {
5757
5840
  get: (externalIds) => getDocuments(this.requireClient(), externalIds),
5758
5841
  delete: (externalIds) => deleteDocuments(this.requireClient(), externalIds),
5759
5842
  update: (documents) => updateDocuments(this.requireClient(), documents),
5760
- uploadUrl: (urls, shared, workspaceId) => uploadUrl(
5761
- this.requireClient(),
5762
- urls,
5763
- workspaceId ?? this.requireWorkspace(),
5764
- shared
5765
- ),
5766
- uploadFile: (fileData, fileName, options) => uploadFile(
5767
- this.getAuthHeaders(),
5768
- options?.workspaceId ?? this.requireWorkspace(),
5769
- fileData,
5770
- fileName,
5771
- options?.folder ? { folder: options.folder } : void 0
5772
- ),
5843
+ uploadUrl: (urls, shared) => {
5844
+ this.requireWorkspace();
5845
+ return uploadUrl(this.requireClient(), urls, shared);
5846
+ },
5847
+ uploadFile: (fileData, fileName, options) => {
5848
+ this.requireWorkspace();
5849
+ return uploadFile(
5850
+ this.getAuthHeaders(),
5851
+ fileData,
5852
+ fileName,
5853
+ options?.folder ? { folder: options.folder } : void 0
5854
+ );
5855
+ },
5773
5856
  download: (docId) => downloadDocument(this.getAuthHeaders(), docId),
5774
5857
  getParsedContent: (docId, stage) => getParsedContent(this.getAuthHeaders(), docId, stage)
5775
5858
  };
@@ -5967,7 +6050,8 @@ function chunk(arr, size) {
5967
6050
  }
5968
6051
  return chunks;
5969
6052
  }
5970
- function readFileAsBlob(filePath, fileSize) {
6053
+ function readFileAsBlob(filePath, fileSize, fileName) {
6054
+ const type = fileName ? mimeFromName(fileName) ?? "" : "";
5971
6055
  if (fileSize > NODE_BUFFER_LIMIT) {
5972
6056
  const chunks = [];
5973
6057
  const CHUNK = 256 * 1024 * 1024;
@@ -5981,15 +6065,15 @@ function readFileAsBlob(filePath, fileSize) {
5981
6065
  pos += len;
5982
6066
  }
5983
6067
  fs2.closeSync(fd);
5984
- return new Blob(chunks);
6068
+ return new Blob(chunks, { type });
5985
6069
  }
5986
- return new Blob([fs2.readFileSync(filePath)]);
6070
+ return new Blob([fs2.readFileSync(filePath)], { type });
5987
6071
  }
5988
- async function uploadLocalFile(auth, workspaceId, filePath, options) {
6072
+ async function uploadLocalFile(auth, filePath, options) {
5989
6073
  const stat = fs2.statSync(filePath);
5990
6074
  const fileName = path2.basename(filePath);
5991
- const blob = readFileAsBlob(filePath, stat.size);
5992
- const result = await uploadFile(auth, workspaceId, blob, fileName, options);
6075
+ const blob = readFileAsBlob(filePath, stat.size, fileName);
6076
+ const result = await uploadFile(auth, blob, fileName, options);
5993
6077
  return { ...result, fileName };
5994
6078
  }
5995
6079
  async function uploadLocalFilesDirect(arbi, workspaceKey, filePaths, options) {
@@ -6148,37 +6232,7 @@ async function uploadLocalArchiveDirect(arbi, workspaceKey, archivePath, options
6148
6232
  }
6149
6233
  }
6150
6234
  }
6151
- function mimeFromName(name) {
6152
- const ext = path2.extname(name).toLowerCase();
6153
- switch (ext) {
6154
- case ".pdf":
6155
- return "application/pdf";
6156
- case ".txt":
6157
- return "text/plain";
6158
- case ".md":
6159
- return "text/markdown";
6160
- case ".html":
6161
- case ".htm":
6162
- return "text/html";
6163
- case ".doc":
6164
- return "application/msword";
6165
- case ".docx":
6166
- return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
6167
- case ".xls":
6168
- return "application/vnd.ms-excel";
6169
- case ".xlsx":
6170
- return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
6171
- case ".ppt":
6172
- return "application/vnd.ms-powerpoint";
6173
- case ".pptx":
6174
- return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
6175
- case ".eml":
6176
- return "message/rfc822";
6177
- default:
6178
- return void 0;
6179
- }
6180
- }
6181
- async function uploadDirectory(auth, workspaceId, dirPath, options) {
6235
+ async function uploadDirectory(auth, dirPath, options) {
6182
6236
  const resolvedDir = path2.resolve(dirPath);
6183
6237
  const dirName = path2.basename(resolvedDir);
6184
6238
  const entries = collectFiles(resolvedDir);
@@ -6234,7 +6288,7 @@ async function uploadDirectory(auth, workspaceId, dirPath, options) {
6234
6288
  });
6235
6289
  } else {
6236
6290
  try {
6237
- uploadable.push({ data: readFileAsBlob(f2.absolutePath, f2.size), name: f2.name });
6291
+ uploadable.push({ data: readFileAsBlob(f2.absolutePath, f2.size, f2.name), name: f2.name });
6238
6292
  } catch (err) {
6239
6293
  batchSkipped.push({
6240
6294
  file_name: f2.name,
@@ -6245,7 +6299,7 @@ async function uploadDirectory(auth, workspaceId, dirPath, options) {
6245
6299
  }
6246
6300
  let result = { doc_ext_ids: [], skipped: [] };
6247
6301
  if (uploadable.length > 0) {
6248
- result = await uploadFiles(auth, workspaceId, uploadable, {
6302
+ result = await uploadFiles(auth, uploadable, {
6249
6303
  folder,
6250
6304
  configExtId: options?.configExtId
6251
6305
  });
@@ -6270,7 +6324,7 @@ async function uploadDirectory(auth, workspaceId, dirPath, options) {
6270
6324
  }
6271
6325
  return { doc_ext_ids: allDocIds, skipped: allSkipped, folders };
6272
6326
  }
6273
- async function uploadZip(auth, workspaceId, zipPath, options) {
6327
+ async function uploadZip(auth, zipPath, options) {
6274
6328
  const JSZip = (await import('jszip')).default;
6275
6329
  const zipBuffer = fs2.readFileSync(zipPath);
6276
6330
  const zip = await JSZip.loadAsync(zipBuffer);
@@ -6334,7 +6388,7 @@ async function uploadZip(auth, workspaceId, zipPath, options) {
6334
6388
  data: new Blob([f2.data]),
6335
6389
  name: f2.name
6336
6390
  }));
6337
- const result = await uploadFiles(auth, workspaceId, blobs, {
6391
+ const result = await uploadFiles(auth, blobs, {
6338
6392
  folder,
6339
6393
  configExtId: options?.configExtId
6340
6394
  });
@@ -6405,7 +6459,7 @@ function isTransientError(err) {
6405
6459
  function sleep2(ms) {
6406
6460
  return new Promise((r2) => setTimeout(r2, ms));
6407
6461
  }
6408
- async function uploadManifest(auth, workspaceId, paths, options) {
6462
+ async function uploadManifest(auth, paths, options) {
6409
6463
  const maxRetries = Math.max(1, options?.maxRetries ?? 3);
6410
6464
  const outcomes = [];
6411
6465
  const summary = {
@@ -6526,7 +6580,7 @@ async function uploadManifest(auth, workspaceId, paths, options) {
6526
6580
  const readable = [];
6527
6581
  for (const f2 of batch) {
6528
6582
  try {
6529
- const blob = readFileAsBlob(f2.absolutePath, f2.size);
6583
+ const blob = readFileAsBlob(f2.absolutePath, f2.size, f2.basename);
6530
6584
  readable.push({ f: f2, blob });
6531
6585
  } catch (err) {
6532
6586
  const msg = err instanceof Error ? err.message : String(err);
@@ -6554,7 +6608,6 @@ async function uploadManifest(auth, workspaceId, paths, options) {
6554
6608
  try {
6555
6609
  result = await uploadFiles(
6556
6610
  auth,
6557
- workspaceId,
6558
6611
  readable.map((r2) => ({ data: r2.blob, name: r2.f.basename })),
6559
6612
  { folder, configExtId: options?.configExtId }
6560
6613
  );
@@ -6668,7 +6721,7 @@ function walkSupportedFiles(dirPath) {
6668
6721
  }
6669
6722
  return out.sort();
6670
6723
  }
6671
- async function uploadArchive(auth, workspaceId, archivePath, options) {
6724
+ async function uploadArchive(auth, archivePath, options) {
6672
6725
  try {
6673
6726
  execSync("7z --help", { stdio: "ignore" });
6674
6727
  } catch {
@@ -6687,7 +6740,7 @@ async function uploadArchive(auth, workspaceId, archivePath, options) {
6687
6740
  fs2.renameSync(tmpDir, namedDir);
6688
6741
  uploadDir = namedDir;
6689
6742
  }
6690
- return await uploadDirectory(auth, workspaceId, uploadDir, options);
6743
+ return await uploadDirectory(auth, uploadDir, options);
6691
6744
  } finally {
6692
6745
  fs2.rmSync(tmpDir, { recursive: true, force: true });
6693
6746
  }