@scalemule/sdk 0.0.76 → 0.0.77

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.
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Experiments (A/B tests) on top of scalemule-flags variants.
3
+ *
4
+ * Convention shared by every ScaleMule client and the analytics service:
5
+ * - An experiment is a flag with two or more weighted variants. Evaluating it with a stable
6
+ * identifier (`session_id` or `user_id`) yields the visitor's `variant_key`.
7
+ * - Every analytics event sent while a visitor is in an experiment carries
8
+ * `properties.experiments = { "<flag_key>": "<variant_key>" }`.
9
+ * - `experiment_exposed` is tracked once per visitor and flag when the variant is first shown.
10
+ * - The analytics service reports per-variant results from those properties
11
+ * (`GET /v1/analytics/admin/experiments/{flag_key}`), so any tracked event can be the goal.
12
+ */
13
+ declare const EXPERIMENTS_PROPERTY = "experiments";
14
+ declare const EXPERIMENT_EXPOSED_EVENT = "experiment_exposed";
15
+ declare const MAX_EXPERIMENTS_PER_EVENT = 10;
16
+ /** Active assignments for one visitor: flag key → variant key. */
17
+ type ExperimentAssignments = Record<string, string>;
18
+ interface ExperimentAssignment<T = unknown> {
19
+ flag_key: string;
20
+ /** The variant the visitor is in, or null when the flag is off, missing or has no variants. */
21
+ variant: string | null;
22
+ /** The raw flag evaluation this assignment came from, when one was made. */
23
+ evaluation?: ExperimentEvaluationLike<T> | null;
24
+ }
25
+ /** The subset of a flag evaluation the experiment helpers read. */
26
+ interface ExperimentEvaluationLike<T = unknown> {
27
+ flag_key?: string;
28
+ value?: T;
29
+ reason?: string;
30
+ variant_key?: string | null;
31
+ }
32
+ declare function isExperimentKey(value: unknown): value is string;
33
+ declare function isVariantKey(value: unknown): value is string;
34
+ /**
35
+ * The variant a flag evaluation puts the visitor in.
36
+ * Weighted variants report `variant_key`; a rule or default that serves a string value counts as
37
+ * that variant (so a rule can pin everyone to "modern" and the report still groups them).
38
+ */
39
+ declare function experimentVariant(evaluation: ExperimentEvaluationLike | null | undefined): string | null;
40
+ /** Keeps only well-formed `{ flag_key: variant_key }` pairs, at most MAX_EXPERIMENTS_PER_EVENT. */
41
+ declare function normalizeExperiments(input: unknown): ExperimentAssignments;
42
+ /** Merges the visitor's assignments into event properties under `experiments`. Empty assignments add nothing. */
43
+ declare function withExperiments(properties: Record<string, unknown> | undefined, experiments: ExperimentAssignments | undefined): Record<string, unknown> | undefined;
44
+ /** The `experiment_exposed` event for one assignment. */
45
+ declare function exposureEvent(flagKey: string, variant: string): {
46
+ event_name: string;
47
+ event_category: string;
48
+ properties: Record<string, unknown>;
49
+ };
50
+ /** Key under which a client remembers that an exposure was already sent this session. */
51
+ declare function exposureStorageKey(flagKey: string): string;
52
+
53
+ export { type ExperimentAssignment as E, MAX_EXPERIMENTS_PER_EVENT as M, EXPERIMENTS_PROPERTY as a, EXPERIMENT_EXPOSED_EVENT as b, type ExperimentAssignments as c, type ExperimentEvaluationLike as d, experimentVariant as e, exposureEvent as f, exposureStorageKey as g, isVariantKey as h, isExperimentKey as i, normalizeExperiments as n, withExperiments as w };
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Experiments (A/B tests) on top of scalemule-flags variants.
3
+ *
4
+ * Convention shared by every ScaleMule client and the analytics service:
5
+ * - An experiment is a flag with two or more weighted variants. Evaluating it with a stable
6
+ * identifier (`session_id` or `user_id`) yields the visitor's `variant_key`.
7
+ * - Every analytics event sent while a visitor is in an experiment carries
8
+ * `properties.experiments = { "<flag_key>": "<variant_key>" }`.
9
+ * - `experiment_exposed` is tracked once per visitor and flag when the variant is first shown.
10
+ * - The analytics service reports per-variant results from those properties
11
+ * (`GET /v1/analytics/admin/experiments/{flag_key}`), so any tracked event can be the goal.
12
+ */
13
+ declare const EXPERIMENTS_PROPERTY = "experiments";
14
+ declare const EXPERIMENT_EXPOSED_EVENT = "experiment_exposed";
15
+ declare const MAX_EXPERIMENTS_PER_EVENT = 10;
16
+ /** Active assignments for one visitor: flag key → variant key. */
17
+ type ExperimentAssignments = Record<string, string>;
18
+ interface ExperimentAssignment<T = unknown> {
19
+ flag_key: string;
20
+ /** The variant the visitor is in, or null when the flag is off, missing or has no variants. */
21
+ variant: string | null;
22
+ /** The raw flag evaluation this assignment came from, when one was made. */
23
+ evaluation?: ExperimentEvaluationLike<T> | null;
24
+ }
25
+ /** The subset of a flag evaluation the experiment helpers read. */
26
+ interface ExperimentEvaluationLike<T = unknown> {
27
+ flag_key?: string;
28
+ value?: T;
29
+ reason?: string;
30
+ variant_key?: string | null;
31
+ }
32
+ declare function isExperimentKey(value: unknown): value is string;
33
+ declare function isVariantKey(value: unknown): value is string;
34
+ /**
35
+ * The variant a flag evaluation puts the visitor in.
36
+ * Weighted variants report `variant_key`; a rule or default that serves a string value counts as
37
+ * that variant (so a rule can pin everyone to "modern" and the report still groups them).
38
+ */
39
+ declare function experimentVariant(evaluation: ExperimentEvaluationLike | null | undefined): string | null;
40
+ /** Keeps only well-formed `{ flag_key: variant_key }` pairs, at most MAX_EXPERIMENTS_PER_EVENT. */
41
+ declare function normalizeExperiments(input: unknown): ExperimentAssignments;
42
+ /** Merges the visitor's assignments into event properties under `experiments`. Empty assignments add nothing. */
43
+ declare function withExperiments(properties: Record<string, unknown> | undefined, experiments: ExperimentAssignments | undefined): Record<string, unknown> | undefined;
44
+ /** The `experiment_exposed` event for one assignment. */
45
+ declare function exposureEvent(flagKey: string, variant: string): {
46
+ event_name: string;
47
+ event_category: string;
48
+ properties: Record<string, unknown>;
49
+ };
50
+ /** Key under which a client remembers that an exposure was already sent this session. */
51
+ declare function exposureStorageKey(flagKey: string): string;
52
+
53
+ export { type ExperimentAssignment as E, MAX_EXPERIMENTS_PER_EVENT as M, EXPERIMENTS_PROPERTY as a, EXPERIMENT_EXPOSED_EVENT as b, type ExperimentAssignments as c, type ExperimentEvaluationLike as d, experimentVariant as e, exposureEvent as f, exposureStorageKey as g, isVariantKey as h, isExperimentKey as i, normalizeExperiments as n, withExperiments as w };
@@ -1,3 +1,5 @@
1
+ import { E as ExperimentAssignment } from '../experiments-RH_CTd1R.mjs';
2
+
1
3
  /** Wire format types matching the Rust FlagConfigWire from /v1/flags/config */
