@scalemule/sdk 0.0.47 → 0.0.49

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.mts CHANGED
@@ -153,6 +153,12 @@ interface ScaleMuleConfig {
153
153
  * recover stripped fields for existing entries until those accounts log in again.
154
154
  */
155
155
  accountSwitcherPrivacy?: AccountSwitcherPrivacy;
156
+ /** Callback when a 401 auto-refresh starts */
157
+ onRefreshStart?: () => void;
158
+ /** Callback when a 401 auto-refresh finishes */
159
+ onRefreshEnd?: () => void;
160
+ /** Callback when a 401 auto-refresh fails */
161
+ onAutoRefreshFailed?: (error: ApiError) => void;
156
162
  }
157
163
  /**
158
164
  * A session entry in the multi-account session pool.
@@ -233,6 +239,8 @@ interface RequestOptions {
233
239
  headers?: Record<string, string>;
234
240
  /** Client context to forward end-user info (IP, UA, etc.) in server-to-server calls */
235
241
  clientContext?: ClientContext;
242
+ /** Internal flag to prevent infinite refresh loops */
243
+ isAutoRefresh?: boolean;
236
244
  }
237
245
  /**
238
246
  * End-user context for server-to-server calls.
@@ -343,6 +351,10 @@ declare class ScaleMuleClient {
343
351
  private accountSwitcherEnabled;
344
352
  private accountSwitcherPrivacy;
345
353
  private knownAccounts;
354
+ private refreshPromise;
355
+ private onRefreshStart?;
356
+ private onRefreshEnd?;
357
+ private onAutoRefreshFailed?;
346
358
  constructor(config: ScaleMuleConfig);
347
359
  initialize(): Promise<void>;
348
360
  setSession(token: string, userId: string): Promise<void>;
@@ -403,6 +415,8 @@ declare class ScaleMuleClient {
403
415
  retries?: number;
404
416
  skipRetry?: boolean;
405
417
  signal?: AbortSignal;
418
+ isAutoRefresh?: boolean;
419
+ onAutoRefreshFailed?: (error: ApiError) => void;
406
420
  }): Promise<ApiResponse<T>>;
407
421
  get<T>(path: string, options?: RequestOptions): Promise<ApiResponse<T>>;
408
422
  post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<ApiResponse<T>>;
@@ -4616,7 +4630,7 @@ declare class PhotoService extends ServiceModule {
4616
4630
  }
4617
4631
 
4618
4632
  /**
4619
- * Audio service — typed wrapper over `/v1/audios`.
4633
+ * Audio service — typed wrapper over `/v1/audio`.
4620
4634
  *
4621
4635
  * Phase 5 MVP scope:
4622
4636
  * - `uploadViaStorage()` — presigned-direct-to-S3 upload + register flow,
@@ -4690,6 +4704,78 @@ declare class AudioService extends ServiceModule {
4690
4704
  }, requestOptions?: RequestOptions): Promise<ApiResponse<AudioUploadViaStorageResult>>;
4691
4705
  }
4692
4706
 
4707
+ type TtsAccessMode = 'owner_private' | 'tenant_shared' | 'public';
4708
+ interface TtsAudioInfo {
4709
+ id: string;
4710
+ status: string;
4711
+ access_mode: TtsAccessMode;
4712
+ codec?: string | null;
4713
+ duration_ms?: number | null;
4714
+ bit_rate_kbps?: number | null;
4715
+ waveform_peaks?: unknown;
4716
+ url?: string | null;
4717
+ expires_at?: string | null;
4718
+ }
4719
+ interface TtsSynthesizeReadyResult {
4720
+ status: 'ready';
4721
+ audio_id: string;
4722
+ cached: boolean;
4723
+ provider: string;
4724
+ chunks: number;
4725
+ access_mode: TtsAccessMode;
4726
+ audio: TtsAudioInfo;
4727
+ }
4728
+ interface TtsSynthesizeQueuedResult {
4729
+ status: 'queued';
4730
+ job_id: string;
4731
+ }
4732
+ type TtsSynthesizeResult = TtsSynthesizeReadyResult | TtsSynthesizeQueuedResult;
4733
+ interface TtsJobStatus {
4734
+ id: string;
4735
+ access_mode: TtsAccessMode;
4736
+ provider: string;
4737
+ voice: string;
4738
+ model: string;
4739
+ format: string;
4740
+ status: 'queued' | 'chunking' | 'synthesizing' | 'concatenating' | 'ready' | 'failed';
4741
+ chunk_total: number;
4742
+ chunk_done: number;
4743
+ audio_id?: string | null;
4744
+ audio?: TtsAudioInfo | null;
4745
+ error?: string | null;
4746
+ created_at: string;
4747
+ updated_at: string;
4748
+ }
4749
+ interface TtsVoice {
4750
+ provider: string;
4751
+ id: string;
4752
+ display_name: string;
4753
+ language?: string | null;
4754
+ gender?: string | null;
4755
+ preview_url?: string | null;
4756
+ }
4757
+ interface TtsVoicesResponse {
4758
+ provider: string;
4759
+ voices: TtsVoice[];
4760
+ }
4761
+ interface TtsSynthesizeParams {
4762
+ text: string;
4763
+ voice?: string;
4764
+ model?: string;
4765
+ provider?: string;
4766
+ async?: boolean;
4767
+ accessMode?: TtsAccessMode;
4768
+ }
4769
+ interface TtsListVoicesParams {
4770
+ provider?: string;
4771
+ }
4772
+ declare class TtsService extends ServiceModule {
4773
+ protected basePath: string;
4774
+ synthesize(params: TtsSynthesizeParams, options?: RequestOptions): Promise<ApiResponse<TtsSynthesizeResult>>;
4775
+ getJob(id: string, options?: RequestOptions): Promise<ApiResponse<TtsJobStatus>>;
4776
+ listVoices(params?: TtsListVoicesParams, options?: RequestOptions): Promise<ApiResponse<TtsVoicesResponse>>;
4777
+ }
4778
+
4693
4779
  /**
4694
4780
  * Queue Service Module
4695
4781
  *
@@ -6415,6 +6501,7 @@ declare class ScaleMule {
6415
6501
  readonly functions: FunctionsService;
6416
6502
  readonly photo: PhotoService;
6417
6503
  readonly audio: AudioService;
6504
+ readonly tts: TtsService;
6418
6505
  readonly flagContent: FlagContentService;
6419
6506
  readonly creatorMaker: CreatorMakerService;
6420
6507
  readonly compliance: ComplianceService;
@@ -6489,4 +6576,4 @@ declare class ScaleMule {
6489
6576
  getClient(): ScaleMuleClient;
6490
6577
  }
6491
6578
 
6492
- export { type AccountBalance, type AccountSwitcherPrivacy, 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 AudioRegisterResult, AudioService, type AudioUploadViaStorageResult, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type CacheEntry, CacheService, type CalendarEvent, type CallParticipant, type CallSession, type CatalogEntry, CatalogService, type ChatMessage, type ChatReaction, ChatService, type ClaimResult, type Client, type ClientContext, type Collection, type Comment, CommunicationService, type CompletedPart, ComplianceService, type CompressionConfig, ConferenceService, type ConferenceSettings, type ConnectedAccount, type ConnectedAccountSubscription, type ConnectedSetupIntentResponse, type ConnectedSubscriptionListParams, type ConnectionStatus, type ContentFlag, type ContentPolicy, type Conversation, type CostReportDay, type CreateProjectInput as CreateCreatorProjectInput, type CreateFlagRequest, type CreateRuleRequest, type CreateSegmentRequest, type CreateSessionResponse, type CreateVariantRequest, type GenerationJob as CreatorJob, CreatorMakerService, type GenerationOutput as CreatorOutput, type CreatorProject, type CreatorUsage, type Credential, type CredentialScope, type Customer, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DeviceInfo, type DirectoryUser, type DirectoryUserDetail, type DirectoryUsersListResponse, type Document, type ErrorCode, ErrorCodes, type EventAggregation, EventsService, type FileInfo, type FileStatus, 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 GenerateInput, type GrantInfo, type GraphEdge, type GraphNode, GraphService, IdentityService, type IdentityType, type IncomingRequestLike, type Invoice, type JobExecution, type JobStats, type JoinCallResponse, type KnownAccount, type KnownAccountDisplay, type Leaderboard, type LeaderboardEntry, LeaderboardService, type Like, type ListNotificationsParams, type Listing, ListingsService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, type MediaPolicy, type MessageCallback, type MessagePin, 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 Notification, type NotificationListResponse, NotificationsService, 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 PinnedMessagesResponse, 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 PushApiFetcher, type PushPreferences, type PushSettings, type PushSubscriptionInfo, type PushToken, type PushTokenAssociationResult, type PushTopic, type QueryFilter, type QueryOptions, type QuerySort, type QueueJob, QueueService, type ReadStatus, RealtimeService, type RedeemResult, type ReferralAnalytics, type ReferralCampaign, type ReferralProfile, type ReferralStats, ReferralsService, type Refund, type RegisterAgentRequest, type RegisterAgentResponse, type RegisterPushTokenData, type RequestOptions, type ResolvedReferral, 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 SearchUsersParams, type SecurityLayers, type ServerlessFunction, type ServiceHealth, ServiceModule, type Session, type SessionArtifact, type SessionInfo, type SessionLog, type SessionPoolEntry, type Severity, type ShareLink, type ShortestPathResult, type SignedUrlResponse, type SocialPost, SocialService, type SocialUser, type SsoConfig, type StatusCallback, type StorageAdapter, StorageService, type StorageSettings, type StrategyResult, type StylePreset, 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 UnreadCountResponse, 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, WEB_PUSH_SERVICE_WORKER, WebPushManager, type WebPushManagerOptions, type WebPushSubscriptionData, type Webhook, WebhooksService, type WebrtcStats, 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 };
6579
+ export { type AccountBalance, type AccountSwitcherPrivacy, 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 AudioRegisterResult, AudioService, type AudioUploadViaStorageResult, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type CacheEntry, CacheService, type CalendarEvent, type CallParticipant, type CallSession, type CatalogEntry, CatalogService, type ChatMessage, type ChatReaction, ChatService, type ClaimResult, type Client, type ClientContext, type Collection, type Comment, CommunicationService, type CompletedPart, ComplianceService, type CompressionConfig, ConferenceService, type ConferenceSettings, type ConnectedAccount, type ConnectedAccountSubscription, type ConnectedSetupIntentResponse, type ConnectedSubscriptionListParams, type ConnectionStatus, type ContentFlag, type ContentPolicy, type Conversation, type CostReportDay, type CreateProjectInput as CreateCreatorProjectInput, type CreateFlagRequest, type CreateRuleRequest, type CreateSegmentRequest, type CreateSessionResponse, type CreateVariantRequest, type GenerationJob as CreatorJob, CreatorMakerService, type GenerationOutput as CreatorOutput, type CreatorProject, type CreatorUsage, type Credential, type CredentialScope, type Customer, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DeviceInfo, type DirectoryUser, type DirectoryUserDetail, type DirectoryUsersListResponse, type Document, type ErrorCode, ErrorCodes, type EventAggregation, EventsService, type FileInfo, type FileStatus, 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 GenerateInput, type GrantInfo, type GraphEdge, type GraphNode, GraphService, IdentityService, type IdentityType, type IncomingRequestLike, type Invoice, type JobExecution, type JobStats, type JoinCallResponse, type KnownAccount, type KnownAccountDisplay, type Leaderboard, type LeaderboardEntry, LeaderboardService, type Like, type ListNotificationsParams, type Listing, ListingsService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, type MediaPolicy, type MessageCallback, type MessagePin, 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 Notification, type NotificationListResponse, NotificationsService, 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 PinnedMessagesResponse, 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 PushApiFetcher, type PushPreferences, type PushSettings, type PushSubscriptionInfo, type PushToken, type PushTokenAssociationResult, type PushTopic, type QueryFilter, type QueryOptions, type QuerySort, type QueueJob, QueueService, type ReadStatus, RealtimeService, type RedeemResult, type ReferralAnalytics, type ReferralCampaign, type ReferralProfile, type ReferralStats, ReferralsService, type Refund, type RegisterAgentRequest, type RegisterAgentResponse, type RegisterPushTokenData, type RequestOptions, type ResolvedReferral, 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 SearchUsersParams, type SecurityLayers, type ServerlessFunction, type ServiceHealth, ServiceModule, type Session, type SessionArtifact, type SessionInfo, type SessionLog, type SessionPoolEntry, type Severity, type ShareLink, type ShortestPathResult, type SignedUrlResponse, type SocialPost, SocialService, type SocialUser, type SsoConfig, type StatusCallback, type StorageAdapter, StorageService, type StorageSettings, type StrategyResult, type StylePreset, 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 TtsAccessMode, type TtsAudioInfo, type TtsJobStatus, type TtsListVoicesParams, TtsService, type TtsSynthesizeParams, type TtsSynthesizeQueuedResult, type TtsSynthesizeReadyResult, type TtsSynthesizeResult, type TtsVoice, type TtsVoicesResponse, type UnreadCountResponse, 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, WEB_PUSH_SERVICE_WORKER, WebPushManager, type WebPushManagerOptions, type WebPushSubscriptionData, type Webhook, WebhooksService, type WebrtcStats, 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.d.ts CHANGED
@@ -153,6 +153,12 @@ interface ScaleMuleConfig {
153
153
  * recover stripped fields for existing entries until those accounts log in again.
154
154
  */
