@scalemule/sdk 0.0.19 → 0.0.21
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 +62 -27
- package/dist/index.d.ts +62 -27
- package/dist/index.js +266 -15
- package/dist/index.mjs +266 -15
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -125,6 +125,20 @@ interface ScaleMuleConfig {
|
|
|
125
125
|
enableRateLimitQueue?: boolean;
|
|
126
126
|
/** Enable offline queue — queues requests when offline, syncs on reconnect */
|
|
127
127
|
enableOfflineQueue?: boolean;
|
|
128
|
+
/** Enable multi-account session pool (Google Account Chooser style). Default: false */
|
|
129
|
+
enableMultiSession?: boolean;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* A session entry in the multi-account session pool.
|
|
133
|
+
*/
|
|
134
|
+
interface SessionPoolEntry {
|
|
135
|
+
token: string;
|
|
136
|
+
userId: string;
|
|
137
|
+
email: string;
|
|
138
|
+
fullName?: string;
|
|
139
|
+
avatarUrl?: string;
|
|
140
|
+
expiresAt?: string;
|
|
141
|
+
addedAt: string;
|
|
128
142
|
}
|
|
129
143
|
/**
|
|
130
144
|
* Per-request options that override client defaults.
|
|
@@ -234,21 +248,6 @@ declare function extractClientContext(request: IncomingRequestLike): ClientConte
|
|
|
234
248
|
*/
|
|
235
249
|
declare function buildClientContextHeaders(context: ClientContext | undefined): Record<string, string>;
|
|
236
250
|
|
|
237
|
-
/**
|
|
238
|
-
* ScaleMule Core HTTP Client
|
|
239
|
-
*
|
|
240
|
-
* Fetch-based client with:
|
|
241
|
-
* - { data, error } response contract
|
|
242
|
-
* - Exponential backoff with jitter on retries
|
|
243
|
-
* - x-idempotency-key on POST retries (prevents duplicate side effects)
|
|
244
|
-
* - Rate limit queue (auto-queues on 429)
|
|
245
|
-
* - Offline queue with persistence
|
|
246
|
-
* - AbortController / AbortSignal support
|
|
247
|
-
* - Works in browser, Node.js 18+, and edge runtimes
|
|
248
|
-
*
|
|
249
|
-
* Promoted from sdks/scalemule-nextjs and adapted for the base SDK.
|
|
250
|
-
*/
|
|
251
|
-
|
|
252
251
|
declare class ScaleMuleClient {
|
|
253
252
|
private apiKey;
|
|
254
253
|
private baseUrl;
|
|
@@ -262,6 +261,9 @@ declare class ScaleMuleClient {
|
|
|
262
261
|
private rateLimitQueue;
|
|
263
262
|
private offlineQueue;
|
|
264
263
|
private workspaceId;
|
|
264
|
+
private anonymousId;
|
|
265
|
+
private multiSessionEnabled;
|
|
266
|
+
private sessionPool;
|
|
265
267
|
constructor(config: ScaleMuleConfig);
|
|
266
268
|
initialize(): Promise<void>;
|
|
267
269
|
setSession(token: string, userId: string): Promise<void>;
|
|
@@ -271,6 +273,22 @@ declare class ScaleMuleClient {
|
|
|
271
273
|
getSessionToken(): string | null;
|
|
272
274
|
getUserId(): string | null;
|
|
273
275
|
isAuthenticated(): boolean;
|
|
276
|
+
getAnonymousId(): string | null;
|
|
277
|
+
isMultiSessionEnabled(): boolean;
|
|
278
|
+
/** Get all accounts in the session pool */
|
|
279
|
+
getSessionPool(): SessionPoolEntry[];
|
|
280
|
+
/** Get the active account entry, or null */
|
|
281
|
+
getActiveAccount(): SessionPoolEntry | null;
|
|
282
|
+
/** Add an account to the session pool and set it as active */
|
|
283
|
+
addAccount(entry: SessionPoolEntry): Promise<void>;
|
|
284
|
+
/** Switch to a different account in the pool. Returns false if not found. */
|
|
285
|
+
switchAccount(userId: string): Promise<boolean>;
|
|
286
|
+
/** Remove a specific account from the pool */
|
|
287
|
+
removeAccount(userId: string): Promise<void>;
|
|
288
|
+
/** Clear all accounts from the pool */
|
|
289
|
+
clearAllAccounts(): Promise<void>;
|
|
290
|
+
/** Persist session pool to storage */
|
|
291
|
+
private persistSessionPool;
|
|
274
292
|
getBaseUrl(): string;
|
|
275
293
|
getApiKey(): string;
|
|
276
294
|
isOnline(): boolean;
|
|
@@ -607,6 +625,7 @@ declare class AuthService extends ServiceModule {
|
|
|
607
625
|
email: string;
|
|
608
626
|
password: string;
|
|
609
627
|
remember_me?: boolean;
|
|
628
|
+
device_fingerprint?: Record<string, unknown>;
|
|
610
629
|
}, options?: RequestOptions): Promise<ApiResponse<AuthSession>>;
|
|
611
630
|
logout(options?: RequestOptions): Promise<ApiResponse<{
|
|
612
631
|
logged_out: boolean;
|
|
@@ -3589,6 +3608,11 @@ declare class PhotoService extends ServiceModule {
|
|
|
3589
3608
|
* Use this when files are uploaded via the storage service (presigned URL)
|
|
3590
3609
|
* instead of the photo service's upload endpoint.
|
|
3591
3610
|
*
|
|
3611
|
+
* If the file scan is still in progress, the server waits briefly (~5s) for it
|
|
3612
|
+
* to complete. In the rare case the scan exceeds that window, the server queues
|
|
3613
|
+
* the registration and returns 202; this method retries automatically until the
|
|
3614
|
+
* photo record is available.
|
|
3615
|
+
*
|
|
3592
3616
|
* Returns the photo record with `id` that can be used with `getTransformUrl()`.
|
|
3593
3617
|
*/
|
|
3594
3618
|
register(registerOptions: {
|
|
@@ -4090,6 +4114,16 @@ declare class IdentityService extends ServiceModule {
|
|
|
4090
4114
|
revokeApiKey(id: string, options?: RequestOptions): Promise<ApiResponse<{
|
|
4091
4115
|
revoked: boolean;
|
|
4092
4116
|
}>>;
|
|
4117
|
+
/**
|
|
4118
|
+
* Explicitly link an anonymous_id to the current authenticated user.
|
|
4119
|
+
* Called automatically on init when both a session and anonymous_id exist
|
|
4120
|
+
* (transitional path for users who registered before identity linking existed).
|
|
4121
|
+
*/
|
|
4122
|
+
identify(anonymousId: string, deviceFingerprintHash?: string, options?: RequestOptions): Promise<ApiResponse<{
|
|
4123
|
+
linked: boolean;
|
|
4124
|
+
anonymous_id: string;
|
|
4125
|
+
message: string;
|
|
4126
|
+
}>>;
|
|
4093
4127
|
}
|
|
4094
4128
|
|
|
4095
4129
|
/**
|
|
@@ -5128,17 +5162,6 @@ declare class AgentSessionsService extends ServiceModule {
|
|
|
5128
5162
|
listArtifacts(sessionId: string, options?: RequestOptions): Promise<ApiResponse<SessionArtifact[]>>;
|
|
5129
5163
|
}
|
|
5130
5164
|
|
|
5131
|
-
/**
|
|
5132
|
-
* ScaleMule SDK for TypeScript/JavaScript
|
|
5133
|
-
*
|
|
5134
|
-
* Official SDK for ScaleMule Backend-as-a-Service (v2)
|
|
5135
|
-
*
|
|
5136
|
-
* All methods return { data, error } — never throws on API errors.
|
|
5137
|
-
* List methods return { data[], metadata, error } with standardized pagination.
|
|
5138
|
-
*
|
|
5139
|
-
* @packageDocumentation
|
|
5140
|
-
*/
|
|
5141
|
-
|
|
5142
5165
|
/**
|
|
5143
5166
|
* Main entry point for the ScaleMule SDK.
|
|
5144
5167
|
*
|
|
@@ -5233,6 +5256,18 @@ declare class ScaleMule {
|
|
|
5233
5256
|
getUserId(): string | null;
|
|
5234
5257
|
/** Whether a session token is set. */
|
|
5235
5258
|
isAuthenticated(): boolean;
|
|
5259
|
+
/** The anonymous visitor ID used for identity linking. */
|
|
5260
|
+
getAnonymousId(): string | null;
|
|
5261
|
+
/** Get all accounts in the session pool (requires enableMultiSession) */
|
|
5262
|
+
getSessionPool(): SessionPoolEntry[];
|
|
5263
|
+
/** Get the active account, or null */
|
|
5264
|
+
getActiveAccount(): SessionPoolEntry | null;
|
|
5265
|
+
/** Switch to a different account in the pool. Returns false if not found. */
|
|
5266
|
+
switchAccount(userId: string): Promise<boolean>;
|
|
5267
|
+
/** Remove a specific account from the pool */
|
|
5268
|
+
removeAccount(userId: string): Promise<void>;
|
|
5269
|
+
/** Clear all accounts from the pool */
|
|
5270
|
+
clearAllAccounts(): Promise<void>;
|
|
5236
5271
|
/** The base URL being used for API requests. */
|
|
5237
5272
|
getBaseUrl(): string;
|
|
5238
5273
|
/** Set the active workspace context. All subsequent requests include this as x-sm-workspace-id. */
|
|
@@ -5243,4 +5278,4 @@ declare class ScaleMule {
|
|
|
5243
5278
|
getClient(): ScaleMuleClient;
|
|
5244
5279
|
}
|
|
5245
5280
|
|
|
5246
|
-
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 };
|
|
5281
|
+
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 SessionPoolEntry, 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.d.ts
CHANGED
|
@@ -125,6 +125,20 @@ interface ScaleMuleConfig {
|
|
|
125
125
|
enableRateLimitQueue?: boolean;
|
|
126
126
|
/** Enable offline queue — queues requests when offline, syncs on reconnect */
|
|
127
127
|
enableOfflineQueue?: boolean;
|
|
128
|
+
/** Enable multi-account session pool (Google Account Chooser style). Default: false */
|
|
129
|
+
enableMultiSession?: boolean;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* A session entry in the multi-account session pool.
|
|
133
|
+
*/
|
|
134
|
+
interface SessionPoolEntry {
|
|
135
|
+
token: string;
|
|
136
|
+
userId: string;
|
|
137
|
+
email: string;
|
|
138
|
+
fullName?: string;
|
|
139
|
+
avatarUrl?: string;
|
|
140
|
+
expiresAt?: string;
|
|
141
|
+
addedAt: string;
|
|
128
142
|
}
|
|
129
143
|
/**
|
|
130
144
|
* Per-request options that override client defaults.
|
|
@@ -234,21 +248,6 @@ declare function extractClientContext(request: IncomingRequestLike): ClientConte
|
|
|
234
248
|
*/
|
|
235
249
|
declare function buildClientContextHeaders(context: ClientContext | undefined): Record<string, string>;
|
|
236
250
|
|
|
237
|
-
/**
|
|
238
|
-
* ScaleMule Core HTTP Client
|
|
239
|
-
*
|
|
240
|
-
* Fetch-based client with:
|
|
241
|
-
* - { data, error } response contract
|
|
242
|
-
* - Exponential backoff with jitter on retries
|
|
243
|
-
* - x-idempotency-key on POST retries (prevents duplicate side effects)
|
|
244
|
-
* - Rate limit queue (auto-queues on 429)
|
|
245
|
-
* - Offline queue with persistence
|
|
246
|
-
* - AbortController / AbortSignal support
|
|
247
|
-
* - Works in browser, Node.js 18+, and edge runtimes
|
|
248
|
-
*
|
|
249
|
-
* Promoted from sdks/scalemule-nextjs and adapted for the base SDK.
|
|
250
|
-
*/
|
|
251
|
-
|
|
252
251
|
declare class ScaleMuleClient {
|
|
253
252
|
private apiKey;
|
|
254
253
|
private baseUrl;
|
|
@@ -262,6 +261,9 @@ declare class ScaleMuleClient {
|
|
|
262
261
|
private rateLimitQueue;
|
|
263
262
|
private offlineQueue;
|
|
264
263
|
private workspaceId;
|
|
264
|
+
private anonymousId;
|
|
265
|
+
private multiSessionEnabled;
|
|
266
|
+
private sessionPool;
|
|
265
267
|
constructor(config: ScaleMuleConfig);
|
|
266
268
|
initialize(): Promise<void>;
|
|
267
269
|
setSession(token: string, userId: string): Promise<void>;
|
|
@@ -271,6 +273,22 @@ declare class ScaleMuleClient {
|
|
|
271
273
|
getSessionToken(): string | null;
|
|
272
274
|
getUserId(): string | null;
|
|
273
275
|
isAuthenticated(): boolean;
|
|
276
|
+
getAnonymousId(): string | null;
|
|
277
|
+
isMultiSessionEnabled(): boolean;
|
|
278
|
+
/** Get all accounts in the session pool */
|
|
279
|
+
getSessionPool(): SessionPoolEntry[];
|
|
280
|
+
/** Get the active account entry, or null */
|
|
281
|
+
getActiveAccount(): SessionPoolEntry | null;
|
|
282
|
+
/** Add an account to the session pool and set it as active */
|
|
283
|
+
addAccount(entry: SessionPoolEntry): Promise<void>;
|
|
284
|
+
/** Switch to a different account in the pool. Returns false if not found. */
|
|
285
|
+
switchAccount(userId: string): Promise<boolean>;
|
|
286
|
+
/** Remove a specific account from the pool */
|
|
287
|
+
removeAccount(userId: string): Promise<void>;
|
|
288
|
+
/** Clear all accounts from the pool */
|
|
289
|
+
clearAllAccounts(): Promise<void>;
|
|
290
|
+
/** Persist session pool to storage */
|
|
291
|
+
private persistSessionPool;
|
|
274
292
|
getBaseUrl(): string;
|
|
275
293
|
getApiKey(): string;
|
|
276
294
|
isOnline(): boolean;
|
|
@@ -607,6 +625,7 @@ declare class AuthService extends ServiceModule {
|
|
|
607
625
|
email: string;
|
|
608
626
|
password: string;
|
|
609
627
|
remember_me?: boolean;
|
|
628
|
+
device_fingerprint?: Record<string, unknown>;
|
|
610
629
|
}, options?: RequestOptions): Promise<ApiResponse<AuthSession>>;
|
|
611
630
|
logout(options?: RequestOptions): Promise<ApiResponse<{
|
|
612
631
|
logged_out: boolean;
|
|
@@ -3589,6 +3608,11 @@ declare class PhotoService extends ServiceModule {
|
|
|
3589
3608
|
* Use this when files are uploaded via the storage service (presigned URL)
|
|
3590
3609
|
* instead of the photo service's upload endpoint.
|
|
3591
3610
|
*
|
|
3611
|
+
* If the file scan is still in progress, the server waits briefly (~5s) for it
|
|
3612
|
+
* to complete. In the rare case the scan exceeds that window, the server queues
|
|
3613
|
+
* the registration and returns 202; this method retries automatically until the
|
|
3614
|
+
* photo record is available.
|
|
3615
|
+
*
|
|
3592
3616
|
* Returns the photo record with `id` that can be used with `getTransformUrl()`.
|
|
3593
3617
|
*/
|
|
3594
3618
|
register(registerOptions: {
|
|
@@ -4090,6 +4114,16 @@ declare class IdentityService extends ServiceModule {
|
|
|
4090
4114
|
revokeApiKey(id: string, options?: RequestOptions): Promise<ApiResponse<{
|
|
4091
4115
|
revoked: boolean;
|
|
4092
4116
|
}>>;
|
|
4117
|
+
/**
|
|
4118
|
+
* Explicitly link an anonymous_id to the current authenticated user.
|
|
4119
|
+
* Called automatically on init when both a session and anonymous_id exist
|
|
4120
|
+
* (transitional path for users who registered before identity linking existed).
|
|
4121
|
+
*/
|
|
4122
|
+
identify(anonymousId: string, deviceFingerprintHash?: string, options?: RequestOptions): Promise<ApiResponse<{
|
|
4123
|
+
linked: boolean;
|
|
4124
|
+
anonymous_id: string;
|
|
4125
|
+
message: string;
|
|
4126
|
+
}>>;
|
|
4093
4127
|
}
|
|
4094
4128
|
|
|
4095
4129
|
/**
|
|
@@ -5128,17 +5162,6 @@ declare class AgentSessionsService extends ServiceModule {
|
|
|
5128
5162
|
listArtifacts(sessionId: string, options?: RequestOptions): Promise<ApiResponse<SessionArtifact[]>>;
|
|
5129
5163
|
}
|
|
5130
5164
|
|
|
5131
|
-
/**
|
|
5132
|
-
* ScaleMule SDK for TypeScript/JavaScript
|
|
5133
|
-
*
|
|
5134
|
-
* Official SDK for ScaleMule Backend-as-a-Service (v2)
|
|
5135
|
-
*
|
|
5136
|
-
* All methods return { data, error } — never throws on API errors.
|
|
5137
|
-
* List methods return { data[], metadata, error } with standardized pagination.
|
|
5138
|
-
*
|
|
5139
|
-
* @packageDocumentation
|
|
5140
|
-
*/
|
|
5141
|
-
|
|
5142
5165
|
/**
|
|
5143
5166
|
* Main entry point for the ScaleMule SDK.
|
|
5144
5167
|
*
|
|
@@ -5233,6 +5256,18 @@ declare class ScaleMule {
|
|
|
5233
5256
|
getUserId(): string | null;
|
|
5234
5257
|
/** Whether a session token is set. */
|
|
5235
5258
|
isAuthenticated(): boolean;
|
|
5259
|
+
/** The anonymous visitor ID used for identity linking. */
|
|
5260
|
+
getAnonymousId(): string | null;
|
|
5261
|
+
/** Get all accounts in the session pool (requires enableMultiSession) */
|
|
5262
|
+
getSessionPool(): SessionPoolEntry[];
|
|
5263
|
+
/** Get the active account, or null */
|
|
5264
|
+
getActiveAccount(): SessionPoolEntry | null;
|
|
5265
|
+
/** Switch to a different account in the pool. Returns false if not found. */
|
|
5266
|
+
switchAccount(userId: string): Promise<boolean>;
|
|
5267
|
+
/** Remove a specific account from the pool */
|
|
5268
|
+
removeAccount(userId: string): Promise<void>;
|
|
5269
|
+
/** Clear all accounts from the pool */
|
|
5270
|
+
clearAllAccounts(): Promise<void>;
|
|
5236
5271
|
/** The base URL being used for API requests. */
|
|
5237
5272
|
getBaseUrl(): string;
|
|
5238
5273
|
/** Set the active workspace context. All subsequent requests include this as x-sm-workspace-id. */
|
|
@@ -5243,4 +5278,4 @@ declare class ScaleMule {
|
|
|
5243
5278
|
getClient(): ScaleMuleClient;
|
|
5244
5279
|
}
|
|
5245
5280
|
|
|
5246
|
-
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 };
|
|
5281
|
+
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 SessionPoolEntry, 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
|
@@ -467,6 +467,9 @@ var SESSION_STORAGE_KEY = "scalemule_session";
|
|
|
467
467
|
var USER_ID_STORAGE_KEY = "scalemule_user_id";
|
|
468
468
|
var OFFLINE_QUEUE_KEY = "scalemule_offline_queue";
|
|
469
469
|
var WORKSPACE_STORAGE_KEY = "scalemule_workspace_id";
|
|
470
|
+
var ANONYMOUS_ID_STORAGE_KEY = "scalemule_anonymous_id";
|
|
471
|
+
var SESSION_POOL_KEY = "scalemule_session_pool";
|
|
472
|
+
var ACTIVE_ACCOUNT_KEY = "scalemule_active_account";
|
|
470
473
|
var GATEWAY_URLS = {
|
|
471
474
|
dev: "https://api-dev.scalemule.com",
|
|
472
475
|
prod: "https://api.scalemule.com"
|
|
@@ -659,6 +662,8 @@ var ScaleMuleClient = class {
|
|
|
659
662
|
this.rateLimitQueue = null;
|
|
660
663
|
this.offlineQueue = null;
|
|
661
664
|
this.workspaceId = null;
|
|
665
|
+
this.anonymousId = null;
|
|
666
|
+
this.sessionPool = /* @__PURE__ */ new Map();
|
|
662
667
|
this.apiKey = config.apiKey;
|
|
663
668
|
this.baseUrl = config.baseUrl || GATEWAY_URLS[config.environment || "prod"];
|
|
664
669
|
this.debug = config.debug || false;
|
|
@@ -673,6 +678,7 @@ var ScaleMuleClient = class {
|
|
|
673
678
|
this.offlineQueue = new OfflineQueue(this.storage);
|
|
674
679
|
this.offlineQueue.setOnlineCallback(() => this.syncOfflineQueue());
|
|
675
680
|
}
|
|
681
|
+
this.multiSessionEnabled = config.enableMultiSession || false;
|
|
676
682
|
}
|
|
677
683
|
// --------------------------------------------------------------------------
|
|
678
684
|
// Session Management
|
|
@@ -684,7 +690,46 @@ var ScaleMuleClient = class {
|
|
|
684
690
|
if (userId) this.userId = userId;
|
|
685
691
|
const wsId = await this.storage.getItem(WORKSPACE_STORAGE_KEY);
|
|
686
692
|
if (wsId) this.workspaceId = wsId;
|
|
687
|
-
|
|
693
|
+
let anonId = await this.storage.getItem(ANONYMOUS_ID_STORAGE_KEY);
|
|
694
|
+
if (!anonId) {
|
|
695
|
+
anonId = crypto.randomUUID();
|
|
696
|
+
await this.storage.setItem(ANONYMOUS_ID_STORAGE_KEY, anonId);
|
|
697
|
+
}
|
|
698
|
+
this.anonymousId = anonId;
|
|
699
|
+
if (this.multiSessionEnabled) {
|
|
700
|
+
const poolJson = await this.storage.getItem(SESSION_POOL_KEY);
|
|
701
|
+
if (poolJson) {
|
|
702
|
+
try {
|
|
703
|
+
const entries = JSON.parse(poolJson);
|
|
704
|
+
this.sessionPool = new Map(Object.entries(entries));
|
|
705
|
+
} catch {
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
if (token && userId && !this.sessionPool.has(userId)) {
|
|
709
|
+
this.sessionPool.set(userId, {
|
|
710
|
+
token,
|
|
711
|
+
userId,
|
|
712
|
+
email: "",
|
|
713
|
+
addedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
714
|
+
});
|
|
715
|
+
await this.persistSessionPool();
|
|
716
|
+
}
|
|
717
|
+
const activeId = await this.storage.getItem(ACTIVE_ACCOUNT_KEY);
|
|
718
|
+
if (activeId && this.sessionPool.has(activeId)) {
|
|
719
|
+
const entry = this.sessionPool.get(activeId);
|
|
720
|
+
this.sessionToken = entry.token;
|
|
721
|
+
this.userId = activeId;
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
if (this.debug)
|
|
725
|
+
console.log(
|
|
726
|
+
"[ScaleMule] Initialized, session:",
|
|
727
|
+
!!this.sessionToken,
|
|
728
|
+
"anonymousId:",
|
|
729
|
+
anonId,
|
|
730
|
+
"poolSize:",
|
|
731
|
+
this.sessionPool.size
|
|
732
|
+
);
|
|
688
733
|
}
|
|
689
734
|
async setSession(token, userId) {
|
|
690
735
|
this.sessionToken = token;
|
|
@@ -693,12 +738,27 @@ var ScaleMuleClient = class {
|
|
|
693
738
|
await this.storage.setItem(USER_ID_STORAGE_KEY, userId);
|
|
694
739
|
}
|
|
695
740
|
async clearSession() {
|
|
741
|
+
if (this.multiSessionEnabled && this.userId) {
|
|
742
|
+
this.sessionPool.delete(this.userId);
|
|
743
|
+
await this.persistSessionPool();
|
|
744
|
+
const next = this.sessionPool.entries().next().value;
|
|
745
|
+
if (next) {
|
|
746
|
+
const [nextUserId, nextEntry] = next;
|
|
747
|
+
this.sessionToken = nextEntry.token;
|
|
748
|
+
this.userId = nextUserId;
|
|
749
|
+
await this.storage.setItem(SESSION_STORAGE_KEY, nextEntry.token);
|
|
750
|
+
await this.storage.setItem(USER_ID_STORAGE_KEY, nextUserId);
|
|
751
|
+
await this.storage.setItem(ACTIVE_ACCOUNT_KEY, nextUserId);
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
696
755
|
this.sessionToken = null;
|
|
697
756
|
this.userId = null;
|
|
698
757
|
this.workspaceId = null;
|
|
699
758
|
await this.storage.removeItem(SESSION_STORAGE_KEY);
|
|
700
759
|
await this.storage.removeItem(USER_ID_STORAGE_KEY);
|
|
701
760
|
await this.storage.removeItem(WORKSPACE_STORAGE_KEY);
|
|
761
|
+
await this.storage.removeItem(ACTIVE_ACCOUNT_KEY);
|
|
702
762
|
}
|
|
703
763
|
setAccessToken(token) {
|
|
704
764
|
this.sessionToken = token;
|
|
@@ -715,6 +775,80 @@ var ScaleMuleClient = class {
|
|
|
715
775
|
isAuthenticated() {
|
|
716
776
|
return this.sessionToken !== null;
|
|
717
777
|
}
|
|
778
|
+
getAnonymousId() {
|
|
779
|
+
return this.anonymousId;
|
|
780
|
+
}
|
|
781
|
+
isMultiSessionEnabled() {
|
|
782
|
+
return this.multiSessionEnabled;
|
|
783
|
+
}
|
|
784
|
+
// --------------------------------------------------------------------------
|
|
785
|
+
// Multi-Account Session Pool (Phase 2)
|
|
786
|
+
// --------------------------------------------------------------------------
|
|
787
|
+
/** Get all accounts in the session pool */
|
|
788
|
+
getSessionPool() {
|
|
789
|
+
return Array.from(this.sessionPool.values());
|
|
790
|
+
}
|
|
791
|
+
/** Get the active account entry, or null */
|
|
792
|
+
getActiveAccount() {
|
|
793
|
+
if (!this.userId) return null;
|
|
794
|
+
return this.sessionPool.get(this.userId) || null;
|
|
795
|
+
}
|
|
796
|
+
/** Add an account to the session pool and set it as active */
|
|
797
|
+
async addAccount(entry) {
|
|
798
|
+
this.sessionPool.set(entry.userId, entry);
|
|
799
|
+
this.sessionToken = entry.token;
|
|
800
|
+
this.userId = entry.userId;
|
|
801
|
+
await this.storage.setItem(SESSION_STORAGE_KEY, entry.token);
|
|
802
|
+
await this.storage.setItem(USER_ID_STORAGE_KEY, entry.userId);
|
|
803
|
+
await this.storage.setItem(ACTIVE_ACCOUNT_KEY, entry.userId);
|
|
804
|
+
await this.persistSessionPool();
|
|
805
|
+
}
|
|
806
|
+
/** Switch to a different account in the pool. Returns false if not found. */
|
|
807
|
+
async switchAccount(userId) {
|
|
808
|
+
const entry = this.sessionPool.get(userId);
|
|
809
|
+
if (!entry) return false;
|
|
810
|
+
this.sessionToken = entry.token;
|
|
811
|
+
this.userId = userId;
|
|
812
|
+
this.workspaceId = null;
|
|
813
|
+
await this.storage.setItem(SESSION_STORAGE_KEY, entry.token);
|
|
814
|
+
await this.storage.setItem(USER_ID_STORAGE_KEY, userId);
|
|
815
|
+
await this.storage.setItem(ACTIVE_ACCOUNT_KEY, userId);
|
|
816
|
+
await this.storage.removeItem(WORKSPACE_STORAGE_KEY);
|
|
817
|
+
return true;
|
|
818
|
+
}
|
|
819
|
+
/** Remove a specific account from the pool */
|
|
820
|
+
async removeAccount(userId) {
|
|
821
|
+
this.sessionPool.delete(userId);
|
|
822
|
+
await this.persistSessionPool();
|
|
823
|
+
if (this.userId === userId) {
|
|
824
|
+
const next = this.sessionPool.entries().next().value;
|
|
825
|
+
if (next) {
|
|
826
|
+
await this.switchAccount(next[0]);
|
|
827
|
+
} else {
|
|
828
|
+
await this.clearSession();
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
/** Clear all accounts from the pool */
|
|
833
|
+
async clearAllAccounts() {
|
|
834
|
+
this.sessionPool.clear();
|
|
835
|
+
await this.storage.removeItem(SESSION_POOL_KEY);
|
|
836
|
+
await this.storage.removeItem(ACTIVE_ACCOUNT_KEY);
|
|
837
|
+
this.sessionToken = null;
|
|
838
|
+
this.userId = null;
|
|
839
|
+
this.workspaceId = null;
|
|
840
|
+
await this.storage.removeItem(SESSION_STORAGE_KEY);
|
|
841
|
+
await this.storage.removeItem(USER_ID_STORAGE_KEY);
|
|
842
|
+
await this.storage.removeItem(WORKSPACE_STORAGE_KEY);
|
|
843
|
+
}
|
|
844
|
+
/** Persist session pool to storage */
|
|
845
|
+
async persistSessionPool() {
|
|
846
|
+
const obj = {};
|
|
847
|
+
for (const [k, v] of this.sessionPool) {
|
|
848
|
+
obj[k] = v;
|
|
849
|
+
}
|
|
850
|
+
await this.storage.setItem(SESSION_POOL_KEY, JSON.stringify(obj));
|
|
851
|
+
}
|
|
718
852
|
getBaseUrl() {
|
|
719
853
|
return this.baseUrl;
|
|
720
854
|
}
|
|
@@ -764,6 +898,9 @@ var ScaleMuleClient = class {
|
|
|
764
898
|
if (this.workspaceId) {
|
|
765
899
|
headers["x-sm-workspace-id"] = this.workspaceId;
|
|
766
900
|
}
|
|
901
|
+
if (!this.sessionToken && this.anonymousId) {
|
|
902
|
+
headers["x-anonymous-id"] = this.anonymousId;
|
|
903
|
+
}
|
|
767
904
|
let bodyStr;
|
|
768
905
|
if (init.body !== void 0 && init.body !== null) {
|
|
769
906
|
bodyStr = typeof init.body === "string" ? init.body : JSON.stringify(init.body);
|
|
@@ -1210,6 +1347,21 @@ function asString(parent, key) {
|
|
|
1210
1347
|
var import_phone = require("@scalemule/ui/phone");
|
|
1211
1348
|
|
|
1212
1349
|
// src/services/auth.ts
|
|
1350
|
+
function collectDeviceFingerprint() {
|
|
1351
|
+
if (typeof window === "undefined" || typeof navigator === "undefined") return void 0;
|
|
1352
|
+
try {
|
|
1353
|
+
return {
|
|
1354
|
+
screen: `${screen.width}x${screen.height}x${screen.colorDepth}`,
|
|
1355
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
1356
|
+
language: navigator.language,
|
|
1357
|
+
platform: navigator.platform,
|
|
1358
|
+
cookie_enabled: navigator.cookieEnabled,
|
|
1359
|
+
do_not_track: navigator.doNotTrack
|
|
1360
|
+
};
|
|
1361
|
+
} catch {
|
|
1362
|
+
return void 0;
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1213
1365
|
var AuthMfaApi = class extends ServiceModule {
|
|
1214
1366
|
constructor() {
|
|
1215
1367
|
super(...arguments);
|
|
@@ -1308,12 +1460,42 @@ var AuthService = class extends ServiceModule {
|
|
|
1308
1460
|
async register(data, options) {
|
|
1309
1461
|
const payload = {
|
|
1310
1462
|
...data,
|
|
1311
|
-
phone: this.sanitizePhoneField(data.phone)
|
|
1463
|
+
phone: this.sanitizePhoneField(data.phone),
|
|
1464
|
+
anonymous_id: this.client.getAnonymousId()
|
|
1312
1465
|
};
|
|
1313
|
-
|
|
1466
|
+
const result = await this.post("/register", payload, options);
|
|
1467
|
+
if (result.data && this.client.isMultiSessionEnabled()) {
|
|
1468
|
+
await this.client.addAccount({
|
|
1469
|
+
token: result.data.session_token,
|
|
1470
|
+
userId: result.data.user.id,
|
|
1471
|
+
email: result.data.user.email,
|
|
1472
|
+
fullName: result.data.user.full_name,
|
|
1473
|
+
avatarUrl: result.data.user.avatar_url,
|
|
1474
|
+
expiresAt: result.data.expires_at,
|
|
1475
|
+
addedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1476
|
+
});
|
|
1477
|
+
}
|
|
1478
|
+
return result;
|
|
1314
1479
|
}
|
|
1315
1480
|
async login(data, options) {
|
|
1316
|
-
|
|
1481
|
+
const payload = {
|
|
1482
|
+
...data,
|
|
1483
|
+
anonymous_id: this.client.getAnonymousId(),
|
|
1484
|
+
device_fingerprint: data.device_fingerprint || collectDeviceFingerprint()
|
|
1485
|
+
};
|
|
1486
|
+
const result = await this.post("/login", payload, options);
|
|
1487
|
+
if (result.data && this.client.isMultiSessionEnabled()) {
|
|
1488
|
+
await this.client.addAccount({
|
|
1489
|
+
token: result.data.session_token,
|
|
1490
|
+
userId: result.data.user.id,
|
|
1491
|
+
email: result.data.user.email,
|
|
1492
|
+
fullName: result.data.user.full_name,
|
|
1493
|
+
avatarUrl: result.data.user.avatar_url,
|
|
1494
|
+
expiresAt: result.data.expires_at,
|
|
1495
|
+
addedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1496
|
+
});
|
|
1497
|
+
}
|
|
1498
|
+
return result;
|
|
1317
1499
|
}
|
|
1318
1500
|
async logout(options) {
|
|
1319
1501
|
return this.post("/logout", void 0, options);
|
|
@@ -2844,7 +3026,7 @@ init_upload_resume();
|
|
|
2844
3026
|
|
|
2845
3027
|
// src/services/upload-strategy.ts
|
|
2846
3028
|
var MULTIPART_THRESHOLD2 = 8 * 1024 * 1024;
|
|
2847
|
-
var MULTIPART_THRESHOLD_SLOW2 =
|
|
3029
|
+
var MULTIPART_THRESHOLD_SLOW2 = 1 * 1024 * 1024;
|
|
2848
3030
|
var DEFAULT_STALL_TIMEOUT_MS2 = 45e3;
|
|
2849
3031
|
var SLOW_STALL_TIMEOUT_MS = 9e4;
|
|
2850
3032
|
var CHUNK_SIZES = {
|
|
@@ -4074,7 +4256,11 @@ var AnalyticsService = class extends ServiceModule {
|
|
|
4074
4256
|
// Event Tracking (v2 — JetStream buffered)
|
|
4075
4257
|
// --------------------------------------------------------------------------
|
|
4076
4258
|
async track(event, properties, userId, options) {
|
|
4077
|
-
|
|
4259
|
+
const payload = { event_name: event, properties, user_id: userId };
|
|
4260
|
+
if (!userId && !this.client.isAuthenticated()) {
|
|
4261
|
+
payload.anonymous_id = this.client.getAnonymousId();
|
|
4262
|
+
}
|
|
4263
|
+
return this.post("/v2/events", payload, options);
|
|
4078
4264
|
}
|
|
4079
4265
|
async trackBatch(events, options) {
|
|
4080
4266
|
const mapped = events.map(({ event, ...rest }) => ({ event_name: event, ...rest }));
|
|
@@ -4938,17 +5124,38 @@ var PhotoService = class extends ServiceModule {
|
|
|
4938
5124
|
* Use this when files are uploaded via the storage service (presigned URL)
|
|
4939
5125
|
* instead of the photo service's upload endpoint.
|
|
4940
5126
|
*
|
|
5127
|
+
* If the file scan is still in progress, the server waits briefly (~5s) for it
|
|
5128
|
+
* to complete. In the rare case the scan exceeds that window, the server queues
|
|
5129
|
+
* the registration and returns 202; this method retries automatically until the
|
|
5130
|
+
* photo record is available.
|
|
5131
|
+
*
|
|
4941
5132
|
* Returns the photo record with `id` that can be used with `getTransformUrl()`.
|
|
4942
5133
|
*/
|
|
4943
5134
|
async register(registerOptions, requestOptions) {
|
|
4944
|
-
|
|
4945
|
-
|
|
4946
|
-
|
|
4947
|
-
|
|
4948
|
-
|
|
4949
|
-
|
|
4950
|
-
|
|
4951
|
-
|
|
5135
|
+
const body = {
|
|
5136
|
+
file_id: registerOptions.fileId,
|
|
5137
|
+
sm_user_id: registerOptions.userId
|
|
5138
|
+
};
|
|
5139
|
+
const result = await this.post("/register", body, requestOptions);
|
|
5140
|
+
const isPending = (r) => !r.error && r.data && "status" in r.data && r.data.status === "pending_scan";
|
|
5141
|
+
if (!isPending(result)) {
|
|
5142
|
+
return result;
|
|
5143
|
+
}
|
|
5144
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
5145
|
+
await new Promise((r) => setTimeout(r, 1e3));
|
|
5146
|
+
const retry = await this.post("/register", body, requestOptions);
|
|
5147
|
+
if (!isPending(retry)) {
|
|
5148
|
+
return retry;
|
|
5149
|
+
}
|
|
5150
|
+
}
|
|
5151
|
+
return {
|
|
5152
|
+
data: null,
|
|
5153
|
+
error: {
|
|
5154
|
+
code: "scan_timeout",
|
|
5155
|
+
message: "File scan did not complete in time. The photo will be registered automatically when the scan finishes.",
|
|
5156
|
+
status: 202
|
|
5157
|
+
}
|
|
5158
|
+
};
|
|
4952
5159
|
}
|
|
4953
5160
|
/** @deprecated Use upload() instead */
|
|
4954
5161
|
async uploadPhoto(file, options) {
|
|
@@ -5177,6 +5384,18 @@ var IdentityService = class extends ServiceModule {
|
|
|
5177
5384
|
async revokeApiKey(id, options) {
|
|
5178
5385
|
return this.del(`/api-keys/${id}`, options);
|
|
5179
5386
|
}
|
|
5387
|
+
/**
|
|
5388
|
+
* Explicitly link an anonymous_id to the current authenticated user.
|
|
5389
|
+
* Called automatically on init when both a session and anonymous_id exist
|
|
5390
|
+
* (transitional path for users who registered before identity linking existed).
|
|
5391
|
+
*/
|
|
5392
|
+
async identify(anonymousId, deviceFingerprintHash, options) {
|
|
5393
|
+
return this.post(
|
|
5394
|
+
"/identify",
|
|
5395
|
+
{ anonymous_id: anonymousId, device_fingerprint_hash: deviceFingerprintHash },
|
|
5396
|
+
options
|
|
5397
|
+
);
|
|
5398
|
+
}
|
|
5180
5399
|
};
|
|
5181
5400
|
|
|
5182
5401
|
// src/services/catalog.ts
|
|
@@ -5733,7 +5952,12 @@ var ScaleMule = class {
|
|
|
5733
5952
|
* Call this once after construction, before making authenticated requests.
|
|
5734
5953
|
*/
|
|
5735
5954
|
async initialize() {
|
|
5736
|
-
|
|
5955
|
+
await this._client.initialize();
|
|
5956
|
+
const anonymousId = this._client.getAnonymousId();
|
|
5957
|
+
if (this._client.isAuthenticated() && anonymousId) {
|
|
5958
|
+
this.identity.identify(anonymousId).catch(() => {
|
|
5959
|
+
});
|
|
5960
|
+
}
|
|
5737
5961
|
}
|
|
5738
5962
|
/**
|
|
5739
5963
|
* Set authentication session (token + userId).
|
|
@@ -5766,6 +5990,33 @@ var ScaleMule = class {
|
|
|
5766
5990
|
isAuthenticated() {
|
|
5767
5991
|
return this._client.isAuthenticated();
|
|
5768
5992
|
}
|
|
5993
|
+
/** The anonymous visitor ID used for identity linking. */
|
|
5994
|
+
getAnonymousId() {
|
|
5995
|
+
return this._client.getAnonymousId();
|
|
5996
|
+
}
|
|
5997
|
+
// --------------------------------------------------------------------------
|
|
5998
|
+
// Multi-Account Session Pool (Phase 2)
|
|
5999
|
+
// --------------------------------------------------------------------------
|
|
6000
|
+
/** Get all accounts in the session pool (requires enableMultiSession) */
|
|
6001
|
+
getSessionPool() {
|
|
6002
|
+
return this._client.getSessionPool();
|
|
6003
|
+
}
|
|
6004
|
+
/** Get the active account, or null */
|
|
6005
|
+
getActiveAccount() {
|
|
6006
|
+
return this._client.getActiveAccount();
|
|
6007
|
+
}
|
|
6008
|
+
/** Switch to a different account in the pool. Returns false if not found. */
|
|
6009
|
+
async switchAccount(userId) {
|
|
6010
|
+
return this._client.switchAccount(userId);
|
|
6011
|
+
}
|
|
6012
|
+
/** Remove a specific account from the pool */
|
|
6013
|
+
async removeAccount(userId) {
|
|
6014
|
+
return this._client.removeAccount(userId);
|
|
6015
|
+
}
|
|
6016
|
+
/** Clear all accounts from the pool */
|
|
6017
|
+
async clearAllAccounts() {
|
|
6018
|
+
return this._client.clearAllAccounts();
|
|
6019
|
+
}
|
|
5769
6020
|
/** The base URL being used for API requests. */
|
|
5770
6021
|
getBaseUrl() {
|
|
5771
6022
|
return this._client.getBaseUrl();
|
package/dist/index.mjs
CHANGED
|
@@ -104,6 +104,9 @@ var SESSION_STORAGE_KEY = "scalemule_session";
|
|
|
104
104
|
var USER_ID_STORAGE_KEY = "scalemule_user_id";
|
|
105
105
|
var OFFLINE_QUEUE_KEY = "scalemule_offline_queue";
|
|
106
106
|
var WORKSPACE_STORAGE_KEY = "scalemule_workspace_id";
|
|
107
|
+
var ANONYMOUS_ID_STORAGE_KEY = "scalemule_anonymous_id";
|
|
108
|
+
var SESSION_POOL_KEY = "scalemule_session_pool";
|
|
109
|
+
var ACTIVE_ACCOUNT_KEY = "scalemule_active_account";
|
|
107
110
|
var GATEWAY_URLS = {
|
|
108
111
|
dev: "https://api-dev.scalemule.com",
|
|
109
112
|
prod: "https://api.scalemule.com"
|
|
@@ -296,6 +299,8 @@ var ScaleMuleClient = class {
|
|
|
296
299
|
this.rateLimitQueue = null;
|
|
297
300
|
this.offlineQueue = null;
|
|
298
301
|
this.workspaceId = null;
|
|
302
|
+
this.anonymousId = null;
|
|
303
|
+
this.sessionPool = /* @__PURE__ */ new Map();
|
|
299
304
|
this.apiKey = config.apiKey;
|
|
300
305
|
this.baseUrl = config.baseUrl || GATEWAY_URLS[config.environment || "prod"];
|
|
301
306
|
this.debug = config.debug || false;
|
|
@@ -310,6 +315,7 @@ var ScaleMuleClient = class {
|
|
|
310
315
|
this.offlineQueue = new OfflineQueue(this.storage);
|
|
311
316
|
this.offlineQueue.setOnlineCallback(() => this.syncOfflineQueue());
|
|
312
317
|
}
|
|
318
|
+
this.multiSessionEnabled = config.enableMultiSession || false;
|
|
313
319
|
}
|
|
314
320
|
// --------------------------------------------------------------------------
|
|
315
321
|
// Session Management
|
|
@@ -321,7 +327,46 @@ var ScaleMuleClient = class {
|
|
|
321
327
|
if (userId) this.userId = userId;
|
|
322
328
|
const wsId = await this.storage.getItem(WORKSPACE_STORAGE_KEY);
|
|
323
329
|
if (wsId) this.workspaceId = wsId;
|
|
324
|
-
|
|
330
|
+
let anonId = await this.storage.getItem(ANONYMOUS_ID_STORAGE_KEY);
|
|
331
|
+
if (!anonId) {
|
|
332
|
+
anonId = crypto.randomUUID();
|
|
333
|
+
await this.storage.setItem(ANONYMOUS_ID_STORAGE_KEY, anonId);
|
|
334
|
+
}
|
|
335
|
+
this.anonymousId = anonId;
|
|
336
|
+
if (this.multiSessionEnabled) {
|
|
337
|
+
const poolJson = await this.storage.getItem(SESSION_POOL_KEY);
|
|
338
|
+
if (poolJson) {
|
|
339
|
+
try {
|
|
340
|
+
const entries = JSON.parse(poolJson);
|
|
341
|
+
this.sessionPool = new Map(Object.entries(entries));
|
|
342
|
+
} catch {
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
if (token && userId && !this.sessionPool.has(userId)) {
|
|
346
|
+
this.sessionPool.set(userId, {
|
|
347
|
+
token,
|
|
348
|
+
userId,
|
|
349
|
+
email: "",
|
|
350
|
+
addedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
351
|
+
});
|
|
352
|
+
await this.persistSessionPool();
|
|
353
|
+
}
|
|
354
|
+
const activeId = await this.storage.getItem(ACTIVE_ACCOUNT_KEY);
|
|
355
|
+
if (activeId && this.sessionPool.has(activeId)) {
|
|
356
|
+
const entry = this.sessionPool.get(activeId);
|
|
357
|
+
this.sessionToken = entry.token;
|
|
358
|
+
this.userId = activeId;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
if (this.debug)
|
|
362
|
+
console.log(
|
|
363
|
+
"[ScaleMule] Initialized, session:",
|
|
364
|
+
!!this.sessionToken,
|
|
365
|
+
"anonymousId:",
|
|
366
|
+
anonId,
|
|
367
|
+
"poolSize:",
|
|
368
|
+
this.sessionPool.size
|
|
369
|
+
);
|
|
325
370
|
}
|
|
326
371
|
async setSession(token, userId) {
|
|
327
372
|
this.sessionToken = token;
|
|
@@ -330,12 +375,27 @@ var ScaleMuleClient = class {
|
|
|
330
375
|
await this.storage.setItem(USER_ID_STORAGE_KEY, userId);
|
|
331
376
|
}
|
|
332
377
|
async clearSession() {
|
|
378
|
+
if (this.multiSessionEnabled && this.userId) {
|
|
379
|
+
this.sessionPool.delete(this.userId);
|
|
380
|
+
await this.persistSessionPool();
|
|
381
|
+
const next = this.sessionPool.entries().next().value;
|
|
382
|
+
if (next) {
|
|
383
|
+
const [nextUserId, nextEntry] = next;
|
|
384
|
+
this.sessionToken = nextEntry.token;
|
|
385
|
+
this.userId = nextUserId;
|
|
386
|
+
await this.storage.setItem(SESSION_STORAGE_KEY, nextEntry.token);
|
|
387
|
+
await this.storage.setItem(USER_ID_STORAGE_KEY, nextUserId);
|
|
388
|
+
await this.storage.setItem(ACTIVE_ACCOUNT_KEY, nextUserId);
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
333
392
|
this.sessionToken = null;
|
|
334
393
|
this.userId = null;
|
|
335
394
|
this.workspaceId = null;
|
|
336
395
|
await this.storage.removeItem(SESSION_STORAGE_KEY);
|
|
337
396
|
await this.storage.removeItem(USER_ID_STORAGE_KEY);
|
|
338
397
|
await this.storage.removeItem(WORKSPACE_STORAGE_KEY);
|
|
398
|
+
await this.storage.removeItem(ACTIVE_ACCOUNT_KEY);
|
|
339
399
|
}
|
|
340
400
|
setAccessToken(token) {
|
|
341
401
|
this.sessionToken = token;
|
|
@@ -352,6 +412,80 @@ var ScaleMuleClient = class {
|
|
|
352
412
|
isAuthenticated() {
|
|
353
413
|
return this.sessionToken !== null;
|
|
354
414
|
}
|
|
415
|
+
getAnonymousId() {
|
|
416
|
+
return this.anonymousId;
|
|
417
|
+
}
|
|
418
|
+
isMultiSessionEnabled() {
|
|
419
|
+
return this.multiSessionEnabled;
|
|
420
|
+
}
|
|
421
|
+
// --------------------------------------------------------------------------
|
|
422
|
+
// Multi-Account Session Pool (Phase 2)
|
|
423
|
+
// --------------------------------------------------------------------------
|
|
424
|
+
/** Get all accounts in the session pool */
|
|
425
|
+
getSessionPool() {
|
|
426
|
+
return Array.from(this.sessionPool.values());
|
|
427
|
+
}
|
|
428
|
+
/** Get the active account entry, or null */
|
|
429
|
+
getActiveAccount() {
|
|
430
|
+
if (!this.userId) return null;
|
|
431
|
+
return this.sessionPool.get(this.userId) || null;
|
|
432
|
+
}
|
|
433
|
+
/** Add an account to the session pool and set it as active */
|
|
434
|
+
async addAccount(entry) {
|
|
435
|
+
this.sessionPool.set(entry.userId, entry);
|
|
436
|
+
this.sessionToken = entry.token;
|
|
437
|
+
this.userId = entry.userId;
|
|
438
|
+
await this.storage.setItem(SESSION_STORAGE_KEY, entry.token);
|
|
439
|
+
await this.storage.setItem(USER_ID_STORAGE_KEY, entry.userId);
|
|
440
|
+
await this.storage.setItem(ACTIVE_ACCOUNT_KEY, entry.userId);
|
|
441
|
+
await this.persistSessionPool();
|
|
442
|
+
}
|
|
443
|
+
/** Switch to a different account in the pool. Returns false if not found. */
|
|
444
|
+
async switchAccount(userId) {
|
|
445
|
+
const entry = this.sessionPool.get(userId);
|
|
446
|
+
if (!entry) return false;
|
|
447
|
+
this.sessionToken = entry.token;
|
|
448
|
+
this.userId = userId;
|
|
449
|
+
this.workspaceId = null;
|
|
450
|
+
await this.storage.setItem(SESSION_STORAGE_KEY, entry.token);
|
|
451
|
+
await this.storage.setItem(USER_ID_STORAGE_KEY, userId);
|
|
452
|
+
await this.storage.setItem(ACTIVE_ACCOUNT_KEY, userId);
|
|
453
|
+
await this.storage.removeItem(WORKSPACE_STORAGE_KEY);
|
|
454
|
+
return true;
|
|
455
|
+
}
|
|
456
|
+
/** Remove a specific account from the pool */
|
|
457
|
+
async removeAccount(userId) {
|
|
458
|
+
this.sessionPool.delete(userId);
|
|
459
|
+
await this.persistSessionPool();
|
|
460
|
+
if (this.userId === userId) {
|
|
461
|
+
const next = this.sessionPool.entries().next().value;
|
|
462
|
+
if (next) {
|
|
463
|
+
await this.switchAccount(next[0]);
|
|
464
|
+
} else {
|
|
465
|
+
await this.clearSession();
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
/** Clear all accounts from the pool */
|
|
470
|
+
async clearAllAccounts() {
|
|
471
|
+
this.sessionPool.clear();
|
|
472
|
+
await this.storage.removeItem(SESSION_POOL_KEY);
|
|
473
|
+
await this.storage.removeItem(ACTIVE_ACCOUNT_KEY);
|
|
474
|
+
this.sessionToken = null;
|
|
475
|
+
this.userId = null;
|
|
476
|
+
this.workspaceId = null;
|
|
477
|
+
await this.storage.removeItem(SESSION_STORAGE_KEY);
|
|
478
|
+
await this.storage.removeItem(USER_ID_STORAGE_KEY);
|
|
479
|
+
await this.storage.removeItem(WORKSPACE_STORAGE_KEY);
|
|
480
|
+
}
|
|
481
|
+
/** Persist session pool to storage */
|
|
482
|
+
async persistSessionPool() {
|
|
483
|
+
const obj = {};
|
|
484
|
+
for (const [k, v] of this.sessionPool) {
|
|
485
|
+
obj[k] = v;
|
|
486
|
+
}
|
|
487
|
+
await this.storage.setItem(SESSION_POOL_KEY, JSON.stringify(obj));
|
|
488
|
+
}
|
|
355
489
|
getBaseUrl() {
|
|
356
490
|
return this.baseUrl;
|
|
357
491
|
}
|
|
@@ -401,6 +535,9 @@ var ScaleMuleClient = class {
|
|
|
401
535
|
if (this.workspaceId) {
|
|
402
536
|
headers["x-sm-workspace-id"] = this.workspaceId;
|
|
403
537
|
}
|
|
538
|
+
if (!this.sessionToken && this.anonymousId) {
|
|
539
|
+
headers["x-anonymous-id"] = this.anonymousId;
|
|
540
|
+
}
|
|
404
541
|
let bodyStr;
|
|
405
542
|
if (init.body !== void 0 && init.body !== null) {
|
|
406
543
|
bodyStr = typeof init.body === "string" ? init.body : JSON.stringify(init.body);
|
|
@@ -857,6 +994,21 @@ import {
|
|
|
857
994
|
} from "@scalemule/ui/phone";
|
|
858
995
|
|
|
859
996
|
// src/services/auth.ts
|
|
997
|
+
function collectDeviceFingerprint() {
|
|
998
|
+
if (typeof window === "undefined" || typeof navigator === "undefined") return void 0;
|
|
999
|
+
try {
|
|
1000
|
+
return {
|
|
1001
|
+
screen: `${screen.width}x${screen.height}x${screen.colorDepth}`,
|
|
1002
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
1003
|
+
language: navigator.language,
|
|
1004
|
+
platform: navigator.platform,
|
|
1005
|
+
cookie_enabled: navigator.cookieEnabled,
|
|
1006
|
+
do_not_track: navigator.doNotTrack
|
|
1007
|
+
};
|
|
1008
|
+
} catch {
|
|
1009
|
+
return void 0;
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
860
1012
|
var AuthMfaApi = class extends ServiceModule {
|
|
861
1013
|
constructor() {
|
|
862
1014
|
super(...arguments);
|
|
@@ -955,12 +1107,42 @@ var AuthService = class extends ServiceModule {
|
|
|
955
1107
|
async register(data, options) {
|
|
956
1108
|
const payload = {
|
|
957
1109
|
...data,
|
|
958
|
-
phone: this.sanitizePhoneField(data.phone)
|
|
1110
|
+
phone: this.sanitizePhoneField(data.phone),
|
|
1111
|
+
anonymous_id: this.client.getAnonymousId()
|
|
959
1112
|
};
|
|
960
|
-
|
|
1113
|
+
const result = await this.post("/register", payload, options);
|
|
1114
|
+
if (result.data && this.client.isMultiSessionEnabled()) {
|
|
1115
|
+
await this.client.addAccount({
|
|
1116
|
+
token: result.data.session_token,
|
|
1117
|
+
userId: result.data.user.id,
|
|
1118
|
+
email: result.data.user.email,
|
|
1119
|
+
fullName: result.data.user.full_name,
|
|
1120
|
+
avatarUrl: result.data.user.avatar_url,
|
|
1121
|
+
expiresAt: result.data.expires_at,
|
|
1122
|
+
addedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1123
|
+
});
|
|
1124
|
+
}
|
|
1125
|
+
return result;
|
|
961
1126
|
}
|
|
962
1127
|
async login(data, options) {
|
|
963
|
-
|
|
1128
|
+
const payload = {
|
|
1129
|
+
...data,
|
|
1130
|
+
anonymous_id: this.client.getAnonymousId(),
|
|
1131
|
+
device_fingerprint: data.device_fingerprint || collectDeviceFingerprint()
|
|
1132
|
+
};
|
|
1133
|
+
const result = await this.post("/login", payload, options);
|
|
1134
|
+
if (result.data && this.client.isMultiSessionEnabled()) {
|
|
1135
|
+
await this.client.addAccount({
|
|
1136
|
+
token: result.data.session_token,
|
|
1137
|
+
userId: result.data.user.id,
|
|
1138
|
+
email: result.data.user.email,
|
|
1139
|
+
fullName: result.data.user.full_name,
|
|
1140
|
+
avatarUrl: result.data.user.avatar_url,
|
|
1141
|
+
expiresAt: result.data.expires_at,
|
|
1142
|
+
addedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1143
|
+
});
|
|
1144
|
+
}
|
|
1145
|
+
return result;
|
|
964
1146
|
}
|
|
965
1147
|
async logout(options) {
|
|
966
1148
|
return this.post("/logout", void 0, options);
|
|
@@ -2488,7 +2670,7 @@ function asNumber2(value) {
|
|
|
2488
2670
|
|
|
2489
2671
|
// src/services/upload-strategy.ts
|
|
2490
2672
|
var MULTIPART_THRESHOLD2 = 8 * 1024 * 1024;
|
|
2491
|
-
var MULTIPART_THRESHOLD_SLOW2 =
|
|
2673
|
+
var MULTIPART_THRESHOLD_SLOW2 = 1 * 1024 * 1024;
|
|
2492
2674
|
var DEFAULT_STALL_TIMEOUT_MS2 = 45e3;
|
|
2493
2675
|
var SLOW_STALL_TIMEOUT_MS = 9e4;
|
|
2494
2676
|
var CHUNK_SIZES = {
|
|
@@ -3718,7 +3900,11 @@ var AnalyticsService = class extends ServiceModule {
|
|
|
3718
3900
|
// Event Tracking (v2 — JetStream buffered)
|
|
3719
3901
|
// --------------------------------------------------------------------------
|
|
3720
3902
|
async track(event, properties, userId, options) {
|
|
3721
|
-
|
|
3903
|
+
const payload = { event_name: event, properties, user_id: userId };
|
|
3904
|
+
if (!userId && !this.client.isAuthenticated()) {
|
|
3905
|
+
payload.anonymous_id = this.client.getAnonymousId();
|
|
3906
|
+
}
|
|
3907
|
+
return this.post("/v2/events", payload, options);
|
|
3722
3908
|
}
|
|
3723
3909
|
async trackBatch(events, options) {
|
|
3724
3910
|
const mapped = events.map(({ event, ...rest }) => ({ event_name: event, ...rest }));
|
|
@@ -4582,17 +4768,38 @@ var PhotoService = class extends ServiceModule {
|
|
|
4582
4768
|
* Use this when files are uploaded via the storage service (presigned URL)
|
|
4583
4769
|
* instead of the photo service's upload endpoint.
|
|
4584
4770
|
*
|
|
4771
|
+
* If the file scan is still in progress, the server waits briefly (~5s) for it
|
|
4772
|
+
* to complete. In the rare case the scan exceeds that window, the server queues
|
|
4773
|
+
* the registration and returns 202; this method retries automatically until the
|
|
4774
|
+
* photo record is available.
|
|
4775
|
+
*
|
|
4585
4776
|
* Returns the photo record with `id` that can be used with `getTransformUrl()`.
|
|
4586
4777
|
*/
|
|
4587
4778
|
async register(registerOptions, requestOptions) {
|
|
4588
|
-
|
|
4589
|
-
|
|
4590
|
-
|
|
4591
|
-
|
|
4592
|
-
|
|
4593
|
-
|
|
4594
|
-
|
|
4595
|
-
|
|
4779
|
+
const body = {
|
|
4780
|
+
file_id: registerOptions.fileId,
|
|
4781
|
+
sm_user_id: registerOptions.userId
|
|
4782
|
+
};
|
|
4783
|
+
const result = await this.post("/register", body, requestOptions);
|
|
4784
|
+
const isPending = (r) => !r.error && r.data && "status" in r.data && r.data.status === "pending_scan";
|
|
4785
|
+
if (!isPending(result)) {
|
|
4786
|
+
return result;
|
|
4787
|
+
}
|
|
4788
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
4789
|
+
await new Promise((r) => setTimeout(r, 1e3));
|
|
4790
|
+
const retry = await this.post("/register", body, requestOptions);
|
|
4791
|
+
if (!isPending(retry)) {
|
|
4792
|
+
return retry;
|
|
4793
|
+
}
|
|
4794
|
+
}
|
|
4795
|
+
return {
|
|
4796
|
+
data: null,
|
|
4797
|
+
error: {
|
|
4798
|
+
code: "scan_timeout",
|
|
4799
|
+
message: "File scan did not complete in time. The photo will be registered automatically when the scan finishes.",
|
|
4800
|
+
status: 202
|
|
4801
|
+
}
|
|
4802
|
+
};
|
|
4596
4803
|
}
|
|
4597
4804
|
/** @deprecated Use upload() instead */
|
|
4598
4805
|
async uploadPhoto(file, options) {
|
|
@@ -4821,6 +5028,18 @@ var IdentityService = class extends ServiceModule {
|
|
|
4821
5028
|
async revokeApiKey(id, options) {
|
|
4822
5029
|
return this.del(`/api-keys/${id}`, options);
|
|
4823
5030
|
}
|
|
5031
|
+
/**
|
|
5032
|
+
* Explicitly link an anonymous_id to the current authenticated user.
|
|
5033
|
+
* Called automatically on init when both a session and anonymous_id exist
|
|
5034
|
+
* (transitional path for users who registered before identity linking existed).
|
|
5035
|
+
*/
|
|
5036
|
+
async identify(anonymousId, deviceFingerprintHash, options) {
|
|
5037
|
+
return this.post(
|
|
5038
|
+
"/identify",
|
|
5039
|
+
{ anonymous_id: anonymousId, device_fingerprint_hash: deviceFingerprintHash },
|
|
5040
|
+
options
|
|
5041
|
+
);
|
|
5042
|
+
}
|
|
4824
5043
|
};
|
|
4825
5044
|
|
|
4826
5045
|
// src/services/catalog.ts
|
|
@@ -5377,7 +5596,12 @@ var ScaleMule = class {
|
|
|
5377
5596
|
* Call this once after construction, before making authenticated requests.
|
|
5378
5597
|
*/
|
|
5379
5598
|
async initialize() {
|
|
5380
|
-
|
|
5599
|
+
await this._client.initialize();
|
|
5600
|
+
const anonymousId = this._client.getAnonymousId();
|
|
5601
|
+
if (this._client.isAuthenticated() && anonymousId) {
|
|
5602
|
+
this.identity.identify(anonymousId).catch(() => {
|
|
5603
|
+
});
|
|
5604
|
+
}
|
|
5381
5605
|
}
|
|
5382
5606
|
/**
|
|
5383
5607
|
* Set authentication session (token + userId).
|
|
@@ -5410,6 +5634,33 @@ var ScaleMule = class {
|
|
|
5410
5634
|
isAuthenticated() {
|
|
5411
5635
|
return this._client.isAuthenticated();
|
|
5412
5636
|
}
|
|
5637
|
+
/** The anonymous visitor ID used for identity linking. */
|
|
5638
|
+
getAnonymousId() {
|
|
5639
|
+
return this._client.getAnonymousId();
|
|
5640
|
+
}
|
|
5641
|
+
// --------------------------------------------------------------------------
|
|
5642
|
+
// Multi-Account Session Pool (Phase 2)
|
|
5643
|
+
// --------------------------------------------------------------------------
|
|
5644
|
+
/** Get all accounts in the session pool (requires enableMultiSession) */
|
|
5645
|
+
getSessionPool() {
|
|
5646
|
+
return this._client.getSessionPool();
|
|
5647
|
+
}
|
|
5648
|
+
/** Get the active account, or null */
|
|
5649
|
+
getActiveAccount() {
|
|
5650
|
+
return this._client.getActiveAccount();
|
|
5651
|
+
}
|
|
5652
|
+
/** Switch to a different account in the pool. Returns false if not found. */
|
|
5653
|
+
async switchAccount(userId) {
|
|
5654
|
+
return this._client.switchAccount(userId);
|
|
5655
|
+
}
|
|
5656
|
+
/** Remove a specific account from the pool */
|
|
5657
|
+
async removeAccount(userId) {
|
|
5658
|
+
return this._client.removeAccount(userId);
|
|
5659
|
+
}
|
|
5660
|
+
/** Clear all accounts from the pool */
|
|
5661
|
+
async clearAllAccounts() {
|
|
5662
|
+
return this._client.clearAllAccounts();
|
|
5663
|
+
}
|
|
5413
5664
|
/** The base URL being used for API requests. */
|
|
5414
5665
|
getBaseUrl() {
|
|
5415
5666
|
return this._client.getBaseUrl();
|