@scalemule/sdk 0.0.56 → 0.0.58

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
@@ -260,6 +260,13 @@ interface ClientContext {
260
260
  deviceFingerprint?: string;
261
261
  /** HTTP Referer header from the end-user's request */
262
262
  referrer?: string;
263
+ /**
264
+ * End-user anonymous visitor ID, forwarded as `x-anonymous-id`. Set on
265
+ * unauthenticated requests so the backend can link the visitor's pre-auth
266
+ * activity to a registered user on login/register. Populated automatically
267
+ * by `extractClientContext()` when the upstream request carries the header.
268
+ */
269
+ anonymousId?: string;
263
270
  }
264
271
 
265
272
  /**
@@ -331,6 +338,84 @@ declare function extractClientContext(request: IncomingRequestLike): ClientConte
331
338
  */
332
339
  declare function buildClientContextHeaders(context: ClientContext | undefined): Record<string, string>;
333
340
 
341
+ /**
342
+ * Anonymous-ID Contract (Shared)
343
+ *
344
+ * Single source of truth for the visitor's anonymous ID across every
345
+ * ScaleMule client package (`@scalemule/sdk`, `@scalemule/nextjs`, future
346
+ * react-native, etc).
347
+ *
348
+ * Why this lives here, in `@scalemule/sdk`:
349
+ * The platform contract is the HTTP header `x-anonymous-id`. The backend
350
+ * (`ms/scalemule-auth/src/handlers/register.rs`, `login.rs`, `oauth.rs`)
351
+ * reads that header to link anonymous activity to a newly registered user.
352
+ * If two packages disagree on the localStorage key they read/write, the
353
+ * visitor's analytics events and their `x-anonymous-id` header don't
354
+ * match, and the link pipeline attributes events to the wrong identity.
355
+ * Past drift: `@scalemule/nextjs` minted its own ID under `sm_anonymous_id`
356
+ * while this package wrote `scalemule_anonymous_id`. This module collapses
357
+ * that into one helper everyone calls.
358
+ *
359
+ * Migration:
360
+ * `ensureAnonymousId()` reads canonical first, falls back to the legacy
361
+ * key, and dual-writes both during the rollout window. The dual-write +
362
+ * legacy-read can be retired once every maintained `@scalemule/nextjs`
363
+ * consumer has been on a fixed version in production for two release
364
+ * cycles. Tracked in code by the comment near `LEGACY_ANONYMOUS_ID_KEYS`.
365
+ */
366
+
367
+ /**
368
+ * Canonical browser storage keys owned by `@scalemule/sdk`. Other packages
369
+ * MUST import these rather than redeclare their own strings.
370
+ */
371
+ declare const STORAGE_KEYS: {
372
+ readonly SESSION: "scalemule_session";
373
+ readonly USER_ID: "scalemule_user_id";
374
+ readonly WORKSPACE_ID: "scalemule_workspace_id";
375
+ readonly ANONYMOUS_ID: "scalemule_anonymous_id";
376
+ readonly SESSION_POOL: "scalemule_session_pool";
377
+ readonly ACTIVE_ACCOUNT: "scalemule_active_account";
378
+ readonly KNOWN_ACCOUNTS: "scalemule_known_accounts";
379
+ readonly OFFLINE_QUEUE: "scalemule_offline_queue";
380
+ };
381
+ /**
382
+ * Legacy anonymous-ID keys read for migration. Drop entries from this list
383
+ * once we're confident no shipping client still writes them.
384
+ *
385
+ * - `sm_anonymous_id`: previously minted by the `useAnalytics` hook in
386
+ * `@scalemule/nextjs` versions prior to the consolidation.
387
+ */
388
+ declare const LEGACY_ANONYMOUS_ID_KEYS: readonly string[];
389
+ /** UUIDv4 generator with a graceful fallback for environments without `crypto.randomUUID`. */
390
+ declare function generateAnonymousId(): string;
391
+ /**
392
+ * Sync-style read of the canonical anonymous-ID without minting.
393
+ *
394
+ * Returns `null` if storage hasn't been touched yet. Useful when you want
395
+ * to check "is there already a cached ID" without triggering an async
396
+ * write. For the create-if-missing path, use `ensureAnonymousId()`.
397
+ */
398
+ declare function readAnonymousId(storage: StorageAdapter): Promise<string | null>;
399
+ /**
400
+ * Read-or-create the anonymous ID with legacy-key migration and dual-write.
401
+ *
402
+ * Algorithm:
403
+ * 1. Read canonical key — if present, return it (no writes).
404
+ * 2. Read any legacy key — if present, promote it: write to canonical AND
405
+ * keep the legacy key in step with it so a stale tab running old code
406
+ * doesn't desync. Return the value.
407
+ * 3. No ID exists — mint a new UUID, dual-write canonical + legacy keys,
408
+ * return it.
409
+ *
410
+ * Concurrent callers against the same storage adapter are single-flighted
411
+ * — the second caller receives the same promise as the first.
412
+ *
413
+ * Idempotent. Safe to call on every request that needs the header. If you
414
+ * cache the result in memory on the client, you can avoid the storage
415
+ * round-trip after the first call.
416
+ */
417
+ declare function ensureAnonymousId(storage: StorageAdapter): Promise<string>;
418
+
334
419
  declare class ScaleMuleClient {
335
420
  private apiKey;
336
421
  private applicationId;
@@ -346,6 +431,7 @@ declare class ScaleMuleClient {
346
431
  private offlineQueue;
347
432
  private workspaceId;
348
433
  private anonymousId;
434
+ private anonymousIdPromise;
349
435
  private multiSessionEnabled;
350
436
  private sessionPool;
351
437
  private accountSwitcherEnabled;
@@ -365,7 +451,25 @@ declare class ScaleMuleClient {
365
451
  getApplicationId(): string | null;
366
452
  getUserId(): string | null;
367
453
  isAuthenticated(): boolean;
454
+ /**
455
+ * Sync accessor for the cached anonymous ID. Returns `null` until either
456
+ * `initialize()` has run or `ensureAnonymousId()` has been awaited at
457
+ * least once. Use `ensureAnonymousId()` if you need a guaranteed value.
458
+ */
368
459
  getAnonymousId(): string | null;
460
+ /**
461
+ * Lazy-mint or cache-then-return the anonymous ID.
462
+ *
463
+ * Always returns a usable string. Callers that need to attach the
464
+ * `x-anonymous-id` header before `initialize()` has completed (rare —
465
+ * usually only the very first unauthenticated request from a freshly
466
+ * constructed client) should `await` this rather than relying on
467
+ * `getAnonymousId()`.
468
+ *
469
+ * Concurrent callers receive the same in-flight promise — no risk of
470
+ * two simultaneous first requests minting two distinct IDs.
471
+ */
472
+ ensureAnonymousId(): Promise<string>;
369
473
  isMultiSessionEnabled(): boolean;
370
474
  /** Get all accounts in the session pool */
371
475
  getSessionPool(): SessionPoolEntry[];
@@ -4687,6 +4791,17 @@ interface TransformResult {
4687
4791
  height: number;
4688
4792
  format: string;
4689
4793
  }
4794
+ type PhotoPreset = 'hero' | 'inline' | 'thumbnail' | 'avatar' | 'logo';
4795
+ interface PhotoManifest {
4796
+ file_id: string;
4797
+ photo_id: string;
4798
+ content_type: string;
4799
+ preset: PhotoPreset | 'original';
4800
+ ready: boolean;
4801
+ variants: Record<string, string>;
4802
+ srcset: string | null;
4803
+ default: string | null;
4804
+ }
4690
4805
  /** Options for building a transform URL or requesting a transform */
4691
4806
  interface TransformOptions {
4692
4807
  width?: number;
@@ -4745,6 +4860,15 @@ declare class PhotoService extends ServiceModule {
4745
4860
  delete(id: string, options?: RequestOptions): Promise<ApiResponse<{
4746
4861
  deleted: boolean;
4747
4862
  }>>;
4863
+ getPresets(options?: RequestOptions): Promise<ApiResponse<Record<PhotoPreset, {
4864
+ widths: number[];
4865
+ }>>>;
4866
+ getManifest(id: string, params?: {
4867
+ preset?: PhotoPreset;
4868
+ }, options?: RequestOptions): Promise<ApiResponse<PhotoManifest>>;
4869
+ getPublicManifest(id: string, params?: {
4870
+ preset?: PhotoPreset;
4871
+ }, options?: RequestOptions): Promise<ApiResponse<PhotoManifest>>;
4748
4872
  /**
4749
4873
  * Build an absolute URL for the on-demand transform endpoint.
4750
4874
  *
@@ -5005,6 +5129,7 @@ interface MediaManifest {
5005
5129
  file_id: string;
5006
5130
  content_type: string;
5007
5131
  preset: MediaPreset | 'original';
5132
+ ready?: boolean;
5008
5133
  variants: Record<string, string>;
5009
5134
  srcset: string | null;
5010
5135
  default: string | null;
@@ -5071,14 +5196,15 @@ declare class MediaService extends ServiceModule {
5071
5196
  getManifest(fileId: string, options?: MediaManifestOptions, requestOptions?: RequestOptions): Promise<ApiResponse<MediaManifest>>;
5072
5197
  buildAsset(file: FileInfo, options?: MediaManifestOptions & {
5073
5198
  photoId?: string | null;
5074
- }): MediaAsset;
5199
+ }, manifest?: MediaManifest | null): MediaAsset;
5075
5200
  buildManifest(file: FileInfo, options?: MediaManifestOptions): MediaManifest | null;
5076
5201
  private uploadAnonymous;
5077
5202
  private uploadImage;
5078
5203
  private waitForAnonymousReady;
5079
5204
  private fetchInfoBestEffort;
5205
+ private fetchManifest;
5080
5206
  private pollPhotoOptimizationComplete;
5081
- private prewarmManifest;
5207
+ private waitForAnonymousManifest;
5082
5208
  }
5083
5209
 
5084
5210
  type TtsAccessMode = 'owner_private' | 'tenant_shared' | 'public';
@@ -6974,4 +7100,4 @@ declare class ScaleMule {
6974
7100
  getClient(): ScaleMuleClient;
6975
7101
  }
6976
7102
 
6977
- 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, MEDIA_PRESETS, type MediaAsset, type MediaKind, type MediaManifest, type MediaManifestOptions, type MediaPolicy, type MediaPreset, type MediaPresetSpec, MediaService, type MediaUploadEvent, type MediaUploadOptions, type MediaUploadPhase, type MediaUploadResult, 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 TtsSpeechMetadata, type TtsSpeechProfile, 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 };
7103
+ 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, LEGACY_ANONYMOUS_ID_KEYS, 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, MEDIA_PRESETS, type MediaAsset, type MediaKind, type MediaManifest, type MediaManifestOptions, type MediaPolicy, type MediaPreset, type MediaPresetSpec, MediaService, type MediaUploadEvent, type MediaUploadOptions, type MediaUploadPhase, type MediaUploadResult, 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, STORAGE_KEYS, 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 TtsSpeechMetadata, type TtsSpeechProfile, 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, ensureAnonymousId, extractClientContext, generateAnonymousId, generateUploadSessionId, getMeasuredBandwidthMbps, getPartRange, hasMinRoleLevel, readAnonymousId, resolveStrategy, uploadMultipartToS3, uploadSingleToS3, validateIP };
package/dist/index.d.ts CHANGED
@@ -260,6 +260,13 @@ interface ClientContext {
260
260
  deviceFingerprint?: string;
261
261
  /** HTTP Referer header from the end-user's request */
262
262
  referrer?: string;
263
+ /**
264
+ * End-user anonymous visitor ID, forwarded as `x-anonymous-id`. Set on
265
+ * unauthenticated requests so the backend can link the visitor's pre-auth
266
+ * activity to a registered user on login/register. Populated automatically
267
+ * by `extractClientContext()` when the upstream request carries the header.
268
+ */
269
+ anonymousId?: string;
263
270
  }
264
271
 
265
272
  /**
@@ -331,6 +338,84 @@ declare function extractClientContext(request: IncomingRequestLike): ClientConte
331
338
  */
332
339
  declare function buildClientContextHeaders(context: ClientContext | undefined): Record<string, string>;
333
340
 
341
+ /**
342
+ * Anonymous-ID Contract (Shared)
343
+ *
344
+ * Single source of truth for the visitor's anonymous ID across every
345
+ * ScaleMule client package (`@scalemule/sdk`, `@scalemule/nextjs`, future
346
+ * react-native, etc).
347
+ *
348
+ * Why this lives here, in `@scalemule/sdk`:
349
+ * The platform contract is the HTTP header `x-anonymous-id`. The backend
350
+ * (`ms/scalemule-auth/src/handlers/register.rs`, `login.rs`, `oauth.rs`)
351
+ * reads that header to link anonymous activity to a newly registered user.
352
+ * If two packages disagree on the localStorage key they read/write, the
353
+ * visitor's analytics events and their `x-anonymous-id` header don't
354
+ * match, and the link pipeline attributes events to the wrong identity.
355
+ * Past drift: `@scalemule/nextjs` minted its own ID under `sm_anonymous_id`
356
+ * while this package wrote `scalemule_anonymous_id`. This module collapses
357
+ * that into one helper everyone calls.
358
+ *
359
+ * Migration:
360
+ * `ensureAnonymousId()` reads canonical first, falls back to the legacy
361
+ * key, and dual-writes both during the rollout window. The dual-write +
362
+ * legacy-read can be retired once every maintained `@scalemule/nextjs`
363
+ * consumer has been on a fixed version in production for two release
364
+ * cycles. Tracked in code by the comment near `LEGACY_ANONYMOUS_ID_KEYS`.
365
+ */
366
+
367
+ /**
368
+ * Canonical browser storage keys owned by `@scalemule/sdk`. Other packages
369
+ * MUST import these rather than redeclare their own strings.
370
+ */
371
+ declare const STORAGE_KEYS: {
372
+ readonly SESSION: "scalemule_session";
373
+ readonly USER_ID: "scalemule_user_id";
374
+ readonly WORKSPACE_ID: "scalemule_workspace_id";
375
+ readonly ANONYMOUS_ID: "scalemule_anonymous_id";
376
+ readonly SESSION_POOL: "scalemule_session_pool";
377
+ readonly ACTIVE_ACCOUNT: "scalemule_active_account";
378
+ readonly KNOWN_ACCOUNTS: "scalemule_known_accounts";
379
+ readonly OFFLINE_QUEUE: "scalemule_offline_queue";
380
+ };
381
+ /**
382
+ * Legacy anonymous-ID keys read for migration. Drop entries from this list
383
+ * once we're confident no shipping client still writes them.
384
+ *
385
+ * - `sm_anonymous_id`: previously minted by the `useAnalytics` hook in
386
+ * `@scalemule/nextjs` versions prior to the consolidation.
387
+ */
388
+ declare const LEGACY_ANONYMOUS_ID_KEYS: readonly string[];
389
+ /** UUIDv4 generator with a graceful fallback for environments without `crypto.randomUUID`. */
390
+ declare function generateAnonymousId(): string;
391
+ /**
392
+ * Sync-style read of the canonical anonymous-ID without minting.
393
+ *
394
+ * Returns `null` if storage hasn't been touched yet. Useful when you want
395
+ * to check "is there already a cached ID" without triggering an async
396
+ * write. For the create-if-missing path, use `ensureAnonymousId()`.
397
+ */
398
+ declare function readAnonymousId(storage: StorageAdapter): Promise<string | null>;
399
+ /**
400
+ * Read-or-create the anonymous ID with legacy-key migration and dual-write.
401
+ *
402
+ * Algorithm:
403
+ * 1. Read canonical key — if present, return it (no writes).
404
+ * 2. Read any legacy key — if present, promote it: write to canonical AND
405
+ * keep the legacy key in step with it so a stale tab running old code
406
+ * doesn't desync. Return the value.
407
+ * 3. No ID exists — mint a new UUID, dual-write canonical + legacy keys,
408
+ * return it.
409
+ *
410
+ * Concurrent callers against the same storage adapter are single-flighted
411
+ * — the second caller receives the same promise as the first.
412
+ *
413
+ * Idempotent. Safe to call on every request that needs the header. If you
414
+ * cache the result in memory on the client, you can avoid the storage
415
+ * round-trip after the first call.
416
+ */
417
+ declare function ensureAnonymousId(storage: StorageAdapter): Promise<string>;
418
+
334
419
  declare class ScaleMuleClient {
335
420
  private apiKey;
336
421
  private applicationId;
@@ -346,6 +431,7 @@ declare class ScaleMuleClient {
346
431
  private offlineQueue;
347
432
  private workspaceId;
348
433
  private anonymousId;
434
+ private anonymousIdPromise;
349
435
  private multiSessionEnabled;
350
436
  private sessionPool;
351
437
  private accountSwitcherEnabled;
@@ -365,7 +451,25 @@ declare class ScaleMuleClient {
365
451
  getApplicationId(): string | null;
366
452
  getUserId(): string | null;
367
453
  isAuthenticated(): boolean;
454
+ /**
455
+ * Sync accessor for the cached anonymous ID. Returns `null` until either
456
+ * `initialize()` has run or `ensureAnonymousId()` has been awaited at
457
+ * least once. Use `ensureAnonymousId()` if you need a guaranteed value.
458
+ */
368
459
  getAnonymousId(): string | null;
460
+ /**
461
+ * Lazy-mint or cache-then-return the anonymous ID.
462
+ *
463
+ * Always returns a usable string. Callers that need to attach the
464
+ * `x-anonymous-id` header before `initialize()` has completed (rare —
465
+ * usually only the very first unauthenticated request from a freshly
466
+ * constructed client) should `await` this rather than relying on
467
+ * `getAnonymousId()`.
468
+ *
469
+ * Concurrent callers receive the same in-flight promise — no risk of
470
+ * two simultaneous first requests minting two distinct IDs.
471
+ */
472
+ ensureAnonymousId(): Promise<string>;
369
473
  isMultiSessionEnabled(): boolean;
370
474
  /** Get all accounts in the session pool */
371
475
  getSessionPool(): SessionPoolEntry[];
@@ -4687,6 +4791,17 @@ interface TransformResult {
4687
4791
  height: number;
4688
4792
  format: string;
4689
4793
  }
4794
+ type PhotoPreset = 'hero' | 'inline' | 'thumbnail' | 'avatar' | 'logo';
4795
+ interface PhotoManifest {
4796
+ file_id: string;
4797
+ photo_id: string;
4798
+ content_type: string;
4799
+ preset: PhotoPreset | 'original';
4800
+ ready: boolean;
4801
+ variants: Record<string, string>;
4802
+ srcset: string | null;
4803
+ default: string | null;
4804
+ }
4690
4805
  /** Options for building a transform URL or requesting a transform */
4691
4806
  interface TransformOptions {
4692
4807
  width?: number;
@@ -4745,6 +4860,15 @@ declare class PhotoService extends ServiceModule {
4745
4860
  delete(id: string, options?: RequestOptions): Promise<ApiResponse<{
4746
4861
  deleted: boolean;
4747
4862
  }>>;
4863
+ getPresets(options?: RequestOptions): Promise<ApiResponse<Record<PhotoPreset, {
4864
+ widths: number[];
4865
+ }>>>;
4866
+ getManifest(id: string, params?: {
4867
+ preset?: PhotoPreset;
4868
+ }, options?: RequestOptions): Promise<ApiResponse<PhotoManifest>>;
4869
+ getPublicManifest(id: string, params?: {
4870
+ preset?: PhotoPreset;
4871
+ }, options?: RequestOptions): Promise<ApiResponse<PhotoManifest>>;
4748
4872
  /**
4749
4873
  * Build an absolute URL for the on-demand transform endpoint.
4750
4874
  *
@@ -5005,6 +5129,7 @@ interface MediaManifest {
5005
5129
  file_id: string;
5006
5130
  content_type: string;
5007
5131
  preset: MediaPreset | 'original';
5132
+ ready?: boolean;
5008
5133
  variants: Record<string, string>;
5009
5134
  srcset: string | null;
5010
5135
  default: string | null;
@@ -5071,14 +5196,15 @@ declare class MediaService extends ServiceModule {
5071
5196
  getManifest(fileId: string, options?: MediaManifestOptions, requestOptions?: RequestOptions): Promise<ApiResponse<MediaManifest>>;
5072
5197
  buildAsset(file: FileInfo, options?: MediaManifestOptions & {
5073
5198
  photoId?: string | null;
5074
- }): MediaAsset;
5199
+ }, manifest?: MediaManifest | null): MediaAsset;
5075
5200
  buildManifest(file: FileInfo, options?: MediaManifestOptions): MediaManifest | null;
5076
5201
  private uploadAnonymous;
5077
5202
  private uploadImage;
5078
5203
  private waitForAnonymousReady;
5079
5204
  private fetchInfoBestEffort;
5205
+ private fetchManifest;
5080
5206
  private pollPhotoOptimizationComplete;
5081
- private prewarmManifest;
5207
+ private waitForAnonymousManifest;
5082
5208
  }
5083
5209
 
5084
5210
  type TtsAccessMode = 'owner_private' | 'tenant_shared' | 'public';
@@ -6974,4 +7100,4 @@ declare class ScaleMule {
6974
7100
  getClient(): ScaleMuleClient;
6975
7101
  }
6976
7102
 
6977
- 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, MEDIA_PRESETS, type MediaAsset, type MediaKind, type MediaManifest, type MediaManifestOptions, type MediaPolicy, type MediaPreset, type MediaPresetSpec, MediaService, type MediaUploadEvent, type MediaUploadOptions, type MediaUploadPhase, type MediaUploadResult, 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 TtsSpeechMetadata, type TtsSpeechProfile, 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 };
7103
+ 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, LEGACY_ANONYMOUS_ID_KEYS, 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, MEDIA_PRESETS, type MediaAsset, type MediaKind, type MediaManifest, type MediaManifestOptions, type MediaPolicy, type MediaPreset, type MediaPresetSpec, MediaService, type MediaUploadEvent, type MediaUploadOptions, type MediaUploadPhase, type MediaUploadResult, 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, STORAGE_KEYS, 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 TtsSpeechMetadata, type TtsSpeechProfile, 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, ensureAnonymousId, extractClientContext, generateAnonymousId, generateUploadSessionId, getMeasuredBandwidthMbps, getPartRange, hasMinRoleLevel, readAnonymousId, resolveStrategy, uploadMultipartToS3, uploadSingleToS3, validateIP };
package/dist/index.js CHANGED
@@ -319,6 +319,7 @@ __export(index_exports, {
319
319
  FunctionsService: () => FunctionsService,
320
320
  GraphService: () => GraphService,
321
321
  IdentityService: () => IdentityService,
322
+ LEGACY_ANONYMOUS_ID_KEYS: () => LEGACY_ANONYMOUS_ID_KEYS,
322
323
  LeaderboardService: () => LeaderboardService,
323
324
  ListingsService: () => ListingsService,
324
325
  LoggerService: () => LoggerService,
@@ -333,6 +334,7 @@ __export(index_exports, {
333
334
  QueueService: () => QueueService,
334
335
  RealtimeService: () => RealtimeService,
335
336
  ReferralsService: () => ReferralsService,
337
+ STORAGE_KEYS: () => STORAGE_KEYS,
336
338
  ScaleMule: () => ScaleMule,
337
339
  ScaleMuleClient: () => ScaleMuleClient,
338
340
  SchedulerService: () => SchedulerService,
@@ -358,9 +360,11 @@ __export(index_exports, {
358
360
  default: () => index_default,
359
361
  detectCountryFromE164: () => detectCountryFromE164,
360
362
  detectNetworkClass: () => detectNetworkClass,
363
+ ensureAnonymousId: () => ensureAnonymousId,
361
364
  extractClientContext: () => extractClientContext,
362
365
  findPhoneCountryByCode: () => findPhoneCountryByCode,
363
366
  findPhoneCountryByDialCode: () => findPhoneCountryByDialCode,
367
+ generateAnonymousId: () => generateAnonymousId,
364
368
  generateUploadSessionId: () => generateUploadSessionId,
365
369
  getMeasuredBandwidthMbps: () => getMeasuredBandwidthMbps,
366
370
  getPartRange: () => getPartRange,
@@ -368,6 +372,7 @@ __export(index_exports, {
368
372
  isValidE164Phone: () => isValidE164Phone,
369
373
  normalizeAndValidatePhone: () => normalizeAndValidatePhone,
370
374
  normalizePhoneNumber: () => normalizePhoneNumber,
375
+ readAnonymousId: () => readAnonymousId,
371
376
  resolveStrategy: () => resolveStrategy,
372
377
  uploadMultipartToS3: () => uploadMultipartToS3,
373
378
  uploadSingleToS3: () => uploadSingleToS3,
@@ -451,7 +456,8 @@ function extractClientContext(request) {
451
456
  ip,
452
457
  userAgent: getHeader("user-agent") || void 0,
453
458
  deviceFingerprint: getHeader("x-device-fingerprint") || void 0,
454
- referrer: getHeader("referer") || void 0
459
+ referrer: getHeader("referer") || void 0,
460
+ anonymousId: getHeader("x-anonymous-id") || void 0
455
461
  };
456
462
  }
457
463
  function buildClientContextHeaders(context) {
@@ -464,23 +470,106 @@ function buildClientContextHeaders(context) {
464
470
  if (context.userAgent) headers["X-Client-User-Agent"] = context.userAgent;
465
471
  if (context.deviceFingerprint) headers["X-Client-Device-Fingerprint"] = context.deviceFingerprint;
466
472
  if (context.referrer) headers["X-Client-Referrer"] = context.referrer;
473
+ if (context.anonymousId) headers["x-anonymous-id"] = context.anonymousId;
467
474
  return headers;
468
475
  }
469
476
 
477
+ // src/anonymous-id.ts
478
+ var STORAGE_KEYS = {
479
+ SESSION: "scalemule_session",
480
+ USER_ID: "scalemule_user_id",
481
+ WORKSPACE_ID: "scalemule_workspace_id",
482
+ ANONYMOUS_ID: "scalemule_anonymous_id",
483
+ SESSION_POOL: "scalemule_session_pool",
484
+ ACTIVE_ACCOUNT: "scalemule_active_account",
485
+ KNOWN_ACCOUNTS: "scalemule_known_accounts",
486
+ OFFLINE_QUEUE: "scalemule_offline_queue"
487
+ };
488
+ var LEGACY_ANONYMOUS_ID_KEYS = ["sm_anonymous_id"];
489
+ function generateAnonymousId() {
490
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
491
+ return crypto.randomUUID();
492
+ }
493
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
494
+ const r = Math.random() * 16 | 0;
495
+ const v = c === "x" ? r : r & 3 | 8;
496
+ return v.toString(16);
497
+ });
498
+ }
499
+ async function readAnonymousId(storage) {
500
+ const canonical = await storage.getItem(STORAGE_KEYS.ANONYMOUS_ID);
501
+ if (canonical) return canonical;
502
+ for (const legacyKey of LEGACY_ANONYMOUS_ID_KEYS) {
503
+ const legacy = await storage.getItem(legacyKey);
504
+ if (legacy) return legacy;
505
+ }
506
+ return null;
507
+ }
508
+ var inFlight = /* @__PURE__ */ new WeakMap();
509
+ function ensureAnonymousId(storage) {
510
+ const existing = inFlight.get(storage);
511
+ if (existing) return existing;
512
+ const promise = (async () => {
513
+ try {
514
+ return await resolveAnonymousId(storage);
515
+ } finally {
516
+ inFlight.delete(storage);
517
+ }
518
+ })();
519
+ inFlight.set(storage, promise);
520
+ return promise;
521
+ }
522
+ async function resolveAnonymousId(storage) {
523
+ const canonical = await storage.getItem(STORAGE_KEYS.ANONYMOUS_ID);
524
+ if (canonical) {
525
+ for (const legacyKey of LEGACY_ANONYMOUS_ID_KEYS) {
526
+ const legacy = await storage.getItem(legacyKey);
527
+ if (legacy !== canonical) {
528
+ try {
529
+ await storage.setItem(legacyKey, canonical);
530
+ } catch {
531
+ }
532
+ }
533
+ }
534
+ return canonical;
535
+ }
536
+ for (const legacyKey of LEGACY_ANONYMOUS_ID_KEYS) {
537
+ const legacy = await storage.getItem(legacyKey);
538
+ if (legacy) {
539
+ try {
540
+ await storage.setItem(STORAGE_KEYS.ANONYMOUS_ID, legacy);
541
+ } catch {
542
+ }
543
+ return legacy;
544
+ }
545
+ }
546
+ const fresh = generateAnonymousId();
547
+ try {
548
+ await storage.setItem(STORAGE_KEYS.ANONYMOUS_ID, fresh);
549
+ } catch {
550
+ }
551
+ for (const legacyKey of LEGACY_ANONYMOUS_ID_KEYS) {
552
+ try {
553
+ await storage.setItem(legacyKey, fresh);
554
+ } catch {
555
+ }
556
+ }
557
+ return fresh;
558
+ }
559
+
470
560
  // src/client.ts
471
561
  var SDK_VERSION = "0.0.1";
472
562
  var DEFAULT_TIMEOUT = 3e4;
473
563
  var DEFAULT_MAX_RETRIES = 2;
474
564
  var DEFAULT_BACKOFF_MS = 300;
475
565
  var MAX_BACKOFF_MS = 3e4;
476
- var SESSION_STORAGE_KEY = "scalemule_session";
477
- var USER_ID_STORAGE_KEY = "scalemule_user_id";
478
- var OFFLINE_QUEUE_KEY = "scalemule_offline_queue";
479
- var WORKSPACE_STORAGE_KEY = "scalemule_workspace_id";
480
- var ANONYMOUS_ID_STORAGE_KEY = "scalemule_anonymous_id";
481
- var SESSION_POOL_KEY = "scalemule_session_pool";
482
- var ACTIVE_ACCOUNT_KEY = "scalemule_active_account";
483
- var KNOWN_ACCOUNTS_KEY = "scalemule_known_accounts";
566
+ var SESSION_STORAGE_KEY = STORAGE_KEYS.SESSION;
567
+ var USER_ID_STORAGE_KEY = STORAGE_KEYS.USER_ID;
568
+ var OFFLINE_QUEUE_KEY = STORAGE_KEYS.OFFLINE_QUEUE;
569
+ var WORKSPACE_STORAGE_KEY = STORAGE_KEYS.WORKSPACE_ID;
570
+ var SESSION_POOL_KEY = STORAGE_KEYS.SESSION_POOL;
571
+ var ACTIVE_ACCOUNT_KEY = STORAGE_KEYS.ACTIVE_ACCOUNT;
572
+ var KNOWN_ACCOUNTS_KEY = STORAGE_KEYS.KNOWN_ACCOUNTS;
484
573
  var GATEWAY_URLS = {
485
574
  dev: "https://api-dev.scalemule.com",
486
575
  prod: "https://api.scalemule.com"
@@ -723,6 +812,11 @@ var ScaleMuleClient = class {
723
812
  this.offlineQueue = null;
724
813
  this.workspaceId = null;
725
814
  this.anonymousId = null;
815
+ // Per-client single-flight for the lazy mint. The shared helper has its
816
+ // own WeakMap-keyed guard against concurrent callers; this field caches
817
+ // the resolved value at the instance level so subsequent calls (including
818
+ // those during request bursts) don't even await the helper.
819
+ this.anonymousIdPromise = null;
726
820
  this.sessionPool = /* @__PURE__ */ new Map();
727
821
  this.knownAccounts = /* @__PURE__ */ new Map();
728
822
  this.refreshPromise = null;
@@ -758,12 +852,7 @@ var ScaleMuleClient = class {
758
852
  if (userId) this.userId = userId;
759
853
  const wsId = await this.storage.getItem(WORKSPACE_STORAGE_KEY);
760
854
  if (wsId) this.workspaceId = wsId;
761
- let anonId = await this.storage.getItem(ANONYMOUS_ID_STORAGE_KEY);
762
- if (!anonId) {
763
- anonId = crypto.randomUUID();
764
- await this.storage.setItem(ANONYMOUS_ID_STORAGE_KEY, anonId);
765
- }
766
- this.anonymousId = anonId;
855
+ await this.ensureAnonymousId();
767
856
  if (this.multiSessionEnabled) {
768
857
  const poolJson = await this.storage.getItem(SESSION_POOL_KEY);
769
858
  if (poolJson) {
@@ -815,7 +904,7 @@ var ScaleMuleClient = class {
815
904
  "[ScaleMule] Initialized, session:",
816
905
  !!this.sessionToken,
817
906
  "anonymousId:",
818
- anonId,
907
+ this.anonymousId,
819
908
  "poolSize:",
820
909
  this.sessionPool.size,
821
910
  "knownAccounts:",
@@ -869,9 +958,38 @@ var ScaleMuleClient = class {
869
958
  isAuthenticated() {
870
959
  return this.sessionToken !== null;
871
960
  }
961
+ /**
962
+ * Sync accessor for the cached anonymous ID. Returns `null` until either
963
+ * `initialize()` has run or `ensureAnonymousId()` has been awaited at
964
+ * least once. Use `ensureAnonymousId()` if you need a guaranteed value.
965
+ */
872
966
  getAnonymousId() {
873
967
  return this.anonymousId;
874
968
  }
969
+ /**
970
+ * Lazy-mint or cache-then-return the anonymous ID.
971
+ *
972
+ * Always returns a usable string. Callers that need to attach the
973
+ * `x-anonymous-id` header before `initialize()` has completed (rare —
974
+ * usually only the very first unauthenticated request from a freshly
975
+ * constructed client) should `await` this rather than relying on
976
+ * `getAnonymousId()`.
977
+ *
978
+ * Concurrent callers receive the same in-flight promise — no risk of
979
+ * two simultaneous first requests minting two distinct IDs.
980
+ */
981
+ async ensureAnonymousId() {
982
+ if (this.anonymousId) return this.anonymousId;
983
+ if (!this.anonymousIdPromise) {
984
+ this.anonymousIdPromise = ensureAnonymousId(this.storage).then((id) => {
985
+ this.anonymousId = id;
986
+ return id;
987
+ }).finally(() => {
988
+ this.anonymousIdPromise = null;
989
+ });
990
+ }
991
+ return this.anonymousIdPromise;
992
+ }
875
993
  isMultiSessionEnabled() {
876
994
  return this.multiSessionEnabled;
877
995
  }
@@ -1047,8 +1165,16 @@ var ScaleMuleClient = class {
1047
1165
  if (this.workspaceId) {
1048
1166
  headers["x-sm-workspace-id"] = this.workspaceId;
1049
1167
  }
1050
- if (!this.sessionToken && this.anonymousId) {
1051
- headers["x-anonymous-id"] = this.anonymousId;
1168
+ if (!init.skipAuth && !this.sessionToken) {
1169
+ if (!this.anonymousId) {
1170
+ try {
1171
+ await this.ensureAnonymousId();
1172
+ } catch {
1173
+ }
1174
+ }
1175
+ if (this.anonymousId) {
1176
+ headers["x-anonymous-id"] = this.anonymousId;
1177
+ }
1052
1178
  }
1053
1179
  if (attempt > 0 && (method === "POST" || method === "PUT" || method === "PATCH")) {
1054
1180
  if (!idempotencyKey) {
@@ -1525,7 +1651,7 @@ function asString(parent, key) {
1525
1651
  return typeof value === "string" ? value : void 0;
1526
1652
  }
1527
1653
 
1528
- // node_modules/@scalemule/ui/dist/phone/index.mjs
1654
+ // node_modules/.pnpm/@scalemule+ui@0.0.4/node_modules/@scalemule/ui/dist/phone/index.mjs
1529
1655
  var PHONE_COUNTRIES = [
1530
1656
  { code: "US", name: "United States", dialCode: "+1" },
1531
1657
  { code: "CA", name: "Canada", dialCode: "+1" },
@@ -6566,6 +6692,15 @@ var PhotoService = class extends ServiceModule {
6566
6692
  async delete(id, options) {
6567
6693
  return this.del(`/${id}`, options);
6568
6694
  }
6695
+ async getPresets(options) {
6696
+ return this._get("/presets", options);
6697
+ }
6698
+ async getManifest(id, params, options) {
6699
+ return this._get(this.withQuery(`/${id}/manifest`, params), options);
6700
+ }
6701
+ async getPublicManifest(id, params, options) {
6702
+ return this._get(this.withQuery(`/public/${id}/manifest`, params), options);
6703
+ }
6569
6704
  /**
6570
6705
  * Build an absolute URL for the on-demand transform endpoint.
6571
6706
  *
@@ -7025,13 +7160,14 @@ var MediaService = class extends ServiceModule {
7025
7160
  return this.get(fileId, void 0, options);
7026
7161
  }
7027
7162
  async getManifest(fileId, options, requestOptions) {
7028
- const asset = await this.get(fileId, options, requestOptions);
7029
- if (asset.error || !asset.data) {
7030
- return { data: null, error: asset.error };
7163
+ const file = await this.storage.getInfo(fileId, requestOptions);
7164
+ if (file.error || !file.data) {
7165
+ return { data: null, error: file.error };
7031
7166
  }
7032
- return { data: asset.data.manifest, error: null };
7167
+ const manifest = await this.fetchManifest(file.data, options, requestOptions);
7168
+ return { data: manifest, error: null };
7033
7169
  }
7034
- buildAsset(file, options) {
7170
+ buildAsset(file, options, manifest) {
7035
7171
  const visibility = resolveFileVisibility(file);
7036
7172
  const photoId = options?.photoId ?? null;
7037
7173
  const originalUrl = visibility === "anonymous_visible" ? file.cdn_url ?? file.url ?? null : file.url ?? file.cdn_url ?? null;
@@ -7048,7 +7184,7 @@ var MediaService = class extends ServiceModule {
7048
7184
  created_at: file.created_at,
7049
7185
  original_url: originalUrl,
7050
7186
  cdn_url: file.cdn_url ?? null,
7051
- manifest: this.buildManifest(file, options)
7187
+ manifest: manifest ?? this.buildManifest(file, options)
7052
7188
  };
7053
7189
  }
7054
7190
  buildManifest(file, options) {
@@ -7102,19 +7238,27 @@ var MediaService = class extends ServiceModule {
7102
7238
  cdn_url: ready.cdnUrl ?? result.data.cdn_url,
7103
7239
  scan_status: ready.scanStatus
7104
7240
  };
7105
- const manifest = this.buildManifest(fileInfo, {
7241
+ let manifest = this.buildManifest(fileInfo, {
7106
7242
  preset: options?.preset,
7107
7243
  customWidths: options?.customWidths
7108
7244
  });
7109
- if (kind === "image" && fileInfo.content_type !== "image/svg+xml" && options?.prewarm !== false) {
7245
+ if (kind === "image" && fileInfo.content_type !== "image/svg+xml" && options?.preset !== "custom") {
7110
7246
  emit("optimizing", 100, result.data.id);
7111
- await this.prewarmManifest(manifest, options?.signal);
7247
+ const persistedManifest = await this.waitForAnonymousManifest(fileInfo.id, options, requestOptions, emit);
7248
+ if (persistedManifest.error) {
7249
+ return { data: null, error: persistedManifest.error };
7250
+ }
7251
+ manifest = persistedManifest.manifest ?? manifest;
7112
7252
  }
7113
- const asset = this.buildAsset(fileInfo, {
7114
- photoId: null,
7115
- preset: options?.preset,
7116
- customWidths: options?.customWidths
7117
- });
7253
+ const asset = this.buildAsset(
7254
+ fileInfo,
7255
+ {
7256
+ photoId: null,
7257
+ preset: options?.preset,
7258
+ customWidths: options?.customWidths
7259
+ },
7260
+ manifest
7261
+ );
7118
7262
  emit("ready", 100, result.data.id);
7119
7263
  return {
7120
7264
  data: {
@@ -7250,6 +7394,25 @@ var MediaService = class extends ServiceModule {
7250
7394
  const result = await this.storage.getInfo(fileId, requestOptions);
7251
7395
  return result.error || !result.data ? null : result.data;
7252
7396
  }
7397
+ async fetchManifest(file, options, requestOptions) {
7398
+ const kind = detectKind(file.content_type);
7399
+ const visibility = resolveFileVisibility(file);
7400
+ if (kind !== "image" || file.content_type === "image/svg+xml") {
7401
+ return this.buildManifest(file, options);
7402
+ }
7403
+ if (visibility !== "anonymous_visible" || options?.preset === "custom") {
7404
+ return this.buildManifest(file, options);
7405
+ }
7406
+ const persisted = await this.photo.getPublicManifest(
7407
+ file.id,
7408
+ { preset: options?.preset ?? "inline" },
7409
+ requestOptions
7410
+ );
7411
+ if (persisted.error || !persisted.data) {
7412
+ return this.buildManifest(file, options);
7413
+ }
7414
+ return persisted.data;
7415
+ }
7253
7416
  async pollPhotoOptimizationComplete(photoId, requestOptions) {
7254
7417
  for (let attempt = 0; attempt < 40; attempt++) {
7255
7418
  const result = await this.photo.get(photoId, requestOptions);
@@ -7261,30 +7424,31 @@ var MediaService = class extends ServiceModule {
7261
7424
  }
7262
7425
  return null;
7263
7426
  }
7264
- async prewarmManifest(manifest, signal) {
7265
- if (!manifest || manifest.preset === "original") {
7266
- return;
7427
+ async waitForAnonymousManifest(fileId, options, requestOptions, emit) {
7428
+ const preset = options?.preset ?? "inline";
7429
+ const delays = [500, 1e3, 1500, 2e3, 2500, 3e3];
7430
+ for (let attempt = 0; attempt < 30; attempt++) {
7431
+ if (options?.signal?.aborted) {
7432
+ return {
7433
+ manifest: null,
7434
+ error: { code: "aborted", message: "Upload aborted", status: 0 }
7435
+ };
7436
+ }
7437
+ const manifest = await this.photo.getPublicManifest(fileId, { preset }, requestOptions);
7438
+ if (!manifest.error && manifest.data && manifest.data.ready) {
7439
+ return { manifest: manifest.data, error: null };
7440
+ }
7441
+ emit("optimizing", Math.min(99, 15 + attempt * 3), fileId);
7442
+ await sleep4(delays[Math.min(attempt, delays.length - 1)] ?? 3e3);
7267
7443
  }
7268
- const urls = Object.values(manifest.variants);
7269
- await Promise.all(
7270
- urls.map(async (url) => {
7271
- try {
7272
- const response = await fetch(url, {
7273
- method: "GET",
7274
- signal,
7275
- headers: {
7276
- Accept: "image/avif,image/webp,image/*,*/*;q=0.8"
7277
- }
7278
- });
7279
- if (!response.ok) {
7280
- throw new Error(`Prewarm failed with HTTP ${response.status}`);
7281
- }
7282
- await response.arrayBuffer();
7283
- } catch (error) {
7284
- console.warn("[scalemule-sdk] media prewarm failed", url, error);
7285
- }
7286
- })
7287
- );
7444
+ return {
7445
+ manifest: null,
7446
+ error: {
7447
+ code: "manifest_pending",
7448
+ message: "Photo variants are still being generated. Re-fetch the public manifest once ready flips true.",
7449
+ status: 202
7450
+ }
7451
+ };
7288
7452
  }
7289
7453
  };
7290
7454
  function detectKind(contentType) {
@@ -8485,6 +8649,7 @@ var index_default = ScaleMule;
8485
8649
  FunctionsService,
8486
8650
  GraphService,
8487
8651
  IdentityService,
8652
+ LEGACY_ANONYMOUS_ID_KEYS,
8488
8653
  LeaderboardService,
8489
8654
  ListingsService,
8490
8655
  LoggerService,
@@ -8499,6 +8664,7 @@ var index_default = ScaleMule;
8499
8664
  QueueService,
8500
8665
  RealtimeService,
8501
8666
  ReferralsService,
8667
+ STORAGE_KEYS,
8502
8668
  ScaleMule,
8503
8669
  ScaleMuleClient,
8504
8670
  SchedulerService,
@@ -8523,9 +8689,11 @@ var index_default = ScaleMule;
8523
8689
  createUploadPlan,
8524
8690
  detectCountryFromE164,
8525
8691
  detectNetworkClass,
8692
+ ensureAnonymousId,
8526
8693
  extractClientContext,
8527
8694
  findPhoneCountryByCode,
8528
8695
  findPhoneCountryByDialCode,
8696
+ generateAnonymousId,
8529
8697
  generateUploadSessionId,
8530
8698
  getMeasuredBandwidthMbps,
8531
8699
  getPartRange,
@@ -8533,6 +8701,7 @@ var index_default = ScaleMule;
8533
8701
  isValidE164Phone,
8534
8702
  normalizeAndValidatePhone,
8535
8703
  normalizePhoneNumber,
8704
+ readAnonymousId,
8536
8705
  resolveStrategy,
8537
8706
  uploadMultipartToS3,
8538
8707
  uploadSingleToS3,
package/dist/index.mjs CHANGED
@@ -78,7 +78,8 @@ function extractClientContext(request) {
78
78
  ip,
79
79
  userAgent: getHeader("user-agent") || void 0,
80
80
  deviceFingerprint: getHeader("x-device-fingerprint") || void 0,
81
- referrer: getHeader("referer") || void 0
81
+ referrer: getHeader("referer") || void 0,
82
+ anonymousId: getHeader("x-anonymous-id") || void 0
82
83
  };
83
84
  }
84
85
  function buildClientContextHeaders(context) {
@@ -91,23 +92,106 @@ function buildClientContextHeaders(context) {
91
92
  if (context.userAgent) headers["X-Client-User-Agent"] = context.userAgent;
92
93
  if (context.deviceFingerprint) headers["X-Client-Device-Fingerprint"] = context.deviceFingerprint;
93
94
  if (context.referrer) headers["X-Client-Referrer"] = context.referrer;
95
+ if (context.anonymousId) headers["x-anonymous-id"] = context.anonymousId;
94
96
  return headers;
95
97
  }
96
98
 
99
+ // src/anonymous-id.ts
100
+ var STORAGE_KEYS = {
101
+ SESSION: "scalemule_session",
102
+ USER_ID: "scalemule_user_id",
103
+ WORKSPACE_ID: "scalemule_workspace_id",
104
+ ANONYMOUS_ID: "scalemule_anonymous_id",
105
+ SESSION_POOL: "scalemule_session_pool",
106
+ ACTIVE_ACCOUNT: "scalemule_active_account",
107
+ KNOWN_ACCOUNTS: "scalemule_known_accounts",
108
+ OFFLINE_QUEUE: "scalemule_offline_queue"
109
+ };
110
+ var LEGACY_ANONYMOUS_ID_KEYS = ["sm_anonymous_id"];
111
+ function generateAnonymousId() {
112
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
113
+ return crypto.randomUUID();
114
+ }
115
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
116
+ const r = Math.random() * 16 | 0;
117
+ const v = c === "x" ? r : r & 3 | 8;
118
+ return v.toString(16);
119
+ });
120
+ }
121
+ async function readAnonymousId(storage) {
122
+ const canonical = await storage.getItem(STORAGE_KEYS.ANONYMOUS_ID);
123
+ if (canonical) return canonical;
124
+ for (const legacyKey of LEGACY_ANONYMOUS_ID_KEYS) {
125
+ const legacy = await storage.getItem(legacyKey);
126
+ if (legacy) return legacy;
127
+ }
128
+ return null;
129
+ }
130
+ var inFlight = /* @__PURE__ */ new WeakMap();
131
+ function ensureAnonymousId(storage) {
132
+ const existing = inFlight.get(storage);
133
+ if (existing) return existing;
134
+ const promise = (async () => {
135
+ try {
136
+ return await resolveAnonymousId(storage);
137
+ } finally {
138
+ inFlight.delete(storage);
139
+ }
140
+ })();
141
+ inFlight.set(storage, promise);
142
+ return promise;
143
+ }
144
+ async function resolveAnonymousId(storage) {
145
+ const canonical = await storage.getItem(STORAGE_KEYS.ANONYMOUS_ID);
146
+ if (canonical) {
147
+ for (const legacyKey of LEGACY_ANONYMOUS_ID_KEYS) {
148
+ const legacy = await storage.getItem(legacyKey);
149
+ if (legacy !== canonical) {
150
+ try {
151
+ await storage.setItem(legacyKey, canonical);
152
+ } catch {
153
+ }
154
+ }
155
+ }
156
+ return canonical;
157
+ }
158
+ for (const legacyKey of LEGACY_ANONYMOUS_ID_KEYS) {
159
+ const legacy = await storage.getItem(legacyKey);
160
+ if (legacy) {
161
+ try {
162
+ await storage.setItem(STORAGE_KEYS.ANONYMOUS_ID, legacy);
163
+ } catch {
164
+ }
165
+ return legacy;
166
+ }
167
+ }
168
+ const fresh = generateAnonymousId();
169
+ try {
170
+ await storage.setItem(STORAGE_KEYS.ANONYMOUS_ID, fresh);
171
+ } catch {
172
+ }
173
+ for (const legacyKey of LEGACY_ANONYMOUS_ID_KEYS) {
174
+ try {
175
+ await storage.setItem(legacyKey, fresh);
176
+ } catch {
177
+ }
178
+ }
179
+ return fresh;
180
+ }
181
+
97
182
  // src/client.ts
98
183
  var SDK_VERSION = "0.0.1";
99
184
  var DEFAULT_TIMEOUT = 3e4;
100
185
  var DEFAULT_MAX_RETRIES = 2;
101
186
  var DEFAULT_BACKOFF_MS = 300;
102
187
  var MAX_BACKOFF_MS = 3e4;
103
- var SESSION_STORAGE_KEY = "scalemule_session";
104
- var USER_ID_STORAGE_KEY = "scalemule_user_id";
105
- var OFFLINE_QUEUE_KEY = "scalemule_offline_queue";
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";
110
- var KNOWN_ACCOUNTS_KEY = "scalemule_known_accounts";
188
+ var SESSION_STORAGE_KEY = STORAGE_KEYS.SESSION;
189
+ var USER_ID_STORAGE_KEY = STORAGE_KEYS.USER_ID;
190
+ var OFFLINE_QUEUE_KEY = STORAGE_KEYS.OFFLINE_QUEUE;
191
+ var WORKSPACE_STORAGE_KEY = STORAGE_KEYS.WORKSPACE_ID;
192
+ var SESSION_POOL_KEY = STORAGE_KEYS.SESSION_POOL;
193
+ var ACTIVE_ACCOUNT_KEY = STORAGE_KEYS.ACTIVE_ACCOUNT;
194
+ var KNOWN_ACCOUNTS_KEY = STORAGE_KEYS.KNOWN_ACCOUNTS;
111
195
  var GATEWAY_URLS = {
112
196
  dev: "https://api-dev.scalemule.com",
113
197
  prod: "https://api.scalemule.com"
@@ -350,6 +434,11 @@ var ScaleMuleClient = class {
350
434
  this.offlineQueue = null;
351
435
  this.workspaceId = null;
352
436
  this.anonymousId = null;
437
+ // Per-client single-flight for the lazy mint. The shared helper has its
438
+ // own WeakMap-keyed guard against concurrent callers; this field caches
439
+ // the resolved value at the instance level so subsequent calls (including
440
+ // those during request bursts) don't even await the helper.
441
+ this.anonymousIdPromise = null;
353
442
  this.sessionPool = /* @__PURE__ */ new Map();
354
443
  this.knownAccounts = /* @__PURE__ */ new Map();
355
444
  this.refreshPromise = null;
@@ -385,12 +474,7 @@ var ScaleMuleClient = class {
385
474
  if (userId) this.userId = userId;
386
475
  const wsId = await this.storage.getItem(WORKSPACE_STORAGE_KEY);
387
476
  if (wsId) this.workspaceId = wsId;
388
- let anonId = await this.storage.getItem(ANONYMOUS_ID_STORAGE_KEY);
389
- if (!anonId) {
390
- anonId = crypto.randomUUID();
391
- await this.storage.setItem(ANONYMOUS_ID_STORAGE_KEY, anonId);
392
- }
393
- this.anonymousId = anonId;
477
+ await this.ensureAnonymousId();
394
478
  if (this.multiSessionEnabled) {
395
479
  const poolJson = await this.storage.getItem(SESSION_POOL_KEY);
396
480
  if (poolJson) {
@@ -442,7 +526,7 @@ var ScaleMuleClient = class {
442
526
  "[ScaleMule] Initialized, session:",
443
527
  !!this.sessionToken,
444
528
  "anonymousId:",
445
- anonId,
529
+ this.anonymousId,
446
530
  "poolSize:",
447
531
  this.sessionPool.size,
448
532
  "knownAccounts:",
@@ -496,9 +580,38 @@ var ScaleMuleClient = class {
496
580
  isAuthenticated() {
497
581
  return this.sessionToken !== null;
498
582
  }
583
+ /**
584
+ * Sync accessor for the cached anonymous ID. Returns `null` until either
585
+ * `initialize()` has run or `ensureAnonymousId()` has been awaited at
586
+ * least once. Use `ensureAnonymousId()` if you need a guaranteed value.
587
+ */
499
588
  getAnonymousId() {
500
589
  return this.anonymousId;
501
590
  }
591
+ /**
592
+ * Lazy-mint or cache-then-return the anonymous ID.
593
+ *
594
+ * Always returns a usable string. Callers that need to attach the
595
+ * `x-anonymous-id` header before `initialize()` has completed (rare —
596
+ * usually only the very first unauthenticated request from a freshly
597
+ * constructed client) should `await` this rather than relying on
598
+ * `getAnonymousId()`.
599
+ *
600
+ * Concurrent callers receive the same in-flight promise — no risk of
601
+ * two simultaneous first requests minting two distinct IDs.
602
+ */
603
+ async ensureAnonymousId() {
604
+ if (this.anonymousId) return this.anonymousId;
605
+ if (!this.anonymousIdPromise) {
606
+ this.anonymousIdPromise = ensureAnonymousId(this.storage).then((id) => {
607
+ this.anonymousId = id;
608
+ return id;
609
+ }).finally(() => {
610
+ this.anonymousIdPromise = null;
611
+ });
612
+ }
613
+ return this.anonymousIdPromise;
614
+ }
502
615
  isMultiSessionEnabled() {
503
616
  return this.multiSessionEnabled;
504
617
  }
@@ -674,8 +787,16 @@ var ScaleMuleClient = class {
674
787
  if (this.workspaceId) {
675
788
  headers["x-sm-workspace-id"] = this.workspaceId;
676
789
  }
677
- if (!this.sessionToken && this.anonymousId) {
678
- headers["x-anonymous-id"] = this.anonymousId;
790
+ if (!init.skipAuth && !this.sessionToken) {
791
+ if (!this.anonymousId) {
792
+ try {
793
+ await this.ensureAnonymousId();
794
+ } catch {
795
+ }
796
+ }
797
+ if (this.anonymousId) {
798
+ headers["x-anonymous-id"] = this.anonymousId;
799
+ }
679
800
  }
680
801
  if (attempt > 0 && (method === "POST" || method === "PUT" || method === "PATCH")) {
681
802
  if (!idempotencyKey) {
@@ -1152,7 +1273,7 @@ function asString(parent, key) {
1152
1273
  return typeof value === "string" ? value : void 0;
1153
1274
  }
1154
1275
 
1155
- // node_modules/@scalemule/ui/dist/phone/index.mjs
1276
+ // node_modules/.pnpm/@scalemule+ui@0.0.4/node_modules/@scalemule/ui/dist/phone/index.mjs
1156
1277
  var PHONE_COUNTRIES = [
1157
1278
  { code: "US", name: "United States", dialCode: "+1" },
1158
1279
  { code: "CA", name: "Canada", dialCode: "+1" },
@@ -6190,6 +6311,15 @@ var PhotoService = class extends ServiceModule {
6190
6311
  async delete(id, options) {
6191
6312
  return this.del(`/${id}`, options);
6192
6313
  }
6314
+ async getPresets(options) {
6315
+ return this._get("/presets", options);
6316
+ }
6317
+ async getManifest(id, params, options) {
6318
+ return this._get(this.withQuery(`/${id}/manifest`, params), options);
6319
+ }
6320
+ async getPublicManifest(id, params, options) {
6321
+ return this._get(this.withQuery(`/public/${id}/manifest`, params), options);
6322
+ }
6193
6323
  /**
6194
6324
  * Build an absolute URL for the on-demand transform endpoint.
6195
6325
  *
@@ -6649,13 +6779,14 @@ var MediaService = class extends ServiceModule {
6649
6779
  return this.get(fileId, void 0, options);
6650
6780
  }
6651
6781
  async getManifest(fileId, options, requestOptions) {
6652
- const asset = await this.get(fileId, options, requestOptions);
6653
- if (asset.error || !asset.data) {
6654
- return { data: null, error: asset.error };
6782
+ const file = await this.storage.getInfo(fileId, requestOptions);
6783
+ if (file.error || !file.data) {
6784
+ return { data: null, error: file.error };
6655
6785
  }
6656
- return { data: asset.data.manifest, error: null };
6786
+ const manifest = await this.fetchManifest(file.data, options, requestOptions);
6787
+ return { data: manifest, error: null };
6657
6788
  }
6658
- buildAsset(file, options) {
6789
+ buildAsset(file, options, manifest) {
6659
6790
  const visibility = resolveFileVisibility(file);
6660
6791
  const photoId = options?.photoId ?? null;
6661
6792
  const originalUrl = visibility === "anonymous_visible" ? file.cdn_url ?? file.url ?? null : file.url ?? file.cdn_url ?? null;
@@ -6672,7 +6803,7 @@ var MediaService = class extends ServiceModule {
6672
6803
  created_at: file.created_at,
6673
6804
  original_url: originalUrl,
6674
6805
  cdn_url: file.cdn_url ?? null,
6675
- manifest: this.buildManifest(file, options)
6806
+ manifest: manifest ?? this.buildManifest(file, options)
6676
6807
  };
6677
6808
  }
6678
6809
  buildManifest(file, options) {
@@ -6726,19 +6857,27 @@ var MediaService = class extends ServiceModule {
6726
6857
  cdn_url: ready.cdnUrl ?? result.data.cdn_url,
6727
6858
  scan_status: ready.scanStatus
6728
6859
  };
6729
- const manifest = this.buildManifest(fileInfo, {
6860
+ let manifest = this.buildManifest(fileInfo, {
6730
6861
  preset: options?.preset,
6731
6862
  customWidths: options?.customWidths
6732
6863
  });
6733
- if (kind === "image" && fileInfo.content_type !== "image/svg+xml" && options?.prewarm !== false) {
6864
+ if (kind === "image" && fileInfo.content_type !== "image/svg+xml" && options?.preset !== "custom") {
6734
6865
  emit("optimizing", 100, result.data.id);
6735
- await this.prewarmManifest(manifest, options?.signal);
6866
+ const persistedManifest = await this.waitForAnonymousManifest(fileInfo.id, options, requestOptions, emit);
6867
+ if (persistedManifest.error) {
6868
+ return { data: null, error: persistedManifest.error };
6869
+ }
6870
+ manifest = persistedManifest.manifest ?? manifest;
6736
6871
  }
6737
- const asset = this.buildAsset(fileInfo, {
6738
- photoId: null,
6739
- preset: options?.preset,
6740
- customWidths: options?.customWidths
6741
- });
6872
+ const asset = this.buildAsset(
6873
+ fileInfo,
6874
+ {
6875
+ photoId: null,
6876
+ preset: options?.preset,
6877
+ customWidths: options?.customWidths
6878
+ },
6879
+ manifest
6880
+ );
6742
6881
  emit("ready", 100, result.data.id);
6743
6882
  return {
6744
6883
  data: {
@@ -6874,6 +7013,25 @@ var MediaService = class extends ServiceModule {
6874
7013
  const result = await this.storage.getInfo(fileId, requestOptions);
6875
7014
  return result.error || !result.data ? null : result.data;
6876
7015
  }
7016
+ async fetchManifest(file, options, requestOptions) {
7017
+ const kind = detectKind(file.content_type);
7018
+ const visibility = resolveFileVisibility(file);
7019
+ if (kind !== "image" || file.content_type === "image/svg+xml") {
7020
+ return this.buildManifest(file, options);
7021
+ }
7022
+ if (visibility !== "anonymous_visible" || options?.preset === "custom") {
7023
+ return this.buildManifest(file, options);
7024
+ }
7025
+ const persisted = await this.photo.getPublicManifest(
7026
+ file.id,
7027
+ { preset: options?.preset ?? "inline" },
7028
+ requestOptions
7029
+ );
7030
+ if (persisted.error || !persisted.data) {
7031
+ return this.buildManifest(file, options);
7032
+ }
7033
+ return persisted.data;
7034
+ }
6877
7035
  async pollPhotoOptimizationComplete(photoId, requestOptions) {
6878
7036
  for (let attempt = 0; attempt < 40; attempt++) {
6879
7037
  const result = await this.photo.get(photoId, requestOptions);
@@ -6885,30 +7043,31 @@ var MediaService = class extends ServiceModule {
6885
7043
  }
6886
7044
  return null;
6887
7045
  }
6888
- async prewarmManifest(manifest, signal) {
6889
- if (!manifest || manifest.preset === "original") {
6890
- return;
7046
+ async waitForAnonymousManifest(fileId, options, requestOptions, emit) {
7047
+ const preset = options?.preset ?? "inline";
7048
+ const delays = [500, 1e3, 1500, 2e3, 2500, 3e3];
7049
+ for (let attempt = 0; attempt < 30; attempt++) {
7050
+ if (options?.signal?.aborted) {
7051
+ return {
7052
+ manifest: null,
7053
+ error: { code: "aborted", message: "Upload aborted", status: 0 }
7054
+ };
7055
+ }
7056
+ const manifest = await this.photo.getPublicManifest(fileId, { preset }, requestOptions);
7057
+ if (!manifest.error && manifest.data && manifest.data.ready) {
7058
+ return { manifest: manifest.data, error: null };
7059
+ }
7060
+ emit("optimizing", Math.min(99, 15 + attempt * 3), fileId);
7061
+ await sleep4(delays[Math.min(attempt, delays.length - 1)] ?? 3e3);
6891
7062
  }
6892
- const urls = Object.values(manifest.variants);
6893
- await Promise.all(
6894
- urls.map(async (url) => {
6895
- try {
6896
- const response = await fetch(url, {
6897
- method: "GET",
6898
- signal,
6899
- headers: {
6900
- Accept: "image/avif,image/webp,image/*,*/*;q=0.8"
6901
- }
6902
- });
6903
- if (!response.ok) {
6904
- throw new Error(`Prewarm failed with HTTP ${response.status}`);
6905
- }
6906
- await response.arrayBuffer();
6907
- } catch (error) {
6908
- console.warn("[scalemule-sdk] media prewarm failed", url, error);
6909
- }
6910
- })
6911
- );
7063
+ return {
7064
+ manifest: null,
7065
+ error: {
7066
+ code: "manifest_pending",
7067
+ message: "Photo variants are still being generated. Re-fetch the public manifest once ready flips true.",
7068
+ status: 202
7069
+ }
7070
+ };
6912
7071
  }
6913
7072
  };
6914
7073
  function detectKind(contentType) {
@@ -8108,6 +8267,7 @@ export {
8108
8267
  FunctionsService,
8109
8268
  GraphService,
8110
8269
  IdentityService,
8270
+ LEGACY_ANONYMOUS_ID_KEYS,
8111
8271
  LeaderboardService,
8112
8272
  ListingsService,
8113
8273
  LoggerService,
@@ -8122,6 +8282,7 @@ export {
8122
8282
  QueueService,
8123
8283
  RealtimeService,
8124
8284
  ReferralsService,
8285
+ STORAGE_KEYS,
8125
8286
  ScaleMule,
8126
8287
  ScaleMuleClient,
8127
8288
  SchedulerService,
@@ -8147,9 +8308,11 @@ export {
8147
8308
  index_default as default,
8148
8309
  detectCountryFromE164,
8149
8310
  detectNetworkClass,
8311
+ ensureAnonymousId,
8150
8312
  extractClientContext,
8151
8313
  findPhoneCountryByCode,
8152
8314
  findPhoneCountryByDialCode,
8315
+ generateAnonymousId,
8153
8316
  generateUploadSessionId,
8154
8317
  getMeasuredBandwidthMbps,
8155
8318
  getPartRange,
@@ -8157,6 +8320,7 @@ export {
8157
8320
  isValidE164Phone,
8158
8321
  normalizeAndValidatePhone,
8159
8322
  normalizePhoneNumber,
8323
+ readAnonymousId,
8160
8324
  resolveStrategy,
8161
8325
  uploadMultipartToS3,
8162
8326
  uploadSingleToS3,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalemule/sdk",
3
- "version": "0.0.56",
3
+ "version": "0.0.58",
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",
@@ -76,6 +76,7 @@
76
76
  "devDependencies": {
77
77
  "@scalemule/ui": ">=0.0.1",
78
78
  "@types/node": "^20.10.0",
79
+ "@types/semver": "7.7.1",
79
80
  "@typescript-eslint/eslint-plugin": "^6.13.0",
80
81
  "@typescript-eslint/parser": "^6.13.0",
81
82
  "@vitest/coverage-v8": "^1.0.0",