155
155
  accountSwitcherPrivacy?: AccountSwitcherPrivacy;
156
+ /** Callback when a 401 auto-refresh starts */
157
+ onRefreshStart?: () => void;
158
+ /** Callback when a 401 auto-refresh finishes */
159
+ onRefreshEnd?: () => void;
160
+ /** Callback when a 401 auto-refresh fails */
161
+ onAutoRefreshFailed?: (error: ApiError) => void;
156
162
  }
157
163
  /**
158
164
  * A session entry in the multi-account session pool.
@@ -233,6 +239,8 @@ interface RequestOptions {
233
239
  headers?: Record<string, string>;
234
240
  /** Client context to forward end-user info (IP, UA, etc.) in server-to-server calls */
235
241
  clientContext?: ClientContext;
242
+ /** Internal flag to prevent infinite refresh loops */
243
+ isAutoRefresh?: boolean;
236
244
  }
237
245
  /**
238
246
  * End-user context for server-to-server calls.
@@ -343,6 +351,10 @@ declare class ScaleMuleClient {
343
351
  private accountSwitcherEnabled;
344
352
  private accountSwitcherPrivacy;
345
353
  private knownAccounts;
354
+ private refreshPromise;
355
+ private onRefreshStart?;
356
+ private onRefreshEnd?;
357
+ private onAutoRefreshFailed?;
346
358
  constructor(config: ScaleMuleConfig);
347
359
  initialize(): Promise<void>;
348
360
  setSession(token: string, userId: string): Promise<void>;
@@ -403,6 +415,8 @@ declare class ScaleMuleClient {
403
415
  retries?: number;
404
416
  skipRetry?: boolean;
405
417
  signal?: AbortSignal;
418
+ isAutoRefresh?: boolean;
419
+ onAutoRefreshFailed?: (error: ApiError) => void;
406
420
  }): Promise<ApiResponse<T>>;
407
421
  get<T>(path: string, options?: RequestOptions): Promise<ApiResponse<T>>;
408
422
  post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<ApiResponse<T>>;
@@ -4616,7 +4630,7 @@ declare class PhotoService extends ServiceModule {
4616
4630
  }
4617
4631
 
4618
4632
  /**
4619
- * Audio service — typed wrapper over `/v1/audios`.
4633
+ * Audio service — typed wrapper over `/v1/audio`.
4620
4634
  *
4621
4635
  * Phase 5 MVP scope:
4622
4636
  * - `uploadViaStorage()` — presigned-direct-to-S3 upload + register flow,
@@ -4690,6 +4704,78 @@ declare class AudioService extends ServiceModule {
4690
4704
  }, requestOptions?: RequestOptions): Promise<ApiResponse<AudioUploadViaStorageResult>>;
4691
4705
  }
4692
4706
 
4707
+ type TtsAccessMode = 'owner_private' | 'tenant_shared' | 'public';
4708
+ interface TtsAudioInfo {
4709
+ id: string;
4710
+ status: string;
4711
+ access_mode: TtsAccessMode;
4712
+ codec?: string | null;
4713
+ duration_ms?: number | null;
4714
+ bit_rate_kbps?: number | null;
4715
+ waveform_peaks?: unknown;
4716
+ url?: string | null;
4717
+ expires_at?: string | null;
4718
+ }
4719
+ interface TtsSynthesizeReadyResult {
4720
+ status: 'ready';
4721
+ audio_id: string;
4722
+ cached: boolean;
4723
+ provider: string;
4724
+ chunks: number;
4725
+ access_mode: TtsAccessMode;
4726
+ audio: TtsAudioInfo;
4727
+ }
4728
+ interface TtsSynthesizeQueuedResult {
4729
+ status: 'queued';
4730
+ job_id: string;
4731
+ }
4732
+ type TtsSynthesizeResult = TtsSynthesizeReadyResult | TtsSynthesizeQueuedResult;
4733
+ interface TtsJobStatus {
4734
+ id: string;
4735
+ access_mode: TtsAccessMode;
4736
+ provider: string;
4737
+ voice: string;
4738
+ model: string;
4739
+ format: string;
4740
+ status: 'queued' | 'chunking' | 'synthesizing' | 'concatenating' | 'ready' | 'failed';
4741
+ chunk_total: number;
4742
+ chunk_done: number;
4743
+ audio_id?: string | null;
4744
+ audio?: TtsAudioInfo | null;
4745
+ error?: string | null;
4746
+ created_at: string;
4747
+ updated_at: string;
4748
+ }
4749
+ interface TtsVoice {
4750
+ provider: string;
4751
+ id: string;
4752
+ display_name: string;
4753
+ language?: string | null;
4754
+ gender?: string | null;
4755
+ preview_url?: string | null;
4756
+ }
4757
+ interface TtsVoicesResponse {
4758
+ provider: string;
4759
+ voices: TtsVoice[];
4760
+ }
4761
+ interface TtsSynthesizeParams {
4762
+ text: string;
4763
+ voice?: string;
4764
+ model?: string;
4765
+ provider?: string;
4766
+ async?: boolean;
4767
+ accessMode?: TtsAccessMode;
4768
+ }
4769
+ interface TtsListVoicesParams {
4770
+ provider?: string;
4771
+ }
4772
+ declare class TtsService extends ServiceModule {
4773
+ protected basePath: string;
4774
+ synthesize(params: TtsSynthesizeParams, options?: RequestOptions): Promise<ApiResponse<TtsSynthesizeResult>>;
4775
+ getJob(id: string, options?: RequestOptions): Promise<ApiResponse<TtsJobStatus>>;
4776
+ listVoices(params?: TtsListVoicesParams, options?: RequestOptions): Promise<ApiResponse<TtsVoicesResponse>>;
4777
+ }
4778
+
4693
4779
  /**
4694
4780
  * Queue Service Module
4695
4781
  *
@@ -6415,6 +6501,7 @@ declare class ScaleMule {
6415
6501
  readonly functions: FunctionsService;
6416
6502
  readonly photo: PhotoService;
6417
6503
  readonly audio: AudioService;
6504
+ readonly tts: TtsService;
6418
6505
  readonly flagContent: FlagContentService;
6419
6506
  readonly creatorMaker: CreatorMakerService;
6420
6507
  readonly compliance: ComplianceService;
@@ -6489,4 +6576,4 @@ declare class ScaleMule {
6489
6576
  getClient(): ScaleMuleClient;
6490
6577
  }
6491
6578
 
6492
- export { type AccountBalance, type AccountSwitcherPrivacy, 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 AudioRegisterResult, AudioService, type AudioUploadViaStorageResult, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type CacheEntry, CacheService, type CalendarEvent, type CallParticipant, type CallSession, type CatalogEntry, CatalogService, type ChatMessage, type ChatReaction, ChatService, type ClaimResult, type Client, type ClientContext, type Collection, type Comment, CommunicationService, type CompletedPart, ComplianceService, type CompressionConfig, ConferenceService, type ConferenceSettings, type ConnectedAccount, type ConnectedAccountSubscription, type ConnectedSetupIntentResponse, type ConnectedSubscriptionListParams, type ConnectionStatus, type ContentFlag, type ContentPolicy, type Conversation, type CostReportDay, type CreateProjectInput as CreateCreatorProjectInput, type CreateFlagRequest, type CreateRuleRequest, type CreateSegmentRequest, type CreateSessionResponse, type CreateVariantRequest, type GenerationJob as CreatorJob, CreatorMakerService, type GenerationOutput as CreatorOutput, type CreatorProject, type CreatorUsage, type Credential, type CredentialScope, type Customer, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DeviceInfo, type DirectoryUser, type DirectoryUserDetail, type DirectoryUsersListResponse, type Document, type ErrorCode, ErrorCodes, type EventAggregation, EventsService, type FileInfo, type FileStatus, 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 GenerateInput, type GrantInfo, type GraphEdge, type GraphNode, GraphService, IdentityService, type IdentityType, type IncomingRequestLike, type Invoice, type JobExecution, type JobStats, type JoinCallResponse, type KnownAccount, type KnownAccountDisplay, type Leaderboard, type LeaderboardEntry, LeaderboardService, type Like, type ListNotificationsParams, type Listing, ListingsService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, type MediaPolicy, type MessageCallback, type MessagePin, 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 Notification, type NotificationListResponse, NotificationsService, 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 PinnedMessagesResponse, 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 PushApiFetcher, type PushPreferences, type PushSettings, type PushSubscriptionInfo, type PushToken, type PushTokenAssociationResult, type PushTopic, type QueryFilter, type QueryOptions, type QuerySort, type QueueJob, QueueService, type ReadStatus, RealtimeService, type RedeemResult, type ReferralAnalytics, type ReferralCampaign, type ReferralProfile, type ReferralStats, ReferralsService, type Refund, type RegisterAgentRequest, type RegisterAgentResponse, type RegisterPushTokenData, type RequestOptions, type ResolvedReferral, 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 SearchUsersParams, type SecurityLayers, type ServerlessFunction, type ServiceHealth, ServiceModule, type Session, type SessionArtifact, type SessionInfo, type SessionLog, type SessionPoolEntry, type Severity, type ShareLink, type ShortestPathResult, type SignedUrlResponse, type SocialPost, SocialService, type SocialUser, type SsoConfig, type StatusCallback, type StorageAdapter, StorageService, type StorageSettings, type StrategyResult, type StylePreset, 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 UnreadCountResponse, 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, WEB_PUSH_SERVICE_WORKER, WebPushManager, type WebPushManagerOptions, type WebPushSubscriptionData, type Webhook, WebhooksService, type WebrtcStats, 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 };
6579
+ export { type AccountBalance, type AccountSwitcherPrivacy, 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 AudioRegisterResult, AudioService, type AudioUploadViaStorageResult, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type CacheEntry, CacheService, type CalendarEvent, type CallParticipant, type CallSession, type CatalogEntry, CatalogService, type ChatMessage, type ChatReaction, ChatService, type ClaimResult, type Client, type ClientContext, type Collection, type Comment, CommunicationService, type CompletedPart, ComplianceService, type CompressionConfig, ConferenceService, type ConferenceSettings, type ConnectedAccount, type ConnectedAccountSubscription, type ConnectedSetupIntentResponse, type ConnectedSubscriptionListParams, type ConnectionStatus, type ContentFlag, type ContentPolicy, type Conversation, type CostReportDay, type CreateProjectInput as CreateCreatorProjectInput, type CreateFlagRequest, type CreateRuleRequest, type CreateSegmentRequest, type CreateSessionResponse, type CreateVariantRequest, type GenerationJob as CreatorJob, CreatorMakerService, type GenerationOutput as CreatorOutput, type CreatorProject, type CreatorUsage, type Credential, type CredentialScope, type Customer, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DeviceInfo, type DirectoryUser, type DirectoryUserDetail, type DirectoryUsersListResponse, type Document, type ErrorCode, ErrorCodes, type EventAggregation, EventsService, type FileInfo, type FileStatus, 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 GenerateInput, type GrantInfo, type GraphEdge, type GraphNode, GraphService, IdentityService, type IdentityType, type IncomingRequestLike, type Invoice, type JobExecution, type JobStats, type JoinCallResponse, type KnownAccount, type KnownAccountDisplay, type Leaderboard, type LeaderboardEntry, LeaderboardService, type Like, type ListNotificationsParams, type Listing, ListingsService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, type MediaPolicy, type MessageCallback, type MessagePin, 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 Notification, type NotificationListResponse, NotificationsService, 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 PinnedMessagesResponse, 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 PushApiFetcher, type PushPreferences, type PushSettings, type PushSubscriptionInfo, type PushToken, type PushTokenAssociationResult, type PushTopic, type QueryFilter, type QueryOptions, type QuerySort, type QueueJob, QueueService, type ReadStatus, RealtimeService, type RedeemResult, type ReferralAnalytics, type ReferralCampaign, type ReferralProfile, type ReferralStats, ReferralsService, type Refund, type RegisterAgentRequest, type RegisterAgentResponse, type RegisterPushTokenData, type RequestOptions, type ResolvedReferral, 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 SearchUsersParams, type SecurityLayers, type ServerlessFunction, type ServiceHealth, ServiceModule, type Session, type SessionArtifact, type SessionInfo, type SessionLog, type SessionPoolEntry, type Severity, type ShareLink, type ShortestPathResult, type SignedUrlResponse, type SocialPost, SocialService, type SocialUser, type SsoConfig, type StatusCallback, type StorageAdapter, StorageService, type StorageSettings, type StrategyResult, type StylePreset, 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 TtsAccessMode, type TtsAudioInfo, type TtsJobStatus, type TtsListVoicesParams, TtsService, type TtsSynthesizeParams, type TtsSynthesizeQueuedResult, type TtsSynthesizeReadyResult, type TtsSynthesizeResult, type TtsVoice, type TtsVoicesResponse, type UnreadCountResponse, 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, WEB_PUSH_SERVICE_WORKER, WebPushManager, type WebPushManagerOptions, type WebPushSubscriptionData, type Webhook, WebhooksService, type WebrtcStats, 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
@@ -339,6 +339,7 @@ __export(index_exports, {
339
339
  SocialService: () => SocialService,
340
340
  StorageService: () => StorageService,
341
341
  TeamsService: () => TeamsService,
342
+ TtsService: () => TtsService,
342
343
  UploadResumeStore: () => UploadResumeStore,
343
344
  UploadTelemetry: () => UploadTelemetry,
344
345
  VideoService: () => VideoService,
@@ -722,6 +723,7 @@ var ScaleMuleClient = class {
722
723
  this.anonymousId = null;
723
724
  this.sessionPool = /* @__PURE__ */ new Map();