2
4
  interface FlagConfigWire {
3
5
  version: number;
@@ -96,6 +98,8 @@ declare class FlagClient {
96
98
  private doInit;
97
99
  private buildIndexes;
98
100
  evaluate(flagKey: string, context: EvaluationContext): FlagEvaluation;
101
+ /** Local-evaluation counterpart of `FlagsService.experiment`: the visitor's variant for a flag with weighted variants. */
102
+ experiment(flagKey: string, context: EvaluationContext): ExperimentAssignment;
99
103
  evaluateBatch(flagKeys: string[], context: EvaluationContext): Record<string, FlagEvaluation>;
100
104
  shutdown(): Promise<void>;
101
105
  private connectStream;
@@ -1,3 +1,5 @@
1
+ import { E as ExperimentAssignment } from '../experiments-RH_CTd1R.js';
2
+
1
3
  /** Wire format types matching the Rust FlagConfigWire from /v1/flags/config */
2
4
  interface FlagConfigWire {
3
5
  version: number;
@@ -96,6 +98,8 @@ declare class FlagClient {
96
98
  private doInit;
97
99
  private buildIndexes;
98
100
  evaluate(flagKey: string, context: EvaluationContext): FlagEvaluation;
101
+ /** Local-evaluation counterpart of `FlagsService.experiment`: the visitor's variant for a flag with weighted variants. */
102
+ experiment(flagKey: string, context: EvaluationContext): ExperimentAssignment;
99
103
  evaluateBatch(flagKeys: string[], context: EvaluationContext): Record<string, FlagEvaluation>;
100
104
  shutdown(): Promise<void>;
101
105
  private connectStream;
@@ -279,6 +279,18 @@ function result(flag, environment, value, reason) {
279
279
  };
280
280
  }
281
281
 
282
+ // src/experiments.ts
283
+ var VARIANT_PATTERN = /^[a-z0-9][a-z0-9_.:-]{0,63}$/;
284
+ function isVariantKey(value) {
285
+ return typeof value === "string" && VARIANT_PATTERN.test(value);
286
+ }
287
+ function experimentVariant(evaluation) {
288
+ if (!evaluation) return null;
289
+ if (isVariantKey(evaluation.variant_key)) return evaluation.variant_key;
290
+ if (isVariantKey(evaluation.value)) return evaluation.value;
291
+ return null;
292
+ }
293
+
282
294
  // src/flags/client.ts
283
295
  var FlagClient = class {
284
296
  constructor(options) {
@@ -353,6 +365,11 @@ var FlagClient = class {
353
365
  this.recordTelemetry(result2);
354
366
  return result2;
355
367
  }
368
+ /** Local-evaluation counterpart of `FlagsService.experiment`: the visitor's variant for a flag with weighted variants. */
369
+ experiment(flagKey, context) {
370
+ const evaluation = this.evaluate(flagKey, context);
371
+ return { flag_key: flagKey, variant: experimentVariant(evaluation), evaluation };
372
+ }
356
373
  evaluateBatch(flagKeys, context) {
357
374
  if (!this.config) throw new Error("FlagClient not initialized \u2014 call init() first");
358
375
  const results = {};
@@ -250,6 +250,18 @@ function result(flag, environment, value, reason) {
250
250
  };
251
251
  }
252
252
 
253
+ // src/experiments.ts
254
+ var VARIANT_PATTERN = /^[a-z0-9][a-z0-9_.:-]{0,63}$/;
255
+ function isVariantKey(value) {
256
+ return typeof value === "string" && VARIANT_PATTERN.test(value);
257
+ }
258
+ function experimentVariant(evaluation) {
259
+ if (!evaluation) return null;
260
+ if (isVariantKey(evaluation.variant_key)) return evaluation.variant_key;
261
+ if (isVariantKey(evaluation.value)) return evaluation.value;
262
+ return null;
263
+ }
264
+
253
265
  // src/flags/client.ts
254
266
  var FlagClient = class {
255
267
  constructor(options) {
@@ -324,6 +336,11 @@ var FlagClient = class {
324
336
  this.recordTelemetry(result2);
325
337
  return result2;
326
338
  }
339
+ /** Local-evaluation counterpart of `FlagsService.experiment`: the visitor's variant for a flag with weighted variants. */
340
+ experiment(flagKey, context) {
341
+ const evaluation = this.evaluate(flagKey, context);
342
+ return { flag_key: flagKey, variant: experimentVariant(evaluation), evaluation };
343
+ }
327
344
  evaluateBatch(flagKeys, context) {
328
345
  if (!this.config) throw new Error("FlagClient not initialized \u2014 call init() first");
329
346
  const results = {};
package/dist/index.d.mts CHANGED
@@ -1,4 +1,6 @@
1
1
  export { PHONE_COUNTRIES, PhoneCountry, PhoneNormalizationResult, composePhoneNumber, countryFlag, detectCountryFromE164, findPhoneCountryByCode, findPhoneCountryByDialCode, isValidE164Phone, normalizeAndValidatePhone, normalizePhoneNumber } from '@scalemule/ui/phone';
2
+ import { E as ExperimentAssignment } from './experiments-RH_CTd1R.mjs';
3
+ export { a as EXPERIMENTS_PROPERTY, b as EXPERIMENT_EXPOSED_EVENT, c as ExperimentAssignments, d as ExperimentEvaluationLike, M as MAX_EXPERIMENTS_PER_EVENT, e as experimentVariant, f as exposureEvent, g as exposureStorageKey, i as isExperimentKey, h as isVariantKey, n as normalizeExperiments, w as withExperiments } from './experiments-RH_CTd1R.mjs';
2
4
 
3
5
  /**
4
6
  * ScaleMule SDK Types
@@ -3689,6 +3691,13 @@ declare class AnalyticsService extends ServiceModule {
3689
3691
  track(event: string, properties?: Record<string, unknown>, userId?: string, options?: RequestOptions): Promise<ApiResponse<{
3690
3692
  tracked: boolean;
3691
3693
  }>>;
3694
+ /**
3695
+ * Track that a visitor saw an experiment variant. Send it once per visitor and flag; the event
3696
+ * carries `properties.experiments` so the experiment report attributes it.
3697
+ */
3698
+ trackExposure(flagKey: string, variant: string, userId?: string, options?: RequestOptions): Promise<ApiResponse<{
3699
+ tracked: boolean;
3700
+ }>>;
3692
3701
  trackBatch(events: Array<{
3693
3702
  event: string;
3694
3703
  properties?: Record<string, unknown>;
@@ -3877,6 +3886,12 @@ interface UpsertEnvironmentRequest {
3877
3886
  declare class FlagsService extends ServiceModule {
3878
3887
  protected basePath: string;
3879
3888
  evaluate<T = unknown>(flagKey: string, context?: Record<string, unknown>, environment?: string, options?: RequestOptions): Promise<ApiResponse<FlagEvaluation<T>>>;
3889
+ /**
3890
+ * Assign a visitor to an experiment: a flag with weighted variants, evaluated with a stable
3891
+ * identifier (`session_id` or `user_id`) so the assignment is sticky. Attach the result to
3892
+ * analytics events with `withExperiments` and track one exposure with `analytics.trackExposure`.
3893
+ */
3894
+ experiment<T = unknown>(flagKey: string, context?: Record<string, unknown>, environment?: string, options?: RequestOptions): Promise<ApiResponse<ExperimentAssignment<T>>>;
3880
3895
  evaluateBatch(flagKeys: string[], context?: Record<string, unknown>, environment?: string, options?: RequestOptions): Promise<ApiResponse<Record<string, FlagEvaluation>>>;
3881
3896
  evaluateAll(context?: Record<string, unknown>, environment?: string, options?: RequestOptions): Promise<ApiResponse<Record<string, FlagEvaluation>>>;
3882
3897
  list(params?: {
@@ -8558,4 +8573,4 @@ declare class ScaleMule {
8558
8573
  getClient(): ScaleMuleClient;
8559
8574
  }
8560
8575
 
8561
- export { type AcceptQuoteInput, 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 AppointmentDepositValue, type Attachment, type Attendee, type AudioRegisterResult, AudioService, type AudioUploadViaStorageResult, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type BookingCompletionResult, BookingsService, 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 CommunityMapArea, type CommunityMapCanonicalArea, type CommunityMapCollection, type CommunityMapCollectionConfig, type CommunityMapComment, type CommunityMapCommentInput, type CommunityMapCommentPage, type CommunityMapConsent, type CommunityMapEditorialCollection, type CommunityMapEditorialComment, type CommunityMapEditorialFeature, type CommunityMapEditorialMedia, type CommunityMapFeature, type CommunityMapFeatureDraft, type CommunityMapFeatureQuery, type CommunityMapFeatureStatus, type CommunityMapGeometry, type CommunityMapMedia, type CommunityMapOwnSubmission, type CommunityMapOwnSubmissionPage, type CommunityMapPage, type CommunityMapPosition, type CommunityMapPrecision, type CommunityMapPrivateReport, type CommunityMapPrivateSubmission, type CommunityMapProposal, type CommunityMapPublicContent, type CommunityMapQueueQuery, type CommunityMapReactionDefinition, type CommunityMapReceipt, type CommunityMapReportInput, type CommunityMapReportReason, type CommunityMapRevision, type CommunityMapSource, type CommunityMapSubmissionInput, type CommunityMapSubmissionPolicy, type CommunityMapSubmissionStatus, type CommunityMapSubmissionUpdate, type CommunityMapView, type CommunityMapVote, CommunityMapsEditorialService, CommunityMapsGeographyService, CommunityMapsService, type CommunityValueOutcome, 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 CreateLeadInput, type CreatePollInput, type CreateQuoteInput, 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 CustomerStats, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DecisionBatchItem, type DecisionBatchResult, type DecisionEvaluateOptions, type DecisionOutcome, type DecisionProposedAction, type DecisionReceipt, type DecisionResult, type DecisionTraceLevel, type DecisionVersions, DecisionsService, 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 IntelligenceAction, type IntelligenceCache, type IntelligenceChangePage, type IntelligenceClaim, type IntelligenceEvent, type IntelligenceKind, type IntelligenceRecordPage, type IntelligenceRelease, type IntelligenceReleaseReceipt, type IntelligenceSection, type IntelligenceSource, type IntelligenceStatus, type IntelligenceVerification, type Invoice, type JobExecution, type JobStats, type JoinCallResponse, type KnownAccount, type KnownAccountDisplay, LEGACY_ANONYMOUS_ID_KEYS, type Lead, type Leaderboard, type LeaderboardEntry, LeaderboardService, LeadsService, type Like, type ListNotificationsParams, type Listing, ListingsService, type LocalBriefing, type LocalIntelligencePreferences, type LocalIntelligenceRecord, LocalIntelligenceService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, MEDIA_PRESETS, type MediaAsset, type MediaCaptureSession, 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 Poll, type PollBallot, type PollChoice, type PollChoiceInput, type PollListOptions, type PollMedia, type PollMediaKind, type PollStatus, PollsService, 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 Quote, type QuoteDeposit, type QuoteState, type ReadStatus, RealtimeService, type ReceiptVerification, 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 SocialContentProjection, type SocialContentProjectionInput, type SocialDiscoveryCreatorInput, type SocialPolicyAction, type SocialPolicyBatchDecisionItem, type SocialPolicyBatchDecisionRequest, type SocialPolicyBatchDecisionResponse, type SocialPolicyBatchDecisionTarget, type SocialPolicyBlockRequest, type SocialPolicyContactRequest, type SocialPolicyContactRequestListItem, type SocialPolicyContactRequestQuery, type SocialPolicyContactRequestRequest, type SocialPolicyContext, type SocialPolicyDecision, type SocialPolicyDecisionLimits, type SocialPolicyDecisionRequest, type SocialPolicyDecisionResponse, type SocialPolicyIdentity, type SocialPolicyIdentityType, type SocialPolicyMuteRequest, type SocialPolicyPolicyPack, type SocialPolicyRelationship, type SocialPolicyRelationshipQuery, type SocialPolicyRelationshipRequest, type SocialPolicyReportRequest, SocialPolicyService, type SocialPolicySettings, type SocialPolicyUnblockRequest, type SocialPolicyUpdateSettingsRequest, 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 UpdatePollInput, 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 VoteState, 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, applyIntelligenceChanges, buildClientContextHeaders, calculateTotalParts, canPerform, createUploadPlan, ScaleMule as default, detectNetworkClass, ensureAnonymousId, extractClientContext, generateAnonymousId, generateUploadSessionId, getMeasuredBandwidthMbps, getPartRange, hasMinRoleLevel, pollSharePercent, pollVoterKey, prepareCommunityMapAttachment, readAnonymousId, resolveStrategy, startMediaCapture, uploadMultipartToS3, uploadSingleToS3, validateIP };
8576
+ export { type AcceptQuoteInput, 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 AppointmentDepositValue, type Attachment, type Attendee, type AudioRegisterResult, AudioService, type AudioUploadViaStorageResult, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type BookingCompletionResult, BookingsService, 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 CommunityMapArea, type CommunityMapCanonicalArea, type CommunityMapCollection, type CommunityMapCollectionConfig, type CommunityMapComment, type CommunityMapCommentInput, type CommunityMapCommentPage, type CommunityMapConsent, type CommunityMapEditorialCollection, type CommunityMapEditorialComment, type CommunityMapEditorialFeature, type CommunityMapEditorialMedia, type CommunityMapFeature, type CommunityMapFeatureDraft, type CommunityMapFeatureQuery, type CommunityMapFeatureStatus, type CommunityMapGeometry, type CommunityMapMedia, type CommunityMapOwnSubmission, type CommunityMapOwnSubmissionPage, type CommunityMapPage, type CommunityMapPosition, type CommunityMapPrecision, type CommunityMapPrivateReport, type CommunityMapPrivateSubmission, type CommunityMapProposal, type CommunityMapPublicContent, type CommunityMapQueueQuery, type CommunityMapReactionDefinition, type CommunityMapReceipt, type CommunityMapReportInput, type CommunityMapReportReason, type CommunityMapRevision, type CommunityMapSource, type CommunityMapSubmissionInput, type CommunityMapSubmissionPolicy, type CommunityMapSubmissionStatus, type CommunityMapSubmissionUpdate, type CommunityMapView, type CommunityMapVote, CommunityMapsEditorialService, CommunityMapsGeographyService, CommunityMapsService, type CommunityValueOutcome, 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 CreateLeadInput, type CreatePollInput, type CreateQuoteInput, 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 CustomerStats, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DecisionBatchItem, type DecisionBatchResult, type DecisionEvaluateOptions, type DecisionOutcome, type DecisionProposedAction, type DecisionReceipt, type DecisionResult, type DecisionTraceLevel, type DecisionVersions, DecisionsService, type DeviceInfo, type DirectoryUser, type DirectoryUserDetail, type DirectoryUsersListResponse, type Document, type ErrorCode, ErrorCodes, type EventAggregation, EventsService, ExperimentAssignment, 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 IntelligenceAction, type IntelligenceCache, type IntelligenceChangePage, type IntelligenceClaim, type IntelligenceEvent, type IntelligenceKind, type IntelligenceRecordPage, type IntelligenceRelease, type IntelligenceReleaseReceipt, type IntelligenceSection, type IntelligenceSource, type IntelligenceStatus, type IntelligenceVerification, type Invoice, type JobExecution, type JobStats, type JoinCallResponse, type KnownAccount, type KnownAccountDisplay, LEGACY_ANONYMOUS_ID_KEYS, type Lead, type Leaderboard, type LeaderboardEntry, LeaderboardService, LeadsService, type Like, type ListNotificationsParams, type Listing, ListingsService, type LocalBriefing, type LocalIntelligencePreferences, type LocalIntelligenceRecord, LocalIntelligenceService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, MEDIA_PRESETS, type MediaAsset, type MediaCaptureSession, 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 Poll, type PollBallot, type PollChoice, type PollChoiceInput, type PollListOptions, type PollMedia, type PollMediaKind, type PollStatus, PollsService, 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 Quote, type QuoteDeposit, type QuoteState, type ReadStatus, RealtimeService, type ReceiptVerification, 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 SocialContentProjection, type SocialContentProjectionInput, type SocialDiscoveryCreatorInput, type SocialPolicyAction, type SocialPolicyBatchDecisionItem, type SocialPolicyBatchDecisionRequest, type SocialPolicyBatchDecisionResponse, type SocialPolicyBatchDecisionTarget, type SocialPolicyBlockRequest, type SocialPolicyContactRequest, type SocialPolicyContactRequestListItem, type SocialPolicyContactRequestQuery, type SocialPolicyContactRequestRequest, type SocialPolicyContext, type SocialPolicyDecision, type SocialPolicyDecisionLimits, type SocialPolicyDecisionRequest, type SocialPolicyDecisionResponse, type SocialPolicyIdentity, type SocialPolicyIdentityType, type SocialPolicyMuteRequest, type SocialPolicyPolicyPack, type SocialPolicyRelationship, type SocialPolicyRelationshipQuery, type SocialPolicyRelationshipRequest, type SocialPolicyReportRequest, SocialPolicyService, type SocialPolicySettings, type SocialPolicyUnblockRequest, type SocialPolicyUpdateSettingsRequest, 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 UpdatePollInput, 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 VoteState, 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, applyIntelligenceChanges, buildClientContextHeaders, calculateTotalParts, canPerform, createUploadPlan, ScaleMule as default, detectNetworkClass, ensureAnonymousId, extractClientContext, generateAnonymousId, generateUploadSessionId, getMeasuredBandwidthMbps, getPartRange, hasMinRoleLevel, pollSharePercent, pollVoterKey, prepareCommunityMapAttachment, readAnonymousId, resolveStrategy, startMediaCapture, uploadMultipartToS3, uploadSingleToS3, validateIP };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export { PHONE_COUNTRIES, PhoneCountry, PhoneNormalizationResult, composePhoneNumber, countryFlag, detectCountryFromE164, findPhoneCountryByCode, findPhoneCountryByDialCode, isValidE164Phone, normalizeAndValidatePhone, normalizePhoneNumber } from '@scalemule/ui/phone';
2
+ import { E as ExperimentAssignment } from './experiments-RH_CTd1R.js';
3
+ export { a as EXPERIMENTS_PROPERTY, b as EXPERIMENT_EXPOSED_EVENT, c as ExperimentAssignments, d as ExperimentEvaluationLike, M as MAX_EXPERIMENTS_PER_EVENT, e as experimentVariant, f as exposureEvent, g as exposureStorageKey, i as isExperimentKey, h as isVariantKey, n as normalizeExperiments, w as withExperiments } from './experiments-RH_CTd1R.js';
2
4
 
3
5
  /**
4
6
  * ScaleMule SDK Types
@@ -3689,6 +3691,13 @@ declare class AnalyticsService extends ServiceModule {
3689
3691
  track(event: string, properties?: Record<string, unknown>, userId?: string, options?: RequestOptions): Promise<ApiResponse<{
3690
3692
  tracked: boolean;
3691
3693
  }>>;
3694
+ /**
3695
+ * Track that a visitor saw an experiment variant. Send it once per visitor and flag; the event
3696
+ * carries `properties.experiments` so the experiment report attributes it.
3697
+ */
3698
+ trackExposure(flagKey: string, variant: string, userId?: string, options?: RequestOptions): Promise<ApiResponse<{
3699
+ tracked: boolean;
3700
+ }>>;
3692
3701
  trackBatch(events: Array<{
3693
3702
  event: string;
3694
3703
  properties?: Record<string, unknown>;
@@ -3877,6 +3886,12 @@ interface UpsertEnvironmentRequest {
3877
3886
  declare class FlagsService extends ServiceModule {
3878
3887
  protected basePath: string;
3879
3888
  evaluate<T = unknown>(flagKey: string, context?: Record<string, unknown>, environment?: string, options?: RequestOptions): Promise<ApiResponse<FlagEvaluation<T>>>;
3889
+ /**
3890
+ * Assign a visitor to an experiment: a flag with weighted variants, evaluated with a stable
3891
+ * identifier (`session_id` or `user_id`) so the assignment is sticky. Attach the result to
3892
+ * analytics events with `withExperiments` and track one exposure with `analytics.trackExposure`.
3893
+ */
3894
+ experiment<T = unknown>(flagKey: string, context?: Record<string, unknown>, environment?: string, options?: RequestOptions): Promise<ApiResponse<ExperimentAssignment<T>>>;
3880
3895
  evaluateBatch(flagKeys: string[], context?: Record<string, unknown>, environment?: string, options?: RequestOptions): Promise<ApiResponse<Record<string, FlagEvaluation>>>;
3881
3896
  evaluateAll(context?: Record<string, unknown>, environment?: string, options?: RequestOptions): Promise<ApiResponse<Record<string, FlagEvaluation>>>;
3882
3897
  list(params?: {
@@ -8558,4 +8573,4 @@ declare class ScaleMule {
8558
8573
  getClient(): ScaleMuleClient;
8559
8574
  }
8560
8575
 
8561
- export { type AcceptQuoteInput, 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 AppointmentDepositValue, type Attachment, type Attendee, type AudioRegisterResult, AudioService, type AudioUploadViaStorageResult, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type BookingCompletionResult, BookingsService, 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 CommunityMapArea, type CommunityMapCanonicalArea, type CommunityMapCollection, type CommunityMapCollectionConfig, type CommunityMapComment, type CommunityMapCommentInput, type CommunityMapCommentPage, type CommunityMapConsent, type CommunityMapEditorialCollection, type CommunityMapEditorialComment, type CommunityMapEditorialFeature, type CommunityMapEditorialMedia, type CommunityMapFeature, type CommunityMapFeatureDraft, type CommunityMapFeatureQuery, type CommunityMapFeatureStatus, type CommunityMapGeometry, type CommunityMapMedia, type CommunityMapOwnSubmission, type CommunityMapOwnSubmissionPage, type CommunityMapPage, type CommunityMapPosition, type CommunityMapPrecision, type CommunityMapPrivateReport, type CommunityMapPrivateSubmission, type CommunityMapProposal, type CommunityMapPublicContent, type CommunityMapQueueQuery, type CommunityMapReactionDefinition, type CommunityMapReceipt, type CommunityMapReportInput, type CommunityMapReportReason, type CommunityMapRevision, type CommunityMapSource, type CommunityMapSubmissionInput, type CommunityMapSubmissionPolicy, type CommunityMapSubmissionStatus, type CommunityMapSubmissionUpdate, type CommunityMapView, type CommunityMapVote, CommunityMapsEditorialService, CommunityMapsGeographyService, CommunityMapsService, type CommunityValueOutcome, 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 CreateLeadInput, type CreatePollInput, type CreateQuoteInput, 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 CustomerStats, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DecisionBatchItem, type DecisionBatchResult, type DecisionEvaluateOptions, type DecisionOutcome, type DecisionProposedAction, type DecisionReceipt, type DecisionResult, type DecisionTraceLevel, type DecisionVersions, DecisionsService, 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 IntelligenceAction, type IntelligenceCache, type IntelligenceChangePage, type IntelligenceClaim, type IntelligenceEvent, type IntelligenceKind, type IntelligenceRecordPage, type IntelligenceRelease, type IntelligenceReleaseReceipt, type IntelligenceSection, type IntelligenceSource, type IntelligenceStatus, type IntelligenceVerification, type Invoice, type JobExecution, type JobStats, type JoinCallResponse, type KnownAccount, type KnownAccountDisplay, LEGACY_ANONYMOUS_ID_KEYS, type Lead, type Leaderboard, type LeaderboardEntry, LeaderboardService, LeadsService, type Like, type ListNotificationsParams, type Listing, ListingsService, type LocalBriefing, type LocalIntelligencePreferences, type LocalIntelligenceRecord, LocalIntelligenceService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, MEDIA_PRESETS, type MediaAsset, type MediaCaptureSession, 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 Poll, type PollBallot, type PollChoice, type PollChoiceInput, type PollListOptions, type PollMedia, type PollMediaKind, type PollStatus, PollsService, 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 Quote, type QuoteDeposit, type QuoteState, type ReadStatus, RealtimeService, type ReceiptVerification, 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 SocialContentProjection, type SocialContentProjectionInput, type SocialDiscoveryCreatorInput, type SocialPolicyAction, type SocialPolicyBatchDecisionItem, type SocialPolicyBatchDecisionRequest, type SocialPolicyBatchDecisionResponse, type SocialPolicyBatchDecisionTarget, type SocialPolicyBlockRequest, type SocialPolicyContactRequest, type SocialPolicyContactRequestListItem, type SocialPolicyContactRequestQuery, type SocialPolicyContactRequestRequest, type SocialPolicyContext, type SocialPolicyDecision, type SocialPolicyDecisionLimits, type SocialPolicyDecisionRequest, type SocialPolicyDecisionResponse, type SocialPolicyIdentity, type SocialPolicyIdentityType, type SocialPolicyMuteRequest, type SocialPolicyPolicyPack, type SocialPolicyRelationship, type SocialPolicyRelationshipQuery, type SocialPolicyRelationshipRequest, type SocialPolicyReportRequest, SocialPolicyService, type SocialPolicySettings, type SocialPolicyUnblockRequest, type SocialPolicyUpdateSettingsRequest, 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 UpdatePollInput, 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 VoteState, 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, applyIntelligenceChanges, buildClientContextHeaders, calculateTotalParts, canPerform, createUploadPlan, ScaleMule as default, detectNetworkClass, ensureAnonymousId, extractClientContext, generateAnonymousId, generateUploadSessionId, getMeasuredBandwidthMbps, getPartRange, hasMinRoleLevel, pollSharePercent, pollVoterKey, prepareCommunityMapAttachment, readAnonymousId, resolveStrategy, startMediaCapture, uploadMultipartToS3, uploadSingleToS3, validateIP };
8576
+ export { type AcceptQuoteInput, 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 AppointmentDepositValue, type Attachment, type Attendee, type AudioRegisterResult, AudioService, type AudioUploadViaStorageResult, type AuditLog, type AuthRegisterAgentRequest, type AuthRegisterAgentResponse, AuthService, type AuthSession, type AuthUser, type BackupCodes, BillingService, type BookingCompletionResult, BookingsService, 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 CommunityMapArea, type CommunityMapCanonicalArea, type CommunityMapCollection, type CommunityMapCollectionConfig, type CommunityMapComment, type CommunityMapCommentInput, type CommunityMapCommentPage, type CommunityMapConsent, type CommunityMapEditorialCollection, type CommunityMapEditorialComment, type CommunityMapEditorialFeature, type CommunityMapEditorialMedia, type CommunityMapFeature, type CommunityMapFeatureDraft, type CommunityMapFeatureQuery, type CommunityMapFeatureStatus, type CommunityMapGeometry, type CommunityMapMedia, type CommunityMapOwnSubmission, type CommunityMapOwnSubmissionPage, type CommunityMapPage, type CommunityMapPosition, type CommunityMapPrecision, type CommunityMapPrivateReport, type CommunityMapPrivateSubmission, type CommunityMapProposal, type CommunityMapPublicContent, type CommunityMapQueueQuery, type CommunityMapReactionDefinition, type CommunityMapReceipt, type CommunityMapReportInput, type CommunityMapReportReason, type CommunityMapRevision, type CommunityMapSource, type CommunityMapSubmissionInput, type CommunityMapSubmissionPolicy, type CommunityMapSubmissionStatus, type CommunityMapSubmissionUpdate, type CommunityMapView, type CommunityMapVote, CommunityMapsEditorialService, CommunityMapsGeographyService, CommunityMapsService, type CommunityValueOutcome, 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 CreateLeadInput, type CreatePollInput, type CreateQuoteInput, 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 CustomerStats, type DataAccessPolicy, type DataExport, DataService, type DataSource, type DeadLetterJob, type DecisionBatchItem, type DecisionBatchResult, type DecisionEvaluateOptions, type DecisionOutcome, type DecisionProposedAction, type DecisionReceipt, type DecisionResult, type DecisionTraceLevel, type DecisionVersions, DecisionsService, type DeviceInfo, type DirectoryUser, type DirectoryUserDetail, type DirectoryUsersListResponse, type Document, type ErrorCode, ErrorCodes, type EventAggregation, EventsService, ExperimentAssignment, 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 IntelligenceAction, type IntelligenceCache, type IntelligenceChangePage, type IntelligenceClaim, type IntelligenceEvent, type IntelligenceKind, type IntelligenceRecordPage, type IntelligenceRelease, type IntelligenceReleaseReceipt, type IntelligenceSection, type IntelligenceSource, type IntelligenceStatus, type IntelligenceVerification, type Invoice, type JobExecution, type JobStats, type JoinCallResponse, type KnownAccount, type KnownAccountDisplay, LEGACY_ANONYMOUS_ID_KEYS, type Lead, type Leaderboard, type LeaderboardEntry, LeaderboardService, LeadsService, type Like, type ListNotificationsParams, type Listing, ListingsService, type LocalBriefing, type LocalIntelligencePreferences, type LocalIntelligenceRecord, LocalIntelligenceService, type LogEntry, type LogInput, type LogQueryParams, type LogQueryResponse, type LogRecord, LoggerService, type LoginActivitySummary, type LoginDeviceInfo, type LoginHistoryEntry, type LoginRiskInfo, MEDIA_PRESETS, type MediaAsset, type MediaCaptureSession, 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 Poll, type PollBallot, type PollChoice, type PollChoiceInput, type PollListOptions, type PollMedia, type PollMediaKind, type PollStatus, PollsService, 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 Quote, type QuoteDeposit, type QuoteState, type ReadStatus, RealtimeService, type ReceiptVerification, 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 SocialContentProjection, type SocialContentProjectionInput, type SocialDiscoveryCreatorInput, type SocialPolicyAction, type SocialPolicyBatchDecisionItem, type SocialPolicyBatchDecisionRequest, type SocialPolicyBatchDecisionResponse, type SocialPolicyBatchDecisionTarget, type SocialPolicyBlockRequest, type SocialPolicyContactRequest, type SocialPolicyContactRequestListItem, type SocialPolicyContactRequestQuery, type SocialPolicyContactRequestRequest, type SocialPolicyContext, type SocialPolicyDecision, type SocialPolicyDecisionLimits, type SocialPolicyDecisionRequest, type SocialPolicyDecisionResponse, type SocialPolicyIdentity, type SocialPolicyIdentityType, type SocialPolicyMuteRequest, type SocialPolicyPolicyPack, type SocialPolicyRelationship, type SocialPolicyRelationshipQuery, type SocialPolicyRelationshipRequest, type SocialPolicyReportRequest, SocialPolicyService, type SocialPolicySettings, type SocialPolicyUnblockRequest, type SocialPolicyUpdateSettingsRequest, 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 UpdatePollInput, 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 VoteState, 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, applyIntelligenceChanges, buildClientContextHeaders, calculateTotalParts, canPerform, createUploadPlan, ScaleMule as default, detectNetworkClass, ensureAnonymousId, extractClientContext, generateAnonymousId, generateUploadSessionId, getMeasuredBandwidthMbps, getPartRange, hasMinRoleLevel, pollSharePercent, pollVoterKey, prepareCommunityMapAttachment, readAnonymousId, resolveStrategy, startMediaCapture, uploadMultipartToS3, uploadSingleToS3, validateIP };
package/dist/index.js CHANGED
@@ -327,6 +327,8 @@ __export(index_exports, {
327
327
  CreatorMakerService: () => CreatorMakerService,
328
328
  DataService: () => DataService,
329
329
  DecisionsService: () => DecisionsService,
330
+ EXPERIMENTS_PROPERTY: () => EXPERIMENTS_PROPERTY,
331
+ EXPERIMENT_EXPOSED_EVENT: () => EXPERIMENT_EXPOSED_EVENT,
330
332
  ErrorCodes: () => ErrorCodes,
331
333
  EventsService: () => EventsService,
332
334
  FlagContentService: () => FlagContentService,
@@ -340,6 +342,7 @@ __export(index_exports, {
340
342
  ListingsService: () => ListingsService,
341
343
  LocalIntelligenceService: () => LocalIntelligenceService,
342
344
  LoggerService: () => LoggerService,
345
+ MAX_EXPERIMENTS_PER_EVENT: () => MAX_EXPERIMENTS_PER_EVENT,
343
346
  MEDIA_PRESETS: () => MEDIA_PRESETS,
344
347
  MediaService: () => MediaService,
345
348
  NotificationsService: () => NotificationsService,
@@ -381,6 +384,9 @@ __export(index_exports, {
381
384
  detectCountryFromE164: () => detectCountryFromE164,
382
385
  detectNetworkClass: () => detectNetworkClass,
383
386
  ensureAnonymousId: () => ensureAnonymousId,
387
+ experimentVariant: () => experimentVariant,
388
+ exposureEvent: () => exposureEvent,
389
+ exposureStorageKey: () => exposureStorageKey,
384
390
  extractClientContext: () => extractClientContext,
385
391
  findPhoneCountryByCode: () => findPhoneCountryByCode,
386
392
  findPhoneCountryByDialCode: () => findPhoneCountryByDialCode,
@@ -389,8 +395,11 @@ __export(index_exports, {
389
395
  getMeasuredBandwidthMbps: () => getMeasuredBandwidthMbps,
390
396
  getPartRange: () => getPartRange,
391
397
  hasMinRoleLevel: () => hasMinRoleLevel,
398
+ isExperimentKey: () => isExperimentKey,
392
399
  isValidE164Phone: () => isValidE164Phone,
400
+ isVariantKey: () => isVariantKey,
393
401
  normalizeAndValidatePhone: () => normalizeAndValidatePhone,
402
+ normalizeExperiments: () => normalizeExperiments,
394
403
  normalizePhoneNumber: () => normalizePhoneNumber,
395
404
  pollSharePercent: () => pollSharePercent,
396
405
  pollVoterKey: () => pollVoterKey,
@@ -400,7 +409,8 @@ __export(index_exports, {
400
409
  startMediaCapture: () => startMediaCapture,
401
410
  uploadMultipartToS3: () => uploadMultipartToS3,
402
411
  uploadSingleToS3: () => uploadSingleToS3,
403
- validateIP: () => validateIP
412
+ validateIP: () => validateIP,
413
+ withExperiments: () => withExperiments
404
414
  });
405
415
  module.exports = __toCommonJS(index_exports);
406
416
 
@@ -5810,6 +5820,58 @@ var BillingService = class extends ServiceModule {
5810
5820
  }
5811
5821
  };
5812
5822
 
5823
+ // src/experiments.ts
5824
+ var EXPERIMENTS_PROPERTY = "experiments";
5825
+ var EXPERIMENT_EXPOSED_EVENT = "experiment_exposed";
5826
+ var MAX_EXPERIMENTS_PER_EVENT = 10;
5827
+ var KEY_PATTERN = /^[a-z0-9][a-z0-9_.-]{0,63}$/;
5828
+ var VARIANT_PATTERN = /^[a-z0-9][a-z0-9_.:-]{0,63}$/;
5829
+ function isExperimentKey(value) {
5830
+ return typeof value === "string" && KEY_PATTERN.test(value);
5831
+ }
5832
+ function isVariantKey(value) {
5833
+ return typeof value === "string" && VARIANT_PATTERN.test(value);
5834
+ }
5835
+ function experimentVariant(evaluation) {
5836
+ if (!evaluation) return null;
5837
+ if (isVariantKey(evaluation.variant_key)) return evaluation.variant_key;
5838
+ if (isVariantKey(evaluation.value)) return evaluation.value;
5839
+ return null;
5840
+ }
5841
+ function normalizeExperiments(input) {
5842
+ const result = {};
5843
+ if (!input || typeof input !== "object" || Array.isArray(input)) return result;
5844
+ let count = 0;
5845
+ for (const [key, value] of Object.entries(input)) {
5846
+ if (count >= MAX_EXPERIMENTS_PER_EVENT) break;
5847
+ if (isExperimentKey(key) && isVariantKey(value)) {
5848
+ result[key] = value;
5849
+ count++;
5850
+ }
5851
+ }
5852
+ return result;
5853
+ }
5854
+ function withExperiments(properties, experiments) {
5855
+ const normalized = normalizeExperiments({
5856
+ ...normalizeExperiments(properties?.[EXPERIMENTS_PROPERTY]),
5857
+ ...experiments ?? {}
5858
+ });
5859
+ if (Object.keys(normalized).length === 0) return properties;
5860
+ return { ...properties ?? {}, [EXPERIMENTS_PROPERTY]: normalized };
5861
+ }
5862
+ function exposureEvent(flagKey, variant) {
5863
+ if (!isExperimentKey(flagKey)) throw new Error(`Invalid experiment flag key: ${flagKey}`);
5864
+ if (!isVariantKey(variant)) throw new Error(`Invalid experiment variant: ${variant}`);
5865
+ return {
5866
+ event_name: EXPERIMENT_EXPOSED_EVENT,
5867
+ event_category: "system",
5868
+ properties: { flag_key: flagKey, variant, [EXPERIMENTS_PROPERTY]: { [flagKey]: variant } }
5869
+ };
5870
+ }
5871
+ function exposureStorageKey(flagKey) {
5872
+ return `sm_experiment_exposed:${flagKey}`;
5873
+ }
5874
+
5813
5875
  // src/services/analytics.ts
5814
5876
  var AnalyticsService = class extends ServiceModule {
5815
5877
  constructor() {
@@ -5826,6 +5888,14 @@ var AnalyticsService = class extends ServiceModule {
5826
5888
  }
5827
5889
  return this.post("/v2/events", payload, options);
5828
5890
  }
5891
+ /**
5892
+ * Track that a visitor saw an experiment variant. Send it once per visitor and flag; the event
5893
+ * carries `properties.experiments` so the experiment report attributes it.
5894
+ */
5895
+ async trackExposure(flagKey, variant, userId, options) {
5896
+ const event = exposureEvent(flagKey, variant);
5897
+ return this.track(event.event_name, event.properties, userId, options);
5898
+ }
5829
5899
  async trackBatch(events, options) {
5830
5900
  const mapped = events.map(({ event, ...rest }) => ({ event_name: event, ...rest }));
5831
5901
  return this.post("/v2/events/batch", { events: mapped }, options);
@@ -5900,6 +5970,19 @@ var FlagsService = class extends ServiceModule {
5900
5970
  async evaluate(flagKey, context = {}, environment = "prod", options) {
5901
5971
  return this.post("/evaluate", { flag_key: flagKey, environment, context }, options);
5902
5972
  }
5973
+ /**
5974
+ * Assign a visitor to an experiment: a flag with weighted variants, evaluated with a stable
5975
+ * identifier (`session_id` or `user_id`) so the assignment is sticky. Attach the result to
5976
+ * analytics events with `withExperiments` and track one exposure with `analytics.trackExposure`.
5977
+ */
5978
+ async experiment(flagKey, context = {}, environment = "prod", options) {
5979
+ const response = await this.evaluate(flagKey, context, environment, options);
5980
+ if (response.error || !response.data) return { data: null, error: response.error };
5981
+ return {
5982
+ data: { flag_key: flagKey, variant: experimentVariant(response.data), evaluation: response.data },
5983
+ error: null
5984
+ };
5985
+ }
5903
5986
  async evaluateBatch(flagKeys, context = {}, environment = "prod", options) {
5904
5987
  return this.post(
5905
5988
  "/evaluate/batch",
@@ -9558,6 +9641,8 @@ var index_default = ScaleMule;
9558
9641
  CreatorMakerService,
9559
9642
  DataService,
9560
9643
  DecisionsService,
9644
+ EXPERIMENTS_PROPERTY,
9645
+ EXPERIMENT_EXPOSED_EVENT,
9561
9646
  ErrorCodes,
9562
9647
  EventsService,
9563
9648
  FlagContentService,
@@ -9571,6 +9656,7 @@ var index_default = ScaleMule;
9571
9656
  ListingsService,
9572
9657
  LocalIntelligenceService,
9573
9658
  LoggerService,
9659
+ MAX_EXPERIMENTS_PER_EVENT,
9574
9660
  MEDIA_PRESETS,
9575
9661
  MediaService,
9576
9662
  NotificationsService,
@@ -9611,6 +9697,9 @@ var index_default = ScaleMule;
9611
9697
  detectCountryFromE164,
9612
9698
  detectNetworkClass,
9613
9699
  ensureAnonymousId,
9700
+ experimentVariant,
9701
+ exposureEvent,
9702
+ exposureStorageKey,
9614
9703
  extractClientContext,
9615
9704
  findPhoneCountryByCode,
9616
9705
  findPhoneCountryByDialCode,
@@ -9619,8 +9708,11 @@ var index_default = ScaleMule;
9619
9708
  getMeasuredBandwidthMbps,
9620
9709
  getPartRange,
9621
9710
  hasMinRoleLevel,
9711
+ isExperimentKey,
9622
9712
  isValidE164Phone,
9713
+ isVariantKey,
9623
9714
  normalizeAndValidatePhone,
9715
+ normalizeExperiments,
9624
9716
  normalizePhoneNumber,
9625
9717
  pollSharePercent,
9626
9718
  pollVoterKey,
@@ -9630,5 +9722,6 @@ var index_default = ScaleMule;
9630
9722
  startMediaCapture,
9631
9723
  uploadMultipartToS3,
9632
9724
  uploadSingleToS3,
9633
- validateIP
9725
+ validateIP,
9726
+ withExperiments
9634
9727
  });
package/dist/index.mjs CHANGED
@@ -5684,6 +5684,58 @@ var BillingService = class extends ServiceModule {
5684
5684
  }
5685
5685
  };
5686
5686
 
5687
+ // src/experiments.ts
5688
+ var EXPERIMENTS_PROPERTY = "experiments";
5689
+ var EXPERIMENT_EXPOSED_EVENT = "experiment_exposed";
5690
+ var MAX_EXPERIMENTS_PER_EVENT = 10;
5691
+ var KEY_PATTERN = /^[a-z0-9][a-z0-9_.-]{0,63}$/;
5692
+ var VARIANT_PATTERN = /^[a-z0-9][a-z0-9_.:-]{0,63}$/;
5693
+ function isExperimentKey(value) {
5694
+ return typeof value === "string" && KEY_PATTERN.test(value);
5695
+ }
5696
+ function isVariantKey(value) {
5697
+ return typeof value === "string" && VARIANT_PATTERN.test(value);
5698
+ }
5699
+ function experimentVariant(evaluation) {
5700
+ if (!evaluation) return null;
5701
+ if (isVariantKey(evaluation.variant_key)) return evaluation.variant_key;
5702
+ if (isVariantKey(evaluation.value)) return evaluation.value;
5703
+ return null;
5704
+ }
5705
+ function normalizeExperiments(input) {
5706
+ const result = {};
5707
+ if (!input || typeof input !== "object" || Array.isArray(input)) return result;
5708
+ let count = 0;
5709
+ for (const [key, value] of Object.entries(input)) {
5710
+ if (count >= MAX_EXPERIMENTS_PER_EVENT) break;
5711
+ if (isExperimentKey(key) && isVariantKey(value)) {
5712
+ result[key] = value;
5713
+ count++;
5714
+ }
5715
+ }
5716
+ return result;
5717
+ }
5718
+ function withExperiments(properties, experiments) {
5719
+ const normalized = normalizeExperiments({
5720
+ ...normalizeExperiments(properties?.[EXPERIMENTS_PROPERTY]),
5721
+ ...experiments ?? {}
5722
+ });
5723
+ if (Object.keys(normalized).length === 0) return properties;
5724
+ return { ...properties ?? {}, [EXPERIMENTS_PROPERTY]: normalized };
5725
+ }
5726
+ function exposureEvent(flagKey, variant) {
5727
+ if (!isExperimentKey(flagKey)) throw new Error(`Invalid experiment flag key: ${flagKey}`);
5728
+ if (!isVariantKey(variant)) throw new Error(`Invalid experiment variant: ${variant}`);
5729
+ return {
5730
+ event_name: EXPERIMENT_EXPOSED_EVENT,
5731
+ event_category: "system",
5732
+ properties: { flag_key: flagKey, variant, [EXPERIMENTS_PROPERTY]: { [flagKey]: variant } }
5733
+ };
5734
+ }
5735
+ function exposureStorageKey(flagKey) {
5736
+ return `sm_experiment_exposed:${flagKey}`;
5737
+ }
5738
+
5687
5739
  // src/services/analytics.ts
5688
5740
  var AnalyticsService = class extends ServiceModule {
5689
5741
  constructor() {
@@ -5700,6 +5752,14 @@ var AnalyticsService = class extends ServiceModule {
5700
5752
  }
5701
5753
  return this.post("/v2/events", payload, options);
5702
5754
  }
5755
+ /**
5756
+ * Track that a visitor saw an experiment variant. Send it once per visitor and flag; the event
5757
+ * carries `properties.experiments` so the experiment report attributes it.
5758
+ */
5759
+ async trackExposure(flagKey, variant, userId, options) {
5760
+ const event = exposureEvent(flagKey, variant);
5761
+ return this.track(event.event_name, event.properties, userId, options);
5762
+ }
5703
5763
  async trackBatch(events, options) {
5704
5764
  const mapped = events.map(({ event, ...rest }) => ({ event_name: event, ...rest }));
5705
5765
  return this.post("/v2/events/batch", { events: mapped }, options);
@@ -5774,6 +5834,19 @@ var FlagsService = class extends ServiceModule {
5774
5834
  async evaluate(flagKey, context = {}, environment = "prod", options) {
5775
5835
  return this.post("/evaluate", { flag_key: flagKey, environment, context }, options);
5776
5836
  }
5837
+ /**
5838
+ * Assign a visitor to an experiment: a flag with weighted variants, evaluated with a stable
5839
+ * identifier (`session_id` or `user_id`) so the assignment is sticky. Attach the result to
5840
+ * analytics events with `withExperiments` and track one exposure with `analytics.trackExposure`.
5841
+ */
5842
+ async experiment(flagKey, context = {}, environment = "prod", options) {
5843
+ const response = await this.evaluate(flagKey, context, environment, options);
5844
+ if (response.error || !response.data) return { data: null, error: response.error };
5845
+ return {
5846
+ data: { flag_key: flagKey, variant: experimentVariant(response.data), evaluation: response.data },
5847
+ error: null
5848
+ };
5849
+ }
5777
5850
  async evaluateBatch(flagKeys, context = {}, environment = "prod", options) {
5778
5851
  return this.post(
5779
5852
  "/evaluate/batch",
@@ -9431,6 +9504,8 @@ export {
9431
9504
  CreatorMakerService,
9432
9505
  DataService,
9433
9506
  DecisionsService,
9507
+ EXPERIMENTS_PROPERTY,
9508
+ EXPERIMENT_EXPOSED_EVENT,
9434
9509
  ErrorCodes,
9435
9510
  EventsService,
9436
9511
  FlagContentService,
@@ -9444,6 +9519,7 @@ export {
9444
9519
  ListingsService,
9445
9520
  LocalIntelligenceService,
9446
9521
  LoggerService,
9522
+ MAX_EXPERIMENTS_PER_EVENT,
9447
9523
  MEDIA_PRESETS,
9448
9524
  MediaService,
9449
9525
  NotificationsService,
@@ -9485,6 +9561,9 @@ export {
9485
9561
  detectCountryFromE164,
9486
9562
  detectNetworkClass,
9487
9563
  ensureAnonymousId,
9564
+ experimentVariant,
9565
+ exposureEvent,
9566
+ exposureStorageKey,
9488
9567
  extractClientContext,
9489
9568
  findPhoneCountryByCode,
9490
9569
  findPhoneCountryByDialCode,
@@ -9493,8 +9572,11 @@ export {
9493
9572
  getMeasuredBandwidthMbps,
9494
9573
  getPartRange,
9495
9574
  hasMinRoleLevel,
9575
+ isExperimentKey,
9496
9576
  isValidE164Phone,
9577
+ isVariantKey,
9497
9578
  normalizeAndValidatePhone,
9579
+ normalizeExperiments,
9498
9580
  normalizePhoneNumber,
9499
9581
  pollSharePercent,
9500
9582
  pollVoterKey,
@@ -9504,5 +9586,6 @@ export {
9504
9586
  startMediaCapture,
9505
9587
  uploadMultipartToS3,
9506
9588
  uploadSingleToS3,
9507
- validateIP
9589
+ validateIP,
9590
+ withExperiments
9508
9591
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalemule/sdk",
3
- "version": "0.0.76",
3
+ "version": "0.0.77",
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",