@scalemule/sdk 0.0.15 → 0.0.18

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.ts CHANGED
@@ -881,6 +881,21 @@ interface UploadCompleteResponse {
881
881
  already_completed: boolean;
882
882
  scan_queued: boolean;
883
883
  }
884
+ interface UploadFailureReport {
885
+ fileId: string;
886
+ completionToken: string;
887
+ step: string;
888
+ errorCode: string;
889
+ errorMessage?: string;
890
+ httpStatus?: number;
891
+ attempt?: number;
892
+ diagnostics?: Record<string, unknown>;
893
+ }
894
+ interface UploadFailureReportResponse {
895
+ file_id: string;
896
+ recorded: boolean;
897
+ upload_status: string;
898
+ }
884
899
  interface MultipartStartResponse {
885
900
  upload_session_id: string;
886
901
  file_id: string;
@@ -947,6 +962,7 @@ declare class StorageService extends ServiceModule {
947
962
  getUploadUrl(filename: string, contentType: string, options?: {
948
963
  isPublic?: boolean;
949
964
  expiresIn?: number;
965
+ sizeBytes?: number;
950
966
  metadata?: Record<string, unknown>;
951
967
  }, requestOptions?: RequestOptions): Promise<ApiResponse<PresignedUploadResponse>>;
952
968
  /**
@@ -957,6 +973,11 @@ declare class StorageService extends ServiceModule {
957
973
  sizeBytes?: number;
958
974
  checksum?: string;
959
975
  }, requestOptions?: RequestOptions): Promise<ApiResponse<UploadCompleteResponse>>;
976
+ /**
977
+ * Persist a structured client-side upload failure against a file record.
978
+ * Best used by split-upload clients that call getUploadUrl() manually.
979
+ */
980
+ reportUploadFailure(params: UploadFailureReport, requestOptions?: RequestOptions): Promise<ApiResponse<UploadFailureReportResponse>>;
960
981
  /** Start a multipart upload session. */
961
982
  startMultipartUpload(params: {
962
983
  filename: string;
@@ -1050,6 +1071,7 @@ declare class StorageService extends ServiceModule {
1050
1071
  private defaultChunkSize;
1051
1072
  private defaultConcurrency;
1052
1073
  private maybeCompress;
1074
+ private reportUploadFailureBestEffort;
1053
1075
  private getOrCreateTelemetry;
1054
1076
  /** Build RequestOptions with X-Upload-Session-Id header for cross-boundary correlation */
1055
1077
  private withSessionHeader;
@@ -1252,6 +1274,73 @@ declare function getPartRange(partNumber: number, chunkSize: number, totalSize:
1252
1274
  size: number;
1253
1275
  };
1254
1276
 
1277
+ /**
1278
+ * Standalone S3 upload utilities for browser environments.
1279
+ *
1280
+ * These functions handle the client-side portion of presigned URL uploads:
1281
+ * - Single PUT for small files (with retry + stall detection)
1282
+ * - Multipart chunked upload for large files (parallel parts, per-chunk retry, ETag collection)
1283
+ *
1284
+ * Used by any app that gets presigned URLs from the server and needs to upload to S3.
1285
+ * The server-side proxy routes are app-specific; these utilities are app-agnostic.
1286
+ */
1287
+ interface S3UploadProgress {
1288
+ loaded: number;
1289
+ total: number;
1290
+ percentage: number;
1291
+ }
1292
+ interface S3SingleUploadOptions {
1293
+ onProgress?: (progress: S3UploadProgress) => void;
1294
+ signal?: AbortSignal;
1295
+ /** Max retries per attempt (default: 3) */
1296
+ maxRetries?: number;
1297
+ /** Stall timeout in ms — abort if no progress for this long (default: 45000) */
1298
+ stallTimeoutMs?: number;
1299
+ }
1300
+ interface S3SingleUploadResult {
1301
+ success: boolean;
1302
+ error?: string;
1303
+ }
1304
+ interface MultipartPartUrl {
1305
+ partNumber: number;
1306
+ url: string;
1307
+ }
1308
+ interface MultipartConfig {
1309
+ partSizeBytes: number;
1310
+ totalParts: number;
1311
+ partUrls: MultipartPartUrl[];
1312
+ /** Fetch fresh URLs when needed (e.g., on 403 expiry). App provides this via its proxy route. */
1313
+ fetchMoreUrls?: (partNumbers: number[]) => Promise<MultipartPartUrl[] | null>;
1314
+ }
1315
+ interface S3MultipartOptions {
1316
+ onProgress?: (progress: S3UploadProgress) => void;
1317
+ signal?: AbortSignal;
1318
+ /** Max concurrent part uploads (default: 3) */
1319
+ concurrency?: number;
1320
+ /** Max retries per part (default: 3) */
1321
+ maxRetries?: number;
1322
+ }
1323
+ interface PartResult {
1324
+ partNumber: number;
1325
+ etag: string;
1326
+ }
1327
+ interface S3MultipartResult {
1328
+ success: boolean;
1329
+ parts?: PartResult[];
1330
+ error?: string;
1331
+ }
1332
+ /**
1333
+ * Upload a file to S3 via a single presigned PUT.
1334
+ * Includes retry on 5xx/network errors and stall detection.
1335
+ */
1336
+ declare function uploadSingleToS3(url: string, file: File | Blob, options?: S3SingleUploadOptions): Promise<S3SingleUploadResult>;
1337
+ /**
1338
+ * Upload a file to S3 using multipart chunked upload.
1339
+ * Splits the file into chunks, uploads in parallel with per-chunk retry,
1340
+ * collects ETags for completion.
1341
+ */
1342
+ declare function uploadMultipartToS3(file: File | Blob, config: MultipartConfig, options?: S3MultipartOptions): Promise<S3MultipartResult>;
1343
+
1255
1344
  /**
1256
1345
  * Realtime Service Module
1257
1346
  *
@@ -5152,4 +5241,4 @@ declare class ScaleMule {
5152
5241
  getClient(): ScaleMuleClient;
5153
5242
  }
5154
5243
 
5155
- export { type AccountBalance, AccountsService, type ActiveUsers, type ActivityItem, AgentAuthService, AgentModelsService, type AgentProfile, AgentProjectsService, type AgentResponse, type AgentSecurityPolicy, AgentSessionsService, type AgentSigningKey, type AgentToken, type AgentToolEntitlement, AgentToolsService, type Workspace as AgentWorkspace, AgentsService, type AggregateOptions, type AggregateResult, type AnalyticsEvent, AnalyticsService, type ApiError, type ApiKey, type ApiResponse, type Appeal, type Application, type Attachment, type Attendee, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type CacheEntry, CacheService, type CalendarEvent, type CatalogEntry, CatalogService, type ChatMessage, type ChatReaction, ChatService, type ClaimResult, type Client, type ClientContext, type Collection, type Comment, CommunicationService, type CompletedPart, ComplianceService, type CompressionConfig, type ConnectedAccount, type ConnectedAccountSubscription, type ConnectedSetupIntentResponse, type ConnectedSubscriptionListParams, type ConnectionStatus, type ContentFlag, type Conversation, type CostReportDay, type CreateFlagRequest, type CreateRuleRequest, type CreateSegmentRequest, type CreateSessionResponse, type CreateVariantRequest, type Credential, type CredentialScope, type Customer, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DeviceInfo, type Document, type ErrorCode, ErrorCodes, type EventAggregation, EventsService, type FileInfo, type FlagAuditEntry, type FlagCheck, type FlagCondition, FlagContentService, type FlagDefinition, type FlagDetail, type FlagEnvironment, type FlagEvaluation, type FlagSegment, type FlagVariant, FlagsService, type FollowStatus, type FunctionExecution, type FunctionMetrics, FunctionsService, type Funnel, type FunnelConversion, type GdprRequest, type GrantInfo, type GraphEdge, type GraphNode, GraphService, IdentityService, type IdentityType, type IncomingRequestLike, type Invoice, type JobExecution, type JobStats, type Leaderboard, type LeaderboardEntry, LeaderboardService, type Like, type Listing, ListingsService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, type MessageCallback, type MessageStatus, type MetricDataPoint, type MfaStatus, type Model, type ModelEntitlement, type ModelPricing, type ModelProvider, type UsageSummary as ModelUsageSummary, type MultipartCompleteResponse, type MultipartPartUrlsResponse, type MultipartStartResponse, type NetworkClass, type OAuthProvider, type OAuthUrl, OrchestratorService, PHOTO_BREAKPOINTS, type PaginatedResponse, type PaginationMetadata, type PaginationParams, type PartUrl, type Participant, type Payment, type PaymentListParams, type PaymentMethod, type PaymentStatusResponse, type Payout, type PayoutSchedule, type PermissionCheck, type PermissionMatrix, PermissionsService, type PhotoInfo, PhotoService, type Pipeline, type PipelineVersion, type Policy, type PresenceCallback, type PresenceEvent, type PresignedUploadResponse, type Price, type Product, type Project, type ProjectDocument, type ProjectGrant, type ProjectMember, type PushToken, type QueryFilter, type QueryOptions, type QuerySort, type QueueJob, QueueService, type ReadStatus, RealtimeService, type RedeemResult, type Refund, type RegisterAgentRequest, type RegisterAgentResponse, type RequestOptions, type ResumeSession, type Role, type RuntimeTemplate, type RuntimeTemplateVersion, ScaleMule, ScaleMuleClient, type ScaleMuleConfig, type SchedulerJob, SchedulerService, type SearchResult, SearchService, type SecurityLayers, type ServerlessFunction, type ServiceHealth, ServiceModule, type Session, type SessionArtifact, type SessionInfo, type SessionLog, type Severity, type ShortestPathResult, type SignedUrlResponse, type SocialPost, SocialService, type SocialUser, type SsoConfig, type StatusCallback, type StorageAdapter, StorageService, type StrategyResult, type SubmitResult, type Subscription, type TargetingRule, type Task, type TaskAttempt, type TaskTransition, type Team, type TeamInvitation, type TeamMember, TeamsService, type TelemetryPayload, type Tool, type ToolCapability, type ToolIntegration, type TopEvent, type TotpSetup, type Transaction, type TransactionListParams, type TransactionSummary, type TransactionSummaryParams, type Transfer, type TransformOptions, type TransformResult, type TraversalResult, type UpdateFlagRequest, type UpdateRuleRequest, type UpdateSegmentRequest, type UpdateVariantRequest, type UploadCompleteResponse, type UploadEngineConfig, type UploadOptions, type UploadPlan, UploadResumeStore, type UploadStrategy, UploadTelemetry, type UploadTelemetryConfig, type UploadTelemetryEvent, type UpsertEnvironmentRequest, type UsageRecord, type UsageSummary$1 as UsageSummary, type UserRank, type VideoInfo, VideoService, type VideoUploadOptions, type Webhook, WebhooksService, type Workflow, type WorkflowExecution, type Workspace$1 as Workspace, type WorkspaceInvitation, type WorkspaceMember, WorkspacesService, buildClientContextHeaders, calculateTotalParts, canPerform, createUploadPlan, ScaleMule as default, detectNetworkClass, extractClientContext, generateUploadSessionId, getMeasuredBandwidthMbps, getPartRange, hasMinRoleLevel, resolveStrategy, validateIP };
5244
+ export { type AccountBalance, AccountsService, type ActiveUsers, type ActivityItem, AgentAuthService, AgentModelsService, type AgentProfile, AgentProjectsService, type AgentResponse, type AgentSecurityPolicy, AgentSessionsService, type AgentSigningKey, type AgentToken, type AgentToolEntitlement, AgentToolsService, type Workspace as AgentWorkspace, AgentsService, type AggregateOptions, type AggregateResult, type AnalyticsEvent, AnalyticsService, type ApiError, type ApiKey, type ApiResponse, type Appeal, type Application, type Attachment, type Attendee, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type CacheEntry, CacheService, type CalendarEvent, type CatalogEntry, CatalogService, type ChatMessage, type ChatReaction, ChatService, type ClaimResult, type Client, type ClientContext, type Collection, type Comment, CommunicationService, type CompletedPart, ComplianceService, type CompressionConfig, type ConnectedAccount, type ConnectedAccountSubscription, type ConnectedSetupIntentResponse, type ConnectedSubscriptionListParams, type ConnectionStatus, type ContentFlag, type Conversation, type CostReportDay, type CreateFlagRequest, type CreateRuleRequest, type CreateSegmentRequest, type CreateSessionResponse, type CreateVariantRequest, type Credential, type CredentialScope, type Customer, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DeviceInfo, type Document, type ErrorCode, ErrorCodes, type EventAggregation, EventsService, type FileInfo, type FlagAuditEntry, type FlagCheck, type FlagCondition, FlagContentService, type FlagDefinition, type FlagDetail, type FlagEnvironment, type FlagEvaluation, type FlagSegment, type FlagVariant, FlagsService, type FollowStatus, type FunctionExecution, type FunctionMetrics, FunctionsService, type Funnel, type FunnelConversion, type GdprRequest, type GrantInfo, type GraphEdge, type GraphNode, GraphService, IdentityService, type IdentityType, type IncomingRequestLike, type Invoice, type JobExecution, type JobStats, type Leaderboard, type LeaderboardEntry, LeaderboardService, type Like, type Listing, ListingsService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, type MessageCallback, type MessageStatus, type MetricDataPoint, type MfaStatus, type Model, type ModelEntitlement, type ModelPricing, type ModelProvider, type UsageSummary as ModelUsageSummary, type MultipartCompleteResponse, type MultipartConfig, type MultipartPartUrl, type MultipartPartUrlsResponse, type MultipartStartResponse, type NetworkClass, type OAuthProvider, type OAuthUrl, OrchestratorService, PHOTO_BREAKPOINTS, type PaginatedResponse, type PaginationMetadata, type PaginationParams, type PartResult, type PartUrl, type Participant, type Payment, type PaymentListParams, type PaymentMethod, type PaymentStatusResponse, type Payout, type PayoutSchedule, type PermissionCheck, type PermissionMatrix, PermissionsService, type PhotoInfo, PhotoService, type Pipeline, type PipelineVersion, type Policy, type PresenceCallback, type PresenceEvent, type PresignedUploadResponse, type Price, type Product, type Project, type ProjectDocument, type ProjectGrant, type ProjectMember, type PushToken, type QueryFilter, type QueryOptions, type QuerySort, type QueueJob, QueueService, type ReadStatus, RealtimeService, type RedeemResult, type Refund, type RegisterAgentRequest, type RegisterAgentResponse, type RequestOptions, type ResumeSession, type Role, type RuntimeTemplate, type RuntimeTemplateVersion, type S3MultipartOptions, type S3MultipartResult, type S3SingleUploadOptions, type S3SingleUploadResult, type S3UploadProgress, ScaleMule, ScaleMuleClient, type ScaleMuleConfig, type SchedulerJob, SchedulerService, type SearchResult, SearchService, type SecurityLayers, type ServerlessFunction, type ServiceHealth, ServiceModule, type Session, type SessionArtifact, type SessionInfo, type SessionLog, type Severity, type ShortestPathResult, type SignedUrlResponse, type SocialPost, SocialService, type SocialUser, type SsoConfig, type StatusCallback, type StorageAdapter, StorageService, type StrategyResult, type SubmitResult, type Subscription, type TargetingRule, type Task, type TaskAttempt, type TaskTransition, type Team, type TeamInvitation, type TeamMember, TeamsService, type TelemetryPayload, type Tool, type ToolCapability, type ToolIntegration, type TopEvent, type TotpSetup, type Transaction, type TransactionListParams, type TransactionSummary, type TransactionSummaryParams, type Transfer, type TransformOptions, type TransformResult, type TraversalResult, type UpdateFlagRequest, type UpdateRuleRequest, type UpdateSegmentRequest, type UpdateVariantRequest, type UploadCompleteResponse, type UploadEngineConfig, type UploadFailureReport, type UploadFailureReportResponse, type UploadOptions, type UploadPlan, UploadResumeStore, type UploadStrategy, UploadTelemetry, type UploadTelemetryConfig, type UploadTelemetryEvent, type UpsertEnvironmentRequest, type UsageRecord, type UsageSummary$1 as UsageSummary, type UserRank, type VideoInfo, VideoService, type VideoUploadOptions, type Webhook, WebhooksService, type Workflow, type WorkflowExecution, type Workspace$1 as Workspace, type WorkspaceInvitation, type WorkspaceMember, WorkspacesService, buildClientContextHeaders, calculateTotalParts, canPerform, createUploadPlan, ScaleMule as default, detectNetworkClass, extractClientContext, generateUploadSessionId, getMeasuredBandwidthMbps, getPartRange, hasMinRoleLevel, resolveStrategy, uploadMultipartToS3, uploadSingleToS3, validateIP };
package/dist/index.js CHANGED
@@ -359,6 +359,8 @@ __export(index_exports, {
359
359
  normalizeAndValidatePhone: () => import_phone.normalizeAndValidatePhone,
360
360
  normalizePhoneNumber: () => import_phone.normalizePhoneNumber,
361
361
  resolveStrategy: () => resolveStrategy,
362
+ uploadMultipartToS3: () => uploadMultipartToS3,
363
+ uploadSingleToS3: () => uploadSingleToS3,
362
364
  validateIP: () => validateIP
363
365
  });
364
366
  module.exports = __toCommonJS(index_exports);
@@ -1848,6 +1850,22 @@ var StorageService = class extends ServiceModule {
1848
1850
  file_id,
1849
1851
  reason: uploadResult.error.code
1850
1852
  });
1853
+ await this.reportUploadFailureBestEffort(
1854
+ {
1855
+ fileId: file_id,
1856
+ completionToken: completion_token,
1857
+ step: "s3_put",
1858
+ errorCode: uploadResult.error.code,
1859
+ errorMessage: uploadResult.error.message,
1860
+ httpStatus: uploadResult.error.status || void 0,
1861
+ attempt: asNumber2(uploadResult.error.details?.attempt),
1862
+ diagnostics: {
1863
+ ...getUploadEnvironmentDiagnostics(),
1864
+ ...uploadResult.error.details || {}
1865
+ }
1866
+ },
1867
+ requestOpts
1868
+ );
1851
1869
  return { data: null, error: uploadResult.error };
1852
1870
  }
1853
1871
  const completeResult = await this.post(
@@ -1865,6 +1883,21 @@ var StorageService = class extends ServiceModule {
1865
1883
  file_id,
1866
1884
  duration_ms: Date.now() - directStart
1867
1885
  });
1886
+ await this.reportUploadFailureBestEffort(
1887
+ {
1888
+ fileId: file_id,
1889
+ completionToken: completion_token,
1890
+ step: "complete",
1891
+ errorCode: completeResult.error.code,
1892
+ errorMessage: completeResult.error.message,
1893
+ httpStatus: completeResult.error.status || void 0,
1894
+ diagnostics: {
1895
+ ...getUploadEnvironmentDiagnostics(),
1896
+ duration_ms: Date.now() - directStart
1897
+ }
1898
+ },
1899
+ requestOpts
1900
+ );
1868
1901
  } else {
1869
1902
  telemetry?.emit(sessionId, "upload.completed", {
1870
1903
  file_id,
@@ -2027,6 +2060,17 @@ var StorageService = class extends ServiceModule {
2027
2060
  if (options?.signal?.aborted) {
2028
2061
  await this.abortMultipart(upload_session_id, completionToken, requestOpts);
2029
2062
  telemetry?.emit(sessionId, "upload.aborted", { file_id });
2063
+ await this.reportUploadFailureBestEffort(
2064
+ {
2065
+ fileId: file_id,
2066
+ completionToken,
2067
+ step: "multipart_abort",
2068
+ errorCode: "aborted",
2069
+ errorMessage: "Upload aborted",
2070
+ diagnostics: getUploadEnvironmentDiagnostics()
2071
+ },
2072
+ requestOpts
2073
+ );
2030
2074
  return { data: null, error: { code: "aborted", message: "Upload aborted", status: 0 } };
2031
2075
  }
2032
2076
  const remainingUrlCount = pendingParts.slice(partIndex).filter((p) => availableUrls.has(p)).length;
@@ -2128,6 +2172,20 @@ var StorageService = class extends ServiceModule {
2128
2172
  const errorMsg = result.error || "Part upload returned no ETag";
2129
2173
  await this.abortMultipart(upload_session_id, completionToken, requestOpts);
2130
2174
  telemetry?.emit(sessionId, "upload.multipart.aborted", { file_id, error: errorMsg });
2175
+ await this.reportUploadFailureBestEffort(
2176
+ {
2177
+ fileId: file_id,
2178
+ completionToken,
2179
+ step: "multipart_part",
2180
+ errorCode: "upload_error",
2181
+ errorMessage: errorMsg,
2182
+ diagnostics: {
2183
+ ...getUploadEnvironmentDiagnostics(),
2184
+ part_number: result.partNum
2185
+ }
2186
+ },
2187
+ requestOpts
2188
+ );
2131
2189
  return {
2132
2190
  data: null,
2133
2191
  error: { code: "upload_error", message: `Part ${result.partNum} failed: ${errorMsg}`, status: 0 }
@@ -2167,6 +2225,21 @@ var StorageService = class extends ServiceModule {
2167
2225
  error: completeResult.error.message,
2168
2226
  duration_ms: Date.now() - multipartStart
2169
2227
  });
2228
+ await this.reportUploadFailureBestEffort(
2229
+ {
2230
+ fileId: file_id,
2231
+ completionToken,
2232
+ step: "multipart_complete",
2233
+ errorCode: completeResult.error.code,
2234
+ errorMessage: completeResult.error.message,
2235
+ httpStatus: completeResult.error.status || void 0,
2236
+ diagnostics: {
2237
+ ...getUploadEnvironmentDiagnostics(),
2238
+ duration_ms: Date.now() - multipartStart
2239
+ }
2240
+ },
2241
+ requestOpts
2242
+ );
2170
2243
  return { data: null, error: completeResult.error };
2171
2244
  }
2172
2245
  telemetry?.emit(sessionId, "upload.multipart.completed", {
@@ -2227,6 +2300,7 @@ var StorageService = class extends ServiceModule {
2227
2300
  content_type: contentType,
2228
2301
  is_public: options?.isPublic ?? true,
2229
2302
  expires_in: options?.expiresIn ?? 3600,
2303
+ size_bytes: options?.sizeBytes,
2230
2304
  metadata: options?.metadata
2231
2305
  },
2232
2306
  requestOptions
@@ -2248,6 +2322,26 @@ var StorageService = class extends ServiceModule {
2248
2322
  requestOptions
2249
2323
  );
2250
2324
  }
2325
+ /**
2326
+ * Persist a structured client-side upload failure against a file record.
2327
+ * Best used by split-upload clients that call getUploadUrl() manually.
2328
+ */
2329
+ async reportUploadFailure(params, requestOptions) {
2330
+ return this.post(
2331
+ "/signed-url/report-failure",
2332
+ {
2333
+ file_id: params.fileId,
2334
+ completion_token: params.completionToken,
2335
+ step: params.step,
2336
+ error_code: params.errorCode,
2337
+ error_message: params.errorMessage,
2338
+ http_status: params.httpStatus,
2339
+ attempt: params.attempt,
2340
+ diagnostics: params.diagnostics
2341
+ },
2342
+ requestOptions
2343
+ );
2344
+ }
2251
2345
  // --------------------------------------------------------------------------
2252
2346
  // Multipart Public API (for advanced/server-side usage)
2253
2347
  // --------------------------------------------------------------------------
@@ -2373,6 +2467,13 @@ var StorageService = class extends ServiceModule {
2373
2467
  telemetry?.emit(sessionId || "", "upload.retried", { attempt });
2374
2468
  }
2375
2469
  const result = await this.uploadToPresignedUrl(url, file, onProgress, signal);
2470
+ if (result.error) {
2471
+ result.error.details = {
2472
+ ...result.error.details || {},
2473
+ attempt: attempt + 1,
2474
+ max_attempts: RETRY_DELAYS.length
2475
+ };
2476
+ }
2376
2477
  if (!result.error) return result;
2377
2478
  if (result.error.code === "aborted") return result;
2378
2479
  if (result.error.status && NON_RETRYABLE_STATUS_CODES.has(result.error.status)) {
@@ -2424,7 +2525,12 @@ var StorageService = class extends ServiceModule {
2424
2525
  error: {
2425
2526
  code: "upload_error",
2426
2527
  message: `S3 upload failed: ${response.status} ${response.statusText}`,
2427
- status: response.status
2528
+ status: response.status,
2529
+ details: {
2530
+ transport: "fetch",
2531
+ total_bytes: file.size,
2532
+ online: getOnlineStatus()
2533
+ }
2428
2534
  }
2429
2535
  };
2430
2536
  }
@@ -2442,7 +2548,12 @@ var StorageService = class extends ServiceModule {
2442
2548
  error: {
2443
2549
  code: isStall ? "upload_stalled" : "upload_error",
2444
2550
  message: isStall ? `Upload stalled (no progress for ${stallTimeout / 1e3}s)` : err instanceof Error ? err.message : "S3 upload failed",
2445
- status: 0
2551
+ status: 0,
2552
+ details: {
2553
+ transport: "fetch",
2554
+ total_bytes: file.size,
2555
+ online: getOnlineStatus()
2556
+ }
2446
2557
  }
2447
2558
  };
2448
2559
  }
@@ -2452,6 +2563,8 @@ var StorageService = class extends ServiceModule {
2452
2563
  const xhr = new XMLHttpRequest();
2453
2564
  const stallTimeout = getStallTimeout();
2454
2565
  let stallTimer = null;
2566
+ let lastLoaded = 0;
2567
+ let totalBytes = file.size;
2455
2568
  const resetStallTimer = () => {
2456
2569
  if (stallTimer !== null) clearTimeout(stallTimer);
2457
2570
  stallTimer = setTimeout(() => {
@@ -2461,7 +2574,14 @@ var StorageService = class extends ServiceModule {
2461
2574
  error: {
2462
2575
  code: "upload_stalled",
2463
2576
  message: `Upload stalled (no progress for ${stallTimeout / 1e3}s)`,
2464
- status: 0
2577
+ status: 0,
2578
+ details: {
2579
+ transport: "xhr",
2580
+ bytes_sent: lastLoaded,
2581
+ total_bytes: totalBytes,
2582
+ progress_percent: totalBytes > 0 ? Math.round(lastLoaded / totalBytes * 100) : void 0,
2583
+ online: getOnlineStatus()
2584
+ }
2465
2585
  }
2466
2586
  });
2467
2587
  }, stallTimeout);
@@ -2488,6 +2608,8 @@ var StorageService = class extends ServiceModule {
2488
2608
  }
2489
2609
  xhr.upload.addEventListener("progress", (event) => {
2490
2610
  resetStallTimer();
2611
+ lastLoaded = event.loaded;
2612
+ totalBytes = event.total || totalBytes;
2491
2613
  if (event.lengthComputable && onProgress) {
2492
2614
  onProgress(Math.round(event.loaded / event.total * 100));
2493
2615
  }
@@ -2503,7 +2625,14 @@ var StorageService = class extends ServiceModule {
2503
2625
  error: {
2504
2626
  code: "upload_error",
2505
2627
  message: `S3 upload failed: ${xhr.status}`,
2506
- status: xhr.status
2628
+ status: xhr.status,
2629
+ details: {
2630
+ transport: "xhr",
2631
+ bytes_sent: lastLoaded,
2632
+ total_bytes: totalBytes,
2633
+ progress_percent: totalBytes > 0 ? Math.round(lastLoaded / totalBytes * 100) : void 0,
2634
+ online: getOnlineStatus()
2635
+ }
2507
2636
  }
2508
2637
  });
2509
2638
  }
@@ -2512,7 +2641,18 @@ var StorageService = class extends ServiceModule {
2512
2641
  clearStallTimer();
2513
2642
  resolve({
2514
2643
  data: null,
2515
- error: { code: "upload_error", message: "S3 upload failed", status: 0 }
2644
+ error: {
2645
+ code: "upload_error",
2646
+ message: "S3 upload failed",
2647
+ status: 0,
2648
+ details: {
2649
+ transport: "xhr",
2650
+ bytes_sent: lastLoaded,
2651
+ total_bytes: totalBytes,
2652
+ progress_percent: totalBytes > 0 ? Math.round(lastLoaded / totalBytes * 100) : void 0,
2653
+ online: getOnlineStatus()
2654
+ }
2655
+ }
2516
2656
  });
2517
2657
  });
2518
2658
  xhr.addEventListener("abort", () => {
@@ -2621,6 +2761,12 @@ var StorageService = class extends ServiceModule {
2621
2761
  return null;
2622
2762
  }
2623
2763
  }
2764
+ async reportUploadFailureBestEffort(params, requestOptions) {
2765
+ try {
2766
+ await this.reportUploadFailure(params, requestOptions);
2767
+ } catch {
2768
+ }
2769
+ }
2624
2770
  getOrCreateTelemetry() {
2625
2771
  if (!this.telemetry) {
2626
2772
  this.telemetry = new UploadTelemetry(this.client);
@@ -2660,6 +2806,38 @@ function getNetworkEffectiveType2() {
2660
2806
  }
2661
2807
  return "4g";
2662
2808
  }
2809
+ function getOnlineStatus() {
2810
+ if (typeof navigator === "undefined") return void 0;
2811
+ return navigator.onLine;
2812
+ }
2813
+ function getUploadEnvironmentDiagnostics() {
2814
+ const diagnostics = {
2815
+ network_type: getNetworkEffectiveType2(),
2816
+ online: getOnlineStatus()
2817
+ };
2818
+ if (typeof navigator !== "undefined") {
2819
+ const nav = navigator;
2820
+ if (typeof nav.hardwareConcurrency === "number") {
2821
+ diagnostics.hardware_concurrency = nav.hardwareConcurrency;
2822
+ }
2823
+ if (typeof nav.deviceMemory === "number") {
2824
+ diagnostics.device_memory_gb = nav.deviceMemory;
2825
+ }
2826
+ if (nav.connection?.downlink != null) {
2827
+ diagnostics.downlink_mbps = nav.connection.downlink;
2828
+ }
2829
+ if (nav.connection?.rtt != null) {
2830
+ diagnostics.rtt_ms = nav.connection.rtt;
2831
+ }
2832
+ }
2833
+ if (typeof document !== "undefined") {
2834
+ diagnostics.visibility_state = document.visibilityState;
2835
+ }
2836
+ return diagnostics;
2837
+ }
2838
+ function asNumber2(value) {
2839
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
2840
+ }
2663
2841
 
2664
2842
  // src/index.ts
2665
2843
  init_upload_resume();
@@ -2758,6 +2936,199 @@ function getPartRange(partNumber, chunkSize, totalSize) {
2758
2936
  return { start, end, size: end - start };
2759
2937
  }
2760
2938
 
2939
+ // src/services/upload-to-s3.ts
2940
+ var DEFAULT_RETRY_DELAYS = [0, 1e3, 3e3];
2941
+ var DEFAULT_STALL_TIMEOUT_MS3 = 45e3;
2942
+ var DEFAULT_CONCURRENCY = 3;
2943
+ async function uploadSingleToS3(url, file, options) {
2944
+ const maxRetries = options?.maxRetries ?? 3;
2945
+ const retryDelays = DEFAULT_RETRY_DELAYS.slice(0, maxRetries);
2946
+ const stallTimeout = options?.stallTimeoutMs ?? DEFAULT_STALL_TIMEOUT_MS3;
2947
+ for (let attempt = 0; attempt < retryDelays.length; attempt++) {
2948
+ if (attempt > 0) {
2949
+ await sleep3(retryDelays[attempt] || 1e3);
2950
+ }
2951
+ if (options?.signal?.aborted) {
2952
+ return { success: false, error: "Upload aborted" };
2953
+ }
2954
+ const result = await doSinglePut(url, file, options?.onProgress, options?.signal, stallTimeout);
2955
+ if (result === "success") return { success: true };
2956
+ if (result === "abort") return { success: false, error: "Upload aborted" };
2957
+ if (result === "stall") return { success: false, error: "Upload stalled \u2014 no progress" };
2958
+ }
2959
+ return { success: false, error: "Upload failed after retries" };
2960
+ }
2961
+ function doSinglePut(url, file, onProgress, signal, stallTimeoutMs) {
2962
+ return new Promise((resolve) => {
2963
+ const xhr = new XMLHttpRequest();
2964
+ let stallTimer = null;
2965
+ const resetStallTimer = () => {
2966
+ if (stallTimer) clearTimeout(stallTimer);
2967
+ if (stallTimeoutMs) {
2968
+ stallTimer = setTimeout(() => {
2969
+ xhr.abort();
2970
+ resolve("stall");
2971
+ }, stallTimeoutMs);
2972
+ }
2973
+ };
2974
+ xhr.upload.addEventListener("progress", (e) => {
2975
+ resetStallTimer();
2976
+ if (e.lengthComputable && onProgress) {
2977
+ onProgress({
2978
+ loaded: e.loaded,
2979
+ total: e.total,
2980
+ percentage: Math.round(e.loaded / e.total * 100)
2981
+ });
2982
+ }
2983
+ });
2984
+ xhr.addEventListener("load", () => {
2985
+ if (stallTimer) clearTimeout(stallTimer);
2986
+ if (xhr.status >= 200 && xhr.status < 300) {
2987
+ resolve("success");
2988
+ } else if (xhr.status >= 500) {
2989
+ resolve("retry");
2990
+ } else {
2991
+ resolve("retry");
2992
+ }
2993
+ });
2994
+ xhr.addEventListener("error", () => {
2995
+ if (stallTimer) clearTimeout(stallTimer);
2996
+ resolve("retry");
2997
+ });
2998
+ xhr.addEventListener("abort", () => {
2999
+ if (stallTimer) clearTimeout(stallTimer);
3000
+ });
3001
+ if (signal) {
3002
+ signal.addEventListener(
3003
+ "abort",
3004
+ () => {
3005
+ xhr.abort();
3006
+ if (stallTimer) clearTimeout(stallTimer);
3007
+ resolve("abort");
3008
+ },
3009
+ { once: true }
3010
+ );
3011
+ }
3012
+ xhr.open("PUT", url);
3013
+ xhr.setRequestHeader("Content-Type", file.type || "application/octet-stream");
3014
+ resetStallTimer();
3015
+ xhr.send(file);
3016
+ });
3017
+ }
3018
+ async function uploadMultipartToS3(file, config, options) {
3019
+ const { partSizeBytes, totalParts, partUrls: initialPartUrls, fetchMoreUrls } = config;
3020
+ const concurrency = options?.concurrency ?? DEFAULT_CONCURRENCY;
3021
+ const maxRetries = options?.maxRetries ?? 3;
3022
+ const completedParts = [];
3023
+ const availableUrls = /* @__PURE__ */ new Map();
3024
+ for (const pu of initialPartUrls) {
3025
+ availableUrls.set(pu.partNumber, pu.url);
3026
+ }
3027
+ let totalUploaded = 0;
3028
+ for (let i = 0; i < totalParts; i += concurrency) {
3029
+ if (options?.signal?.aborted) {
3030
+ return { success: false, error: "Upload aborted" };
3031
+ }
3032
+ const batchPartNumbers = [];
3033
+ for (let j = i; j < Math.min(i + concurrency, totalParts); j++) {
3034
+ batchPartNumbers.push(j + 1);
3035
+ }
3036
+ const missingUrls = batchPartNumbers.filter((p) => !availableUrls.has(p));
3037
+ if (missingUrls.length > 0 && fetchMoreUrls) {
3038
+ const fetched = await fetchMoreUrls(missingUrls);
3039
+ if (fetched) {
3040
+ for (const pu of fetched) availableUrls.set(pu.partNumber, pu.url);
3041
+ }
3042
+ }
3043
+ const results = await Promise.all(
3044
+ batchPartNumbers.map(async (partNum) => {
3045
+ const url = availableUrls.get(partNum);
3046
+ if (!url) return { partNum, error: "No URL available" };
3047
+ const start = (partNum - 1) * partSizeBytes;
3048
+ const end = Math.min(start + partSizeBytes, file.size);
3049
+ const blob = file.slice(start, end);
3050
+ let result = await uploadPartWithRetry(url, blob, partNum, maxRetries, options?.signal);
3051
+ if (!result && fetchMoreUrls) {
3052
+ const freshUrls = await fetchMoreUrls([partNum]);
3053
+ if (freshUrls?.[0]) {
3054
+ availableUrls.set(partNum, freshUrls[0].url);
3055
+ result = await uploadPartWithRetry(freshUrls[0].url, blob, partNum, maxRetries, options?.signal);
3056
+ }
3057
+ }
3058
+ if (result) {
3059
+ totalUploaded += end - start;
3060
+ options?.onProgress?.({
3061
+ loaded: totalUploaded,
3062
+ total: file.size,
3063
+ percentage: Math.round(totalUploaded / file.size * 100)
3064
+ });
3065
+ return { partNum, etag: result.etag };
3066
+ }
3067
+ return { partNum, error: "Part upload failed after retries" };
3068
+ })
3069
+ );
3070
+ for (const result of results) {
3071
+ if ("error" in result) {
3072
+ return { success: false, error: `Part ${result.partNum}: ${result.error}` };
3073
+ }
3074
+ completedParts.push({ partNumber: result.partNum, etag: result.etag });
3075
+ }
3076
+ }
3077
+ return {
3078
+ success: true,
3079
+ parts: completedParts.sort((a, b) => a.partNumber - b.partNumber)
3080
+ };
3081
+ }
3082
+ async function uploadPartWithRetry(url, blob, _partNumber, maxRetries, signal) {
3083
+ const retryDelays = DEFAULT_RETRY_DELAYS.slice(0, maxRetries);
3084
+ for (let attempt = 0; attempt < retryDelays.length; attempt++) {
3085
+ if (attempt > 0) await sleep3(retryDelays[attempt] || 1e3);
3086
+ if (signal?.aborted) return null;
3087
+ const result = await doPartPut(url, blob, signal);
3088
+ if (result === "abort") return null;
3089
+ if (typeof result === "object") return result;
3090
+ }
3091
+ return null;
3092
+ }
3093
+ function doPartPut(url, blob, signal) {
3094
+ return new Promise((resolve) => {
3095
+ const xhr = new XMLHttpRequest();
3096
+ xhr.addEventListener("load", () => {
3097
+ if (xhr.status >= 200 && xhr.status < 300) {
3098
+ const etag = xhr.getResponseHeader("etag");
3099
+ if (etag) {
3100
+ resolve({ etag });
3101
+ } else {
3102
+ resolve("retry");
3103
+ }
3104
+ } else if (xhr.status === 403) {
3105
+ resolve("retry");
3106
+ } else if (xhr.status >= 500) {
3107
+ resolve("retry");
3108
+ } else {
3109
+ resolve("retry");
3110
+ }
3111
+ });
3112
+ xhr.addEventListener("error", () => resolve("retry"));
3113
+ xhr.addEventListener("abort", () => resolve("abort"));
3114
+ if (signal) {
3115
+ signal.addEventListener(
3116
+ "abort",
3117
+ () => {
3118
+ xhr.abort();
3119
+ resolve("abort");
3120
+ },
3121
+ { once: true }
3122
+ );
3123
+ }
3124
+ xhr.open("PUT", url);
3125
+ xhr.send(blob);
3126
+ });
3127
+ }
3128
+ function sleep3(ms) {
3129
+ return new Promise((r) => setTimeout(r, ms));
3130
+ }
3131
+
2761
3132
  // src/services/realtime.ts
2762
3133
  var DEFAULT_RECONNECT_BASE_MS = 1e3;
2763
3134
  var MAX_RECONNECT_MS = 3e4;
@@ -4419,8 +4790,8 @@ var SearchService = class extends ServiceModule {
4419
4790
  async query(queryStr, queryOptions, requestOptions) {
4420
4791
  return this.post("", { query: queryStr, ...queryOptions }, requestOptions);
4421
4792
  }
4422
- async index(indexName, document, options) {
4423
- return this.post("/documents", { index: indexName, ...document }, options);
4793
+ async index(indexName, document2, options) {
4794
+ return this.post("/documents", { index: indexName, ...document2 }, options);
4424
4795
  }
4425
4796
  async removeDocument(indexName, docId, options) {
4426
4797
  return this.del(`/documents/${indexName}/${docId}`, options);
@@ -5449,5 +5820,7 @@ var index_default = ScaleMule;
5449
5820
  normalizeAndValidatePhone,
5450
5821
  normalizePhoneNumber,
5451
5822
  resolveStrategy,
5823
+ uploadMultipartToS3,
5824
+ uploadSingleToS3,
5452
5825
  validateIP
5453
5826
  });