724
725
  this.knownAccounts = /* @__PURE__ */ new Map();
726
+ this.refreshPromise = null;
725
727
  this.apiKey = config.apiKey;
726
728
  this.applicationId = config.applicationId || null;
727
729
  this.baseUrl = config.baseUrl || GATEWAY_URLS[config.environment || "prod"];
@@ -740,6 +742,9 @@ var ScaleMuleClient = class {
740
742
  this.multiSessionEnabled = config.enableMultiSession || false;
741
743
  this.accountSwitcherEnabled = config.enableAccountSwitcher || false;
742
744
  this.accountSwitcherPrivacy = config.accountSwitcherPrivacy || "full";
745
+ this.onRefreshStart = config.onRefreshStart;
746
+ this.onRefreshEnd = config.onRefreshEnd;
747
+ this.onAutoRefreshFailed = config.onAutoRefreshFailed;
743
748
  }
744
749
  // --------------------------------------------------------------------------
745
750
  // Session Management
@@ -1025,34 +1030,28 @@ var ScaleMuleClient = class {
1025
1030
  const method = (init.method || "GET").toUpperCase();
1026
1031
  const timeout = init.timeout || this.defaultTimeout;
1027
1032
  const maxRetries = init.skipRetry ? 0 : init.retries ?? this.maxRetries;
1028
- const headers = {
1029
- "x-api-key": this.apiKey,
1030
- "User-Agent": `ScaleMule-SDK-TypeScript/${SDK_VERSION}`,
1031
- ...init.headers
1032
- };
1033
- if (!init.skipAuth && this.sessionToken) {
1034
- headers["Authorization"] = `Bearer ${this.sessionToken}`;
1035
- }
1036
- if (this.workspaceId) {
1037
- headers["x-sm-workspace-id"] = this.workspaceId;
1038
- }
1039
- if (!this.sessionToken && this.anonymousId) {
1040
- headers["x-anonymous-id"] = this.anonymousId;
1041
- }
1042
- let bodyStr;
1043
- if (init.body !== void 0 && init.body !== null) {
1044
- bodyStr = typeof init.body === "string" ? init.body : JSON.stringify(init.body);
1045
- if (!headers["Content-Type"]) {
1046
- headers["Content-Type"] = "application/json";
1047
- }
1048
- }
1049
- if (this.debug) {
1050
- console.log(`[ScaleMule] ${method} ${path}`);
1051
- }
1052
- const idempotencyKey = method === "POST" ? generateIdempotencyKey() : void 0;
1033
+ const bodyStr = init.body ? JSON.stringify(init.body) : void 0;
1053
1034
  let lastError = null;
1035
+ let idempotencyKey = null;
1054
1036
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
1055
- if (attempt > 0 && idempotencyKey) {
1037
+ const headers = {
1038
+ "x-api-key": this.apiKey,
1039
+ "User-Agent": `ScaleMule-SDK-TypeScript/${SDK_VERSION}`,
1040
+ ...init.headers
1041
+ };
1042
+ if (!init.skipAuth && this.sessionToken) {
1043
+ headers["Authorization"] = `Bearer ${this.sessionToken}`;
1044
+ }
1045
+ if (this.workspaceId) {
1046
+ headers["x-sm-workspace-id"] = this.workspaceId;
1047
+ }
1048
+ if (!this.sessionToken && this.anonymousId) {
1049
+ headers["x-anonymous-id"] = this.anonymousId;
1050
+ }
1051
+ if (attempt > 0 && (method === "POST" || method === "PUT" || method === "PATCH")) {
1052
+ if (!idempotencyKey) {
1053
+ idempotencyKey = generateIdempotencyKey();
1054
+ }
1056
1055
  headers["x-idempotency-key"] = idempotencyKey;
1057
1056
  }
1058
1057
  const controller = new AbortController();
@@ -1072,6 +1071,10 @@ var ScaleMuleClient = class {
1072
1071
  signal: controller.signal
1073
1072
  });
1074
1073
  clearTimeout(timeoutId);
1074
+ const rotatedToken = response.headers.get("x-rotated-session-token");
1075
+ if (rotatedToken && this.sessionToken && this.userId) {
1076
+ this.setSession(rotatedToken, this.userId);
1077
+ }
1075
1078
  if (this.rateLimitQueue) {
1076
1079
  this.rateLimitQueue.updateFromHeaders(response.headers);
1077
1080
  }
@@ -1094,6 +1097,45 @@ var ScaleMuleClient = class {
1094
1097
  status: response.status,
1095
1098
  details: responseData?.error?.details || responseData?.details
1096
1099
  };
1100
+ if (response.status === 401 && this.sessionToken && !init.isAutoRefresh) {
1101
+ if (this.debug) console.log("[ScaleMule] 401 received, attempting auto-refresh...");
1102
+ let isPrimaryRefresh = false;
1103
+ if (!this.refreshPromise) {
1104
+ isPrimaryRefresh = true;
1105
+ this.onRefreshStart?.();
1106
+ this.refreshPromise = this.auth?.refreshSession ? this.auth.refreshSession() : this.post("/auth/refresh", {}, { isAutoRefresh: true });
1107
+ }
1108
+ const currentRefreshPromise = this.refreshPromise;
1109
+ try {
1110
+ const refreshResult = await currentRefreshPromise;
1111
+ if (!refreshResult || refreshResult.error) {
1112
+ if (this.debug) console.log("[ScaleMule] Auto-refresh failed:", refreshResult?.error);
1113
+ const apiError = refreshResult?.error || {
1114
+ code: "refresh_failed",
1115
+ message: "Auto-refresh failed",
1116
+ status: 400
1117
+ };
1118
+ init.onAutoRefreshFailed?.(apiError);
1119
+ this.onAutoRefreshFailed?.(apiError);
1120
+ return { data: null, error };
1121
+ }
1122
+ if (this.debug) console.log("[ScaleMule] Auto-refresh succeeded, retrying original request...");
1123
+ const newToken = refreshResult.data?.session_token || refreshResult.data?.access_token;
1124
+ if (newToken) {
1125
+ this.sessionToken = newToken;
1126
+ if (this.userId) {
1127
+ await this.storage.setItem(SESSION_STORAGE_KEY, newToken);
1128
+ }
1129
+ }
1130
+ attempt--;
1131
+ continue;
1132
+ } finally {
1133
+ if (isPrimaryRefresh && this.refreshPromise === currentRefreshPromise) {
1134
+ this.refreshPromise = null;
1135
+ this.onRefreshEnd?.();
1136
+ }
1137
+ }
1138
+ }
1097
1139
  if (response.status === 429) {
1098
1140
  const retryAfter = response.headers.get("Retry-After");
1099
1141
  if (retryAfter) {
@@ -6518,7 +6560,7 @@ var AudioService = class extends ServiceModule {
6518
6560
  constructor(client, storage) {
6519
6561
  super(client);
6520
6562
  this.storage = storage;
6521
- this.basePath = "/v1/audios";
6563
+ this.basePath = "/v1/audio";
6522
6564
  }
6523
6565
  /**
6524
6566
  * Register a storage-uploaded audio asset with the audio service.
@@ -6576,6 +6618,34 @@ var AudioService = class extends ServiceModule {
6576
6618
  }
6577
6619
  };
6578
6620
 
6621
+ // src/services/tts.ts
6622
+ var TtsService = class extends ServiceModule {
6623
+ constructor() {
6624
+ super(...arguments);
6625
+ this.basePath = "/v1/tts";
6626
+ }
6627
+ async synthesize(params, options) {
6628
+ return this.post(
6629
+ "/synthesize",
6630
+ {
6631
+ text: params.text,
6632
+ voice: params.voice,
6633
+ model: params.model,
6634
+ provider: params.provider,
6635
+ async: params.async,
6636
+ access_mode: params.accessMode
6637
+ },
6638
+ options
6639
+ );
6640
+ }
6641
+ async getJob(id, options) {
6642
+ return this._get(`/jobs/${id}`, options);
6643
+ }
6644
+ async listVoices(params, options) {
6645
+ return this._get(this.withQuery("/voices", { provider: params?.provider }), options);
6646
+ }
6647
+ };
6648
+
6579
6649
  // src/services/queue.ts
6580
6650
  var DeadLetterApi = class extends ServiceModule {
6581
6651
  constructor() {
@@ -7427,6 +7497,7 @@ var ScaleMule = class {
7427
7497
  this.functions = new FunctionsService(this._client);
7428
7498
  this.photo = new PhotoService(this._client, this.storage);
7429
7499
  this.audio = new AudioService(this._client, this.storage);
7500
+ this.tts = new TtsService(this._client);
7430
7501
  this.flagContent = new FlagContentService(this._client);
7431
7502
  this.creatorMaker = new CreatorMakerService(this._client);
7432
7503
  this.compliance = new ComplianceService(this._client);
@@ -7608,6 +7679,7 @@ var index_default = ScaleMule;
7608
7679
  SocialService,
7609
7680
  StorageService,
7610
7681
  TeamsService,
7682
+ TtsService,
7611
7683
  UploadResumeStore,
7612
7684
  UploadTelemetry,
7613
7685
  VideoService,
package/dist/index.mjs CHANGED
@@ -352,6 +352,7 @@ var ScaleMuleClient = class {
352
352
  this.anonymousId = null;
353
353
  this.sessionPool = /* @__PURE__ */ new Map();
354
354
  this.knownAccounts = /* @__PURE__ */ new Map();
355
+ this.refreshPromise = null;
355
356
  this.apiKey = config.apiKey;
356
357
  this.applicationId = config.applicationId || null;
357
358
  this.baseUrl = config.baseUrl || GATEWAY_URLS[config.environment || "prod"];
@@ -370,6 +371,9 @@ var ScaleMuleClient = class {
370
371
  this.multiSessionEnabled = config.enableMultiSession || false;
371
372
  this.accountSwitcherEnabled = config.enableAccountSwitcher || false;
372
373
  this.accountSwitcherPrivacy = config.accountSwitcherPrivacy || "full";
374
+ this.onRefreshStart = config.onRefreshStart;
375
+ this.onRefreshEnd = config.onRefreshEnd;
376
+ this.onAutoRefreshFailed = config.onAutoRefreshFailed;
373
377
  }
374
378
  // --------------------------------------------------------------------------
375
379
  // Session Management
@@ -655,34 +659,28 @@ var ScaleMuleClient = class {
655
659
  const method = (init.method || "GET").toUpperCase();
656
660
  const timeout = init.timeout || this.defaultTimeout;
657
661
  const maxRetries = init.skipRetry ? 0 : init.retries ?? this.maxRetries;
658
- const headers = {
659
- "x-api-key": this.apiKey,
660
- "User-Agent": `ScaleMule-SDK-TypeScript/${SDK_VERSION}`,
661
- ...init.headers
662
- };
663
- if (!init.skipAuth && this.sessionToken) {
664
- headers["Authorization"] = `Bearer ${this.sessionToken}`;
665
- }
666
- if (this.workspaceId) {
667
- headers["x-sm-workspace-id"] = this.workspaceId;
668
- }
669
- if (!this.sessionToken && this.anonymousId) {
670
- headers["x-anonymous-id"] = this.anonymousId;
671
- }
672
- let bodyStr;
673
- if (init.body !== void 0 && init.body !== null) {
674
- bodyStr = typeof init.body === "string" ? init.body : JSON.stringify(init.body);
675
- if (!headers["Content-Type"]) {
676
- headers["Content-Type"] = "application/json";
677
- }
678
- }
679
- if (this.debug) {
680
- console.log(`[ScaleMule] ${method} ${path}`);
681
- }
682
- const idempotencyKey = method === "POST" ? generateIdempotencyKey() : void 0;
662
+ const bodyStr = init.body ? JSON.stringify(init.body) : void 0;
683
663
  let lastError = null;
664
+ let idempotencyKey = null;
684
665
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
685
- if (attempt > 0 && idempotencyKey) {
666
+ const headers = {
667
+ "x-api-key": this.apiKey,
668
+ "User-Agent": `ScaleMule-SDK-TypeScript/${SDK_VERSION}`,
669
+ ...init.headers
670
+ };
671
+ if (!init.skipAuth && this.sessionToken) {
672
+ headers["Authorization"] = `Bearer ${this.sessionToken}`;
673
+ }
674
+ if (this.workspaceId) {
675
+ headers["x-sm-workspace-id"] = this.workspaceId;
676
+ }
677
+ if (!this.sessionToken && this.anonymousId) {
678
+ headers["x-anonymous-id"] = this.anonymousId;
679
+ }
680
+ if (attempt > 0 && (method === "POST" || method === "PUT" || method === "PATCH")) {
681
+ if (!idempotencyKey) {
682
+ idempotencyKey = generateIdempotencyKey();
683
+ }
686
684
  headers["x-idempotency-key"] = idempotencyKey;
687
685
  }
688
686
  const controller = new AbortController();
@@ -702,6 +700,10 @@ var ScaleMuleClient = class {
702
700
  signal: controller.signal
703
701
  });
704
702
  clearTimeout(timeoutId);
703
+ const rotatedToken = response.headers.get("x-rotated-session-token");
704
+ if (rotatedToken && this.sessionToken && this.userId) {
705
+ this.setSession(rotatedToken, this.userId);
706
+ }
705
707
  if (this.rateLimitQueue) {
706
708
  this.rateLimitQueue.updateFromHeaders(response.headers);
707
709
  }
@@ -724,6 +726,45 @@ var ScaleMuleClient = class {
724
726
  status: response.status,
725
727
  details: responseData?.error?.details || responseData?.details
726
728
  };
729
+ if (response.status === 401 && this.sessionToken && !init.isAutoRefresh) {
730
+ if (this.debug) console.log("[ScaleMule] 401 received, attempting auto-refresh...");
731
+ let isPrimaryRefresh = false;
732
+ if (!this.refreshPromise) {
733
+ isPrimaryRefresh = true;
734
+ this.onRefreshStart?.();
735
+ this.refreshPromise = this.auth?.refreshSession ? this.auth.refreshSession() : this.post("/auth/refresh", {}, { isAutoRefresh: true });
736
+ }
737
+ const currentRefreshPromise = this.refreshPromise;
738
+ try {
739
+ const refreshResult = await currentRefreshPromise;
740
+ if (!refreshResult || refreshResult.error) {
741
+ if (this.debug) console.log("[ScaleMule] Auto-refresh failed:", refreshResult?.error);
742
+ const apiError = refreshResult?.error || {
743
+ code: "refresh_failed",
744
+ message: "Auto-refresh failed",
745
+ status: 400
746
+ };
747
+ init.onAutoRefreshFailed?.(apiError);
748
+ this.onAutoRefreshFailed?.(apiError);
749
+ return { data: null, error };
750
+ }
751
+ if (this.debug) console.log("[ScaleMule] Auto-refresh succeeded, retrying original request...");
752
+ const newToken = refreshResult.data?.session_token || refreshResult.data?.access_token;
753
+ if (newToken) {
754
+ this.sessionToken = newToken;
755
+ if (this.userId) {
756
+ await this.storage.setItem(SESSION_STORAGE_KEY, newToken);
757
+ }
758
+ }
759
+ attempt--;
760
+ continue;
761
+ } finally {
762
+ if (isPrimaryRefresh && this.refreshPromise === currentRefreshPromise) {
763
+ this.refreshPromise = null;
764
+ this.onRefreshEnd?.();
765
+ }
766
+ }
767
+ }
727
768
  if (response.status === 429) {
728
769
  const retryAfter = response.headers.get("Retry-After");
729
770
  if (retryAfter) {
@@ -6145,7 +6186,7 @@ var AudioService = class extends ServiceModule {
6145
6186
  constructor(client, storage) {
6146
6187
  super(client);
6147
6188
  this.storage = storage;
6148
- this.basePath = "/v1/audios";
6189
+ this.basePath = "/v1/audio";
6149
6190
  }
6150
6191
  /**
6151
6192
  * Register a storage-uploaded audio asset with the audio service.
@@ -6203,6 +6244,34 @@ var AudioService = class extends ServiceModule {
6203
6244
  }
6204
6245
  };
6205
6246
 
6247
+ // src/services/tts.ts
6248
+ var TtsService = class extends ServiceModule {
6249
+ constructor() {
6250
+ super(...arguments);
6251
+ this.basePath = "/v1/tts";
6252
+ }
6253
+ async synthesize(params, options) {
6254
+ return this.post(
6255
+ "/synthesize",
6256
+ {
6257
+ text: params.text,
6258
+ voice: params.voice,
6259
+ model: params.model,
6260
+ provider: params.provider,
6261
+ async: params.async,
6262
+ access_mode: params.accessMode
6263
+ },
6264
+ options
6265
+ );
6266
+ }
6267
+ async getJob(id, options) {
6268
+ return this._get(`/jobs/${id}`, options);
6269
+ }
6270
+ async listVoices(params, options) {
6271
+ return this._get(this.withQuery("/voices", { provider: params?.provider }), options);
6272
+ }
6273
+ };
6274
+
6206
6275
  // src/services/queue.ts
6207
6276
  var DeadLetterApi = class extends ServiceModule {
6208
6277
  constructor() {
@@ -7054,6 +7123,7 @@ var ScaleMule = class {
7054
7123
  this.functions = new FunctionsService(this._client);
7055
7124
  this.photo = new PhotoService(this._client, this.storage);
7056
7125
  this.audio = new AudioService(this._client, this.storage);
7126
+ this.tts = new TtsService(this._client);
7057
7127
  this.flagContent = new FlagContentService(this._client);
7058
7128
  this.creatorMaker = new CreatorMakerService(this._client);
7059
7129
  this.compliance = new ComplianceService(this._client);
@@ -7234,6 +7304,7 @@ export {
7234
7304
  SocialService,
7235
7305
  StorageService,
7236
7306
  TeamsService,
7307
+ TtsService,
7237
7308
  UploadResumeStore,
7238
7309
  UploadTelemetry,
7239
7310
  VideoService,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalemule/sdk",
3
- "version": "0.0.47",
3
+ "version": "0.0.49",
4
4
  "description": "Official TypeScript/JavaScript SDK for ScaleMule Backend-as-a-Service",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",