@microsurveysai/react-native 0.1.6 → 0.1.7

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.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/MicroSurveys.ts","../src/core/storage.ts","../src/core/outbox.ts","../src/core/types.ts","../src/core/apiClient.ts","../src/core/persistence.ts","../src/core/identity.ts","../src/core/sampling.ts","../src/core/triggerSequencer.ts","../src/core/triggerEngine.ts","../src/core/eventCounter.ts","../src/core/debug.ts","../src/core/version.ts","../src/core/client.ts","../src/amplitude.ts","../src/asyncStorage.ts","../src/provider.tsx","../src/ui/SurveyModal.tsx","../src/ui/SurveyCard.tsx","../src/ui/CloseButton.tsx","../src/ui/platform.ts","../src/ui/questions.tsx","../src/ui/theme.ts","../src/MicroSurvey.tsx"],"sourcesContent":["//\n// MicroSurveys.ts\n//\n// Public entry point, mirroring iOS `MicroSurveysSDK`. A host wires it up in a\n// few lines, usually at module scope so it can be shared:\n//\n// export const ms = new MicroSurveys({ apiKey: \"ms_live_…\" });\n// amplitude.add(ms.amplitudePlugin()); // forward events + identity\n// ms.start(); // fetch config + flush outbox\n//\n// then mounts <MicroSurveysProvider instance={ms}> to render surveys. It wraps\n// the survey engine (./core) with React Native storage (AsyncStorage), the\n// `AppState` foreground signal and the device platform. Storage loads\n// asynchronously, so calls made before it's ready are buffered and replayed in\n// order.\n//\n\nimport AsyncStorage from \"@react-native-async-storage/async-storage\";\nimport { AppState, Platform } from \"react-native\";\nimport { createClient } from \"./core\";\nimport type {\n ActiveSurvey,\n AnalyticsIdentity,\n KeyValueStorage,\n MicroSurveysClient,\n ProjectTheme,\n Survey,\n SurveyResult,\n} from \"./core\";\nimport { createAmplitudePlugin } from \"./amplitude\";\nimport type { MicroSurveysAmplitudePlugin } from \"./amplitude\";\nimport { hydrateAsyncStorage } from \"./asyncStorage\";\nimport type { AsyncKeyValueStorage } from \"./asyncStorage\";\n\n/** Default API base. Override via `apiBaseURL` for self-hosted deployments. */\nconst DEFAULT_BASE_URL = \"https://console.microsurveys.ai\";\n/** Cached config counts as fresh for 12h on app-foreground, like iOS. */\nconst DEFAULT_CONFIG_TTL_MS = 12 * 60 * 60 * 1000;\n\nexport interface MicroSurveysOptions {\n /** Project API key (`ms_live_…` / `ms_test_…`) from the dashboard. */\n apiKey: string;\n /** Override for self-hosted deployments. Defaults to https://console.microsurveys.ai. */\n apiBaseURL?: string;\n /** Refresh config (when stale) and retry queued ingest whenever the app returns\n * to the foreground. Default true. */\n refreshOnForeground?: boolean;\n /** Foreground freshness window for the cached config, in ms. Default 12h. */\n configTTLms?: number;\n /** A synchronous store (e.g. MMKV) to persist into instead of AsyncStorage. */\n storage?: KeyValueStorage;\n /** An async store to persist into. Defaults to `@react-native-async-storage/async-storage`. */\n asyncStorage?: AsyncKeyValueStorage;\n /** Your app's version (e.g. \"3.2.0\"), sent with responses so results can be\n * compared across releases. With Expo: `Application.nativeApplicationVersion`. */\n appVersion?: string;\n}\n\nfunction appStateForeground(onForeground: () => void): () => void {\n const sub = AppState.addEventListener(\"change\", (state) => {\n if (state === \"active\") onForeground();\n });\n return () => sub.remove();\n}\n\nfunction appStateBackground(onBackground: () => void): () => void {\n const sub = AppState.addEventListener(\"change\", (state) => {\n if (state === \"background\") onBackground();\n });\n return () => sub.remove();\n}\n\nexport class MicroSurveys {\n readonly apiKey: string;\n /** Resolves with the underlying runtime once storage has loaded. */\n readonly ready: Promise<MicroSurveysClient>;\n\n private client: MicroSurveysClient | null = null;\n private pending: ((client: MicroSurveysClient) => void)[] = [];\n\n constructor(opts: MicroSurveysOptions) {\n this.apiKey = opts.apiKey;\n const storage: Promise<KeyValueStorage> = opts.storage\n ? Promise.resolve(opts.storage)\n : hydrateAsyncStorage(opts.asyncStorage ?? (AsyncStorage as unknown as AsyncKeyValueStorage));\n\n this.ready = storage.then((kv) => {\n const client = createClient({\n apiKey: opts.apiKey,\n apiBaseURL: opts.apiBaseURL ?? DEFAULT_BASE_URL,\n configTTLms: opts.configTTLms ?? DEFAULT_CONFIG_TTL_MS,\n refreshOnForeground: opts.refreshOnForeground ?? true,\n // Survey platform targeting: \"ios\" | \"android\".\n platform: Platform.OS,\n osVersion: String(Platform.Version),\n appVersion: opts.appVersion,\n storage: kv,\n subscribeForeground: appStateForeground,\n subscribeBackground: appStateBackground,\n });\n this.client = client;\n const queued = this.pending;\n this.pending = [];\n for (const run of queued) run(client);\n return client;\n });\n }\n\n /** Runs `fn` now if the runtime is ready, otherwise as soon as it is. */\n private withClient(fn: (client: MicroSurveysClient) => void): void {\n if (this.client) fn(this.client);\n else this.pending.push(fn);\n }\n\n // ── Lifecycle ────────────────────────────────────────────────────────────────\n\n /** Flushes queued impressions/responses, refreshes the config, and starts the\n * foreground refresh. Safe to call once early in app launch (the provider\n * calls it for you unless `autoStart={false}`). */\n start(): void {\n this.withClient((c) => c.start());\n }\n\n /** Stops foreground refresh and cancels pending (delayed) presentations. */\n stop(): void {\n this.withClient((c) => c.stop());\n }\n\n /** Forces an ETag-aware config refresh. Keeps the cache on failure. */\n async refreshConfig(): Promise<void> {\n const client = await this.ready;\n await client.refreshConfig();\n }\n\n // ── Identity + events ────────────────────────────────────────────────────────\n\n /** Identify the current user and/or attach properties used by audience\n * targeting. Optional with Amplitude (identity flows in via the plugin). */\n identify(userId: string | null | undefined, properties?: Record<string, unknown>): void {\n this.withClient((c) => c.identify(userId, properties));\n }\n\n /** Record an event. An eligible survey presents itself after its configured\n * delay. Not needed for events that already flow through Amplitude. */\n track(name: string, properties?: Record<string, unknown>): void {\n this.withClient((c) => c.track(name, properties));\n }\n\n /** Identity forwarded by an analytics SDK. Used by the Amplitude plugin. */\n updateAnalyticsIdentity(update: AnalyticsIdentity): void {\n this.withClient((c) => c.updateAnalyticsIdentity(update));\n }\n\n /** The enrichment plugin to register on your Amplitude instance:\n * `amplitude.add(ms.amplitudePlugin())`. Forwards events + identity into the\n * SDK and returns every event unmodified. */\n amplitudePlugin(): MicroSurveysAmplitudePlugin {\n return createAmplitudePlugin(this);\n }\n\n // ── Config + presentation (used by the provider and inline surveys) ──────────\n\n getTheme(): ProjectTheme | null {\n return this.client?.getTheme() ?? null;\n }\n\n getSurvey(surveyId: string): Survey | undefined {\n return this.client?.getSurvey(surveyId);\n }\n\n /** Subscribe to config loads/refreshes. Fires once when the cached config\n * becomes available. Returns an unsubscribe function. */\n onConfigChange(cb: () => void): () => void {\n let unsubscribe: (() => void) | null = null;\n let cancelled = false;\n this.withClient((c) => {\n if (cancelled) return;\n unsubscribe = c.onConfigChange(cb);\n cb();\n });\n return () => {\n cancelled = true;\n unsubscribe?.();\n };\n }\n\n /** Subscribe to auto-triggered surveys. Returns an unsubscribe function. */\n onPresent(cb: (active: ActiveSurvey) => void): () => void {\n let unsubscribe: (() => void) | null = null;\n let cancelled = false;\n this.withClient((c) => {\n if (!cancelled) unsubscribe = c.onPresent(cb);\n });\n return () => {\n cancelled = true;\n unsubscribe?.();\n };\n }\n\n /** Records the outcome of an inline `<MicroSurvey>`. */\n recordInline(survey: Survey, result: SurveyResult, shownAt: Date): void {\n this.withClient((c) => c.recordInline(survey, result, shownAt));\n }\n}\n","//\n// storage.ts\n//\n// Primitives shared by the persistence layers. Every store takes a\n// `KeyValueStorage`: AsyncStorage preloaded into memory (see ../asyncStorage.ts),\n// or a synchronous store such as MMKV.\n//\n\n/** Synchronous string key/value storage the runtime persists into.\n * Implementations should swallow their own errors\n * (quota, disabled storage): persistence is best-effort. */\nexport interface KeyValueStorage {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\n/** Prefix of every key the runtime writes, so adapters can scope reads (e.g.\n * preloading only MicroSurveys keys from an async store). */\nexport const STORAGE_KEY_PREFIX = \"com.microsurveys.\";\n\n/** In-memory storage (nothing survives a restart). Useful for tests. */\nexport function memoryStorage(initial?: Record<string, string>): KeyValueStorage {\n const map = new Map<string, string>(Object.entries(initial ?? {}));\n return {\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => void map.set(key, value),\n removeItem: (key) => void map.delete(key),\n };\n}\n\n/** A v4 UUID, using `crypto.randomUUID` when available with a safe fallback. */\nexport function uuid(): string {\n try {\n // Hermes has no `crypto` unless a polyfill (e.g. expo-crypto) installs one.\n const crypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (crypto && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n /* fall through */\n }\n // RFC-4122-ish fallback.\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/** Current time in **seconds** since the Unix epoch — matches the iOS runtime's\n * `Date.timeIntervalSince1970`, which all persisted timestamps use. */\nexport function nowSeconds(): number {\n return Date.now() / 1000;\n}\n","//\n// outbox.ts\n//\n// FIFO, persisted queue of pending POSTs (impressions/responses), so\n// ingest survives offline reloads and flushes on the next start. Each entry\n// carries a UUID so it can be removed after a successful send. Port of the\n// `Outbox` in iOS `APIClient.swift`.\n//\n\nimport { uuid } from \"./storage\";\nimport type { KeyValueStorage } from \"./storage\";\n\nconst KEY = \"com.microsurveys.outbox\";\nconst MAX_ENTRIES = 200;\n\nexport interface OutboxEntry {\n id: string;\n path: string; // e.g. \"/api/sdk/impressions\"\n body: string; // pre-encoded JSON body\n}\n\nexport class Outbox {\n constructor(private readonly kv: KeyValueStorage) {}\n\n private read(): OutboxEntry[] {\n const data = this.kv.getItem(KEY);\n if (!data) return [];\n try {\n const parsed = JSON.parse(data) as OutboxEntry[];\n return Array.isArray(parsed) ? parsed : [];\n } catch {\n return [];\n }\n }\n\n private write(entries: OutboxEntry[]): void {\n this.kv.setItem(KEY, JSON.stringify(entries));\n }\n\n enqueue(path: string, body: string): void {\n const entries = this.read();\n entries.push({ id: uuid(), path, body });\n if (entries.length > MAX_ENTRIES) entries.splice(0, entries.length - MAX_ENTRIES);\n this.write(entries);\n }\n\n snapshot(): OutboxEntry[] {\n return this.read();\n }\n\n remove(id: string): void {\n this.write(this.read().filter((e) => e.id !== id));\n }\n}\n","//\n// types.ts\n//\n// TypeScript mirror of the SDK API wire contract and the iOS\n// `Models.swift` / `RuntimeModels.swift`. Also includes the loose→typed config\n// normalization (port of `Question.buildConfig` / `Trigger.init(from:)`) so the\n// rest of the engine works against fully-defaulted values.\n//\n\n// ── JSON ────────────────────────────────────────────────────────────────────\n\nexport type Json = string | number | boolean | null | Json[] | { [key: string]: Json };\nexport type JsonObject = { [key: string]: Json };\n\n// ── Questions ───────────────────────────────────────────────────────────────\n\nexport type QuestionType =\n | \"NPS\"\n | \"CES\"\n | \"CSAT_STAR\"\n | \"CSAT_EMOJI\"\n | \"THUMBS\"\n | \"SINGLE_CHOICE\"\n | \"OPEN_TEXT\";\n\nexport interface EmojiOption {\n value: string;\n emoji: string;\n label?: string;\n}\n\nexport interface ChoiceOption {\n value: string;\n label: string;\n}\n\n/** Typed, defaulted per-type config — port of iOS `QuestionConfig`. NPS and CES\n * share the numeric-scale shape; `type` disambiguates defaults + answer shape. */\nexport type QuestionConfig =\n | { kind: \"scale\"; min: number; max: number; minLabel?: string; maxLabel?: string }\n | { kind: \"stars\"; count: number }\n | { kind: \"emoji\"; options: EmojiOption[] }\n | { kind: \"thumbs\" }\n | { kind: \"singleChoice\"; options: ChoiceOption[] }\n | { kind: \"openText\"; placeholder?: string; maxLength?: number };\n\nexport interface Question {\n id: string;\n order: number;\n type: QuestionType;\n prompt: string;\n required: boolean;\n config: QuestionConfig;\n}\n\n// ── Triggers ──────────────────────────────────────────────────────────────\n\nexport type TriggerType = \"SINGLE\" | \"SEQUENCE\";\n\nexport interface TriggerStep {\n order: number;\n event: string;\n match: JsonObject;\n}\n\nexport interface Trigger {\n id: string;\n type: TriggerType;\n delaySeconds: number;\n sequenceWindowSeconds: number | null;\n fireEvery: number;\n warmupCount: number;\n steps: TriggerStep[];\n}\n\n// ── Survey + config envelope ─────────────────────────────────────────────────\n\nexport interface Survey {\n id: string;\n name: string;\n questions: Question[];\n audienceMatch?: JsonObject | null;\n samplePercent?: number | null;\n maxPerUserDays?: number | null;\n startsAt?: string | null;\n endsAt?: string | null;\n triggers?: Trigger[] | null;\n /** `false` = required: hide the close button + block scrim/swipe dismissal. */\n dismissible?: boolean | null;\n /** `\"sheet\"` | `\"dialog\"` | null (inherit the project theme's position). */\n presentation?: string | null;\n successMessage?: string | null;\n /** Platform targeting for auto-presentation. Empty/absent = all platforms.\n * The engine skips a survey whose list is non-empty and excludes the client's\n * platform. Explicit inline `<MicroSurvey>` embeds ignore this. */\n platforms?: string[] | null;\n}\n\nexport interface SDKConfig {\n projectId: string;\n fetchedAt?: string | null;\n theme: ProjectTheme | null;\n surveys: Survey[];\n /** The project turned event signals on: count tracked events and upload the\n * counts (see eventCounter.ts). Absent on older servers, which means off. */\n eventSignals: boolean;\n /** Hashes of the project's test devices for the live debugger (see debug.ts).\n * Empty when none are set, or on older servers. */\n debugUsers: string[];\n /** The project has server events waiting to be picked up: check the mailbox\n * (`POST /api/sdk/pending`). Absent on older servers, which means off. */\n pendingEvents: boolean;\n /** Trigger event names that arrive by server stream rather than from the app.\n * A sequence waiting on one of them as its next step checks more often. */\n serverEvents: string[];\n}\n\n/** Brand-level survey appearance (API-CONTRACT §Theme). All keys optional. */\nexport interface ProjectTheme {\n accent?: string;\n accentText?: string;\n background?: string;\n surface?: string;\n text?: string;\n secondaryText?: string;\n border?: string;\n cornerRadius?: number | null;\n controlRadius?: number;\n controlPill?: boolean;\n controlHeight?: number;\n spacing?: number;\n textScale?: number;\n position?: string; // \"bottom\" | \"center\"\n alignment?: string; // \"leading\" | \"center\"\n font?: string;\n titleSize?: number;\n titleWeight?: string;\n titleLineHeight?: number;\n titleLetterSpacing?: number;\n}\n\n// ── Device context ───────────────────────────────────────────────────────────\n\n/** Where a survey was shown, sent with impressions and responses so results can\n * be broken down by platform, release and language (API-CONTRACT \"Device\n * context\"). Every field is optional; unknown ones are left out. */\nexport interface DeviceContext {\n platform?: string;\n appVersion?: string;\n osVersion?: string;\n locale?: string;\n}\n\n// ── Identity ─────────────────────────────────────────────────────────────────\n\nexport interface Identity {\n /** Amplitude user id, forwarded by an analytics plugin (e.g. React Native's). */\n amplitudeUserId?: string;\n /** Amplitude device id, forwarded by an analytics plugin. */\n amplitudeDeviceId?: string;\n /** Host-supplied id from `identify()`, for non-Amplitude integrations. */\n hostUserId?: string;\n /** Stable, persisted anonymous id — the final fallback. */\n anonymousId: string;\n /** User properties used for `audienceMatch`. */\n userProperties: JsonObject;\n}\n\n/** `endUserId` = Amplitude userId ?? deviceId ?? host id ?? anonymous id — the\n * same order as iOS `MSIdentity.endUserId`. */\nexport function endUserIdOf(identity: Identity): string {\n return identity.amplitudeUserId ?? identity.amplitudeDeviceId ?? identity.hostUserId ?? identity.anonymousId;\n}\n\n// ── Answers / result ─────────────────────────────────────────────────────────\n\n/** The exact JSON submitted under `answers[].value`, keyed per question type\n * (API-CONTRACT §Answer value shapes). */\nexport type AnswerValue =\n | { value: number } // NPS / CES / CSAT_STAR\n | { value: \"up\" | \"down\" } // THUMBS\n | { value: string } // CSAT_EMOJI (chosen option value)\n | { choice: string } // SINGLE_CHOICE\n | { text: string }; // OPEN_TEXT\n\nexport interface SurveyAnswer {\n questionId: string;\n value: AnswerValue;\n}\n\n/** Outcome handed back when the survey UI closes. */\nexport interface SurveyResult {\n answers: SurveyAnswer[];\n /** `true` if the user advanced through and submitted the final question. */\n completed: boolean;\n /** `true` if closed/dismissed before completing. */\n dismissed: boolean;\n}\n\n// ── Persisted trigger state (port of Persistence.swift structs) ──────────────\n\nexport interface TriggerRecord {\n /** Next sequence step index expected (0 = waiting for step 0). */\n stepIndex: number;\n /** Unix seconds when step 0 was matched, to enforce `sequenceWindowSeconds`. */\n startedAt: number | null;\n /** How many times the trigger's full condition has been satisfied. */\n satisfiedCount: number;\n}\n\nexport interface SurveyRecord {\n /** Unix seconds the survey was last shown to this user, for `maxPerUserDays`. */\n lastShownAt?: number | null;\n /** Sticky sampling decision (computed once, reused forever). */\n sampleDecision?: boolean | null;\n}\n\nexport interface UserTriggerState {\n triggers: Record<string, TriggerRecord>;\n surveys: Record<string, SurveyRecord>;\n}\n\nexport function newTriggerRecord(): TriggerRecord {\n return { stepIndex: 0, startedAt: null, satisfiedCount: 0 };\n}\n\nexport function newUserTriggerState(): UserTriggerState {\n return { triggers: {}, surveys: {} };\n}\n\n// ── Config parsing / normalization (port of the Codable inits) ───────────────\n\nfunction asObject(v: unknown): Record<string, unknown> {\n return v && typeof v === \"object\" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};\n}\n\nfunction numOr(v: unknown, fallback: number): number {\n return typeof v === \"number\" && Number.isFinite(v) ? v : fallback;\n}\n\nfunction strOrUndef(v: unknown): string | undefined {\n return typeof v === \"string\" ? v : undefined;\n}\n\n// Upper bounds on what a config can make the SDK draw. A scale, star row or option list is drawn\n// one control per item, so an absurd value (count: 1000000000) would freeze the app. Real surveys\n// sit far below these; the server applies the same bounds before sending the config.\nconst MAX_SCALE_POINTS = 101;\nconst MAX_SCALE_ABS = 1000;\nconst MAX_STARS = 100;\nconst MAX_OPTIONS = 100;\n\nconst QUESTION_TYPES: readonly QuestionType[] = [\"NPS\", \"CES\", \"CSAT_STAR\", \"CSAT_EMOJI\", \"THUMBS\", \"SINGLE_CHOICE\", \"OPEN_TEXT\"];\n\nfunction boundedScale(min: number, max: number): { min: number; max: number } {\n const lo = Math.min(Math.max(min, -MAX_SCALE_ABS), MAX_SCALE_ABS);\n let hi = Math.min(Math.max(max, -MAX_SCALE_ABS), MAX_SCALE_ABS);\n if (hi - lo > MAX_SCALE_POINTS - 1) hi = lo + MAX_SCALE_POINTS - 1;\n return { min: lo, max: hi };\n}\n\nfunction boundedOptions(raw: unknown): unknown[] {\n return Array.isArray(raw) ? raw.slice(0, MAX_OPTIONS) : [];\n}\n\nfunction normalizeConfig(type: QuestionType, raw: Record<string, unknown>): QuestionConfig {\n switch (type) {\n case \"NPS\":\n return { kind: \"scale\", ...boundedScale(numOr(raw.min, 0), numOr(raw.max, 10)), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };\n case \"CES\":\n return { kind: \"scale\", ...boundedScale(numOr(raw.min, 1), numOr(raw.max, 7)), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };\n case \"CSAT_STAR\":\n return { kind: \"stars\", count: Math.min(numOr(raw.count, 5), MAX_STARS) };\n case \"CSAT_EMOJI\": {\n const opts = boundedOptions(raw.options);\n const options: EmojiOption[] = opts.map((o) => {\n const oo = asObject(o);\n return { value: String(oo.value ?? \"\"), emoji: typeof oo.emoji === \"string\" ? oo.emoji : \"\", label: strOrUndef(oo.label) };\n });\n return { kind: \"emoji\", options };\n }\n case \"THUMBS\":\n return { kind: \"thumbs\" };\n case \"SINGLE_CHOICE\": {\n const opts = boundedOptions(raw.options);\n const options: ChoiceOption[] = opts.map((o) => {\n const oo = asObject(o);\n const value = String(oo.value ?? \"\");\n return { value, label: typeof oo.label === \"string\" ? oo.label : value };\n });\n return { kind: \"singleChoice\", options };\n }\n case \"OPEN_TEXT\":\n return { kind: \"openText\", placeholder: strOrUndef(raw.placeholder), maxLength: typeof raw.maxLength === \"number\" ? raw.maxLength : undefined };\n }\n}\n\nfunction normalizeQuestion(raw: Record<string, unknown>): Question | null {\n const id = strOrUndef(raw.id);\n const type = strOrUndef(raw.type) as QuestionType | undefined;\n const prompt = strOrUndef(raw.prompt);\n if (!id || !type || prompt === undefined) return null;\n return {\n id,\n order: numOr(raw.order, 0),\n type,\n prompt,\n required: raw.required === true,\n config: normalizeConfig(type, asObject(raw.config)),\n };\n}\n\nfunction normalizeTrigger(raw: Record<string, unknown>): Trigger | null {\n const id = strOrUndef(raw.id);\n if (!id) return null;\n const type: TriggerType = raw.type === \"SEQUENCE\" ? \"SEQUENCE\" : \"SINGLE\";\n const steps: TriggerStep[] = (Array.isArray(raw.steps) ? raw.steps : [])\n .map((s) => {\n const so = asObject(s);\n const event = strOrUndef(so.event);\n if (!event) return null;\n return { order: numOr(so.order, 0), event, match: asObject(so.match) as JsonObject };\n })\n .filter((s): s is TriggerStep => s !== null);\n return {\n id,\n type,\n delaySeconds: numOr(raw.delaySeconds, 0),\n sequenceWindowSeconds: typeof raw.sequenceWindowSeconds === \"number\" ? raw.sequenceWindowSeconds : null,\n fireEvery: numOr(raw.fireEvery, 1),\n warmupCount: numOr(raw.warmupCount, 0),\n steps,\n };\n}\n\nfunction normalizeSurvey(raw: Record<string, unknown>): Survey | null {\n const id = strOrUndef(raw.id);\n const name = strOrUndef(raw.name);\n if (!id || name === undefined) return null;\n const rawQuestions = Array.isArray(raw.questions) ? raw.questions : [];\n const rawTriggers = Array.isArray(raw.triggers) ? raw.triggers : [];\n // Skip a survey this SDK version can't show (a newer question or trigger type):\n // there's no renderer for the question, and the trigger would fire by the wrong rule.\n if (\n rawQuestions.some((q) => !QUESTION_TYPES.includes(asObject(q).type as QuestionType)) ||\n rawTriggers.some((t) => { const type = asObject(t).type; return type != null && type !== \"SINGLE\" && type !== \"SEQUENCE\"; })\n ) return null;\n const questions = rawQuestions\n .map((q) => normalizeQuestion(asObject(q)))\n .filter((q): q is Question => q !== null);\n const triggers = rawTriggers\n .map((t) => normalizeTrigger(asObject(t)))\n .filter((t): t is Trigger => t !== null);\n return {\n id,\n name,\n questions,\n audienceMatch: (raw.audienceMatch as JsonObject | null) ?? null,\n samplePercent: typeof raw.samplePercent === \"number\" ? raw.samplePercent : null,\n maxPerUserDays: typeof raw.maxPerUserDays === \"number\" ? raw.maxPerUserDays : null,\n startsAt: strOrUndef(raw.startsAt) ?? null,\n endsAt: strOrUndef(raw.endsAt) ?? null,\n triggers,\n dismissible: typeof raw.dismissible === \"boolean\" ? raw.dismissible : null,\n presentation: strOrUndef(raw.presentation) ?? null,\n successMessage: strOrUndef(raw.successMessage) ?? null,\n platforms: Array.isArray(raw.platforms) ? raw.platforms.filter((p): p is string => typeof p === \"string\") : null,\n };\n}\n\n/** Parse a raw `/api/sdk/config` JSON string into a fully-normalized `SDKConfig`.\n * Returns `null` if the payload is unusable. Lenient by design — the SDK must\n * keep working against an older/newer server shape. */\nexport function parseConfig(rawText: string): SDKConfig | null {\n let root: Record<string, unknown>;\n try {\n root = asObject(JSON.parse(rawText));\n } catch {\n return null;\n }\n const projectId = strOrUndef(root.projectId);\n if (!projectId) return null;\n const surveys = (Array.isArray(root.surveys) ? root.surveys : [])\n .map((s) => normalizeSurvey(asObject(s)))\n .filter((s): s is Survey => s !== null);\n const theme = root.theme && typeof root.theme === \"object\" && !Array.isArray(root.theme) ? (root.theme as ProjectTheme) : null;\n return { projectId, fetchedAt: strOrUndef(root.fetchedAt) ?? null, theme,\n surveys,\n eventSignals: root.eventSignals === true,\n debugUsers: Array.isArray(root.debugUsers) ? root.debugUsers.filter((h): h is string => typeof h === \"string\") : [],\n pendingEvents: root.pendingEvents === true,\n serverEvents: Array.isArray(root.serverEvents) ? root.serverEvents.filter((n): n is string => typeof n === \"string\") : [],\n };\n}\n","//\n// apiClient.ts\n//\n// `fetch`-based client for the SDK endpoints plus outbox flush. Every\n// impression/response carries a UUID `clientId` so the server upserts and\n// retries never duplicate (API-CONTRACT §Idempotency). Port of iOS `APIClient`.\n//\n\nimport { Outbox } from \"./outbox\";\nimport { uuid } from \"./storage\";\nimport type { KeyValueStorage } from \"./storage\";\nimport type { EventCount } from \"./eventCounter\";\nimport type { DebugEntry } from \"./debug\";\nimport { parseConfig } from \"./types\";\nimport type { SDKConfig, SurveyAnswer, JsonObject, DeviceContext } from \"./types\";\n\nconst API_VERSION = \"2026-06-30\";\n\nexport type ConfigFetchResult =\n | { kind: \"notModified\" }\n | { kind: \"config\"; rawText: string; config: SDKConfig | null; etag: string | null };\n\n/** One server event waiting in the mailbox (API-CONTRACT §6). */\nexport interface PendingEvent {\n id: string;\n name: string;\n properties: Record<string, unknown>;\n /** ISO 8601: when it happened, not when it arrived. */\n occurredAt: string;\n}\n\n/** The most events `/api/sdk/pending` returns per call. */\nexport const PENDING_PAGE_SIZE = 50;\n\nexport class ApiClient {\n private readonly apiKey: string;\n private readonly baseURL: string;\n private readonly outbox: Outbox;\n private isFlushing = false;\n\n constructor(apiKey: string, baseURL: string, storage: KeyValueStorage) {\n this.apiKey = apiKey;\n this.outbox = new Outbox(storage);\n // Normalize: no trailing slash so `${base}${path}` is clean.\n this.baseURL = baseURL.replace(/\\/+$/, \"\");\n }\n\n // ── Config ─────────────────────────────────────────────────────────────────\n\n /** `GET /api/sdk/config` with optional `If-None-Match`. Resolves `notModified`\n * on 304 so the caller keeps its cache. Throws on network/5xx errors. */\n async fetchConfig(etag: string | null): Promise<ConfigFetchResult> {\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n \"MS-Api-Version\": API_VERSION,\n };\n if (etag) headers[\"If-None-Match\"] = etag;\n\n const res = await fetch(this.endpoint(\"/api/sdk/config\"), { method: \"GET\", headers });\n if (res.status === 304) return { kind: \"notModified\" };\n if (!res.ok) throw new Error(`config fetch failed: ${res.status}`);\n\n const rawText = await res.text();\n return { kind: \"config\", rawText, config: parseConfig(rawText), etag: res.headers.get(\"ETag\") };\n }\n\n // ── Server events mailbox ───────────────────────────────────────────────────\n\n /** `POST /api/sdk/pending`: the server events waiting for this user, oldest\n * first. Each is handed out once, so this is not queued in the outbox. Resolves\n * `[]` without a request when there's no id to ask for. Throws on network/HTTP\n * errors; malformed entries are dropped. */\n async fetchPending(ids: { userId: string | null; deviceId: string | null }): Promise<PendingEvent[]> {\n const body: Record<string, string> = {};\n if (ids.userId) body.userId = ids.userId;\n if (ids.deviceId) body.deviceId = ids.deviceId;\n if (Object.keys(body).length === 0) return [];\n\n const res = await fetch(this.endpoint(\"/api/sdk/pending\"), {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"MS-Api-Version\": API_VERSION,\n \"Content-Type\": \"application/json; charset=utf-8\",\n },\n body: JSON.stringify(body),\n });\n if (!res.ok) throw new Error(`pending fetch failed: ${res.status}`);\n\n const root = (await res.json()) as { events?: unknown };\n const events = Array.isArray(root?.events) ? root.events : [];\n return events.flatMap((raw): PendingEvent[] => {\n const e = raw as Record<string, unknown> | null;\n if (!e || typeof e.id !== \"string\" || typeof e.name !== \"string\" || typeof e.occurredAt !== \"string\") return [];\n if (Number.isNaN(Date.parse(e.occurredAt))) return [];\n const properties =\n e.properties && typeof e.properties === \"object\" && !Array.isArray(e.properties)\n ? (e.properties as Record<string, unknown>)\n : {};\n return [{ id: e.id, name: e.name, properties, occurredAt: e.occurredAt }];\n });\n }\n\n // ── Impressions / responses ─────────────────────────────────────────────────\n\n /** Queues the impression and returns its `clientId`, so the response from the\n * same showing can point back to it. */\n recordImpression(input: {\n surveyId: string;\n triggerId: string | null;\n endUserId: string;\n shownAt: Date;\n dismissed: boolean;\n context: DeviceContext;\n }): string {\n const clientId = uuid();\n const payload = {\n clientId,\n surveyId: input.surveyId,\n triggerId: input.triggerId ?? undefined,\n endUserId: input.endUserId,\n shownAt: input.shownAt.toISOString(),\n dismissed: input.dismissed,\n context: input.context,\n };\n this.enqueue(\"/api/sdk/impressions\", { impressions: [payload] });\n return clientId;\n }\n\n recordResponse(input: {\n surveyId: string;\n endUserId: string;\n completed: boolean;\n submittedAt: Date;\n userProps: JsonObject;\n impressionId: string;\n triggerId: string | null;\n context: DeviceContext;\n answers: SurveyAnswer[];\n }): void {\n const payload = {\n clientId: uuid(),\n surveyId: input.surveyId,\n endUserId: input.endUserId,\n completed: input.completed,\n submittedAt: input.submittedAt.toISOString(),\n userProps: input.userProps,\n impressionId: input.impressionId,\n triggerId: input.triggerId ?? undefined,\n context: input.context,\n answers: input.answers,\n };\n this.enqueue(\"/api/sdk/responses\", { responses: [payload] });\n }\n\n // ── Event signals ─────────────────────────────────────────────────────────\n\n /** Queues one upload window of event counts. No clientId: a re-sent batch\n * can count twice, which is fine for \"last seen\" and trend lines. */\n recordEventCounts(events: EventCount[], context: DeviceContext & { sdkVersion: string }): void {\n if (events.length === 0) return;\n this.enqueue(\"/api/sdk/events\", { events, context });\n }\n\n // ── Live debugger ─────────────────────────────────────────────────────────\n\n /** Sends one debugger entry from a test device. */\n recordDebug(entry: DebugEntry, endUserId: string, context: DeviceContext & { sdkVersion: string }): void {\n this.enqueue(\"/api/sdk/debug\", { entries: [entry], endUserId, context });\n }\n\n private enqueue(path: string, value: unknown): void {\n this.outbox.enqueue(path, JSON.stringify(value));\n void this.flush();\n }\n\n // ── Flush ────────────────────────────────────────────────────────────────────\n\n /** POSTs queued entries in order. Stops at the first retryable failure (likely\n * offline) and leaves the rest for next time. Entries queued while a flush is\n * running are sent by the same flush, so nothing waits for the next event.\n * Idempotency keys make re-sends safe. Never throws. */\n async flush(): Promise<void> {\n if (this.isFlushing) return;\n this.isFlushing = true;\n try {\n // Guards against re-sending an entry whose removal didn't persist (storage full).\n const sent = new Set<string>();\n for (;;) {\n const pending = this.outbox.snapshot().filter((e) => !sent.has(e.id));\n if (pending.length === 0) break;\n let failed = false;\n for (const entry of pending) {\n try {\n await this.post(entry.path, entry.body);\n this.outbox.remove(entry.id);\n sent.add(entry.id);\n } catch {\n failed = true; // network/server problem — retry on the next flush\n break;\n }\n }\n if (failed) break;\n }\n } finally {\n this.isFlushing = false;\n }\n }\n\n private async post(path: string, body: string): Promise<void> {\n const res = await fetch(this.endpoint(path), {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"MS-Api-Version\": API_VERSION,\n \"Content-Type\": \"application/json; charset=utf-8\",\n },\n body,\n });\n // 429/5xx → throw to retry later. Other 4xx are permanent for this body;\n // treat as done so we don't wedge the queue (matches iOS retry rules).\n if (res.status === 429 || (res.status >= 500 && res.status < 600)) {\n throw new Error(`retryable ${res.status}`);\n }\n }\n\n private endpoint(path: string): string {\n return this.baseURL + path;\n }\n}\n","//\n// persistence.ts\n//\n// On-device state so the SDK works immediately/offline and trigger progress\n// survives reloads:\n// • ConfigStore — the latest config JSON + parsed surveys/theme + ETag.\n// • TriggerStateStore — per-endUserId sequence progress, occurrence counters,\n// sticky sampling, and last-shown timestamps for the cap.\n//\n// Ports iOS `Persistence.swift`, backed by a `KeyValueStorage` instead of\n// UserDefaults.\n//\n\nimport type { KeyValueStorage } from \"./storage\";\nimport { parseConfig, newUserTriggerState } from \"./types\";\nimport type { SDKConfig, Survey, ProjectTheme, UserTriggerState } from \"./types\";\n\nconst CONFIG_KEY = \"com.microsurveys.config.cache\";\nconst STATE_PREFIX = \"com.microsurveys.triggerstate.\";\n\ninterface PersistedConfig {\n rawConfig: string; // raw response body — parsed losslessly on load\n etag: string | null;\n storedAt: number; // ms epoch\n}\n\n/** Persists the most recent `/api/sdk/config` result so the SDK can evaluate\n * triggers and render surveys immediately on load, before/without a network\n * refresh. We store the raw response text and re-parse it (lossless). */\nexport class ConfigStore {\n private persisted: PersistedConfig | null = null;\n private parsed: SDKConfig | null = null;\n\n constructor(private readonly kv: KeyValueStorage) {\n const data = kv.getItem(CONFIG_KEY);\n if (data) {\n try {\n const entry = JSON.parse(data) as PersistedConfig;\n if (entry && typeof entry.rawConfig === \"string\") {\n this.persisted = entry;\n this.parsed = parseConfig(entry.rawConfig);\n }\n } catch {\n /* corrupt cache — ignore */\n }\n }\n }\n\n get config(): SDKConfig | null {\n return this.parsed;\n }\n\n get surveys(): Survey[] {\n return this.parsed?.surveys ?? [];\n }\n\n get theme(): ProjectTheme | null {\n return this.parsed?.theme ?? null;\n }\n\n get eventSignals(): boolean {\n return this.parsed?.eventSignals ?? false;\n }\n\n get projectId(): string | null {\n return this.parsed?.projectId ?? null;\n }\n\n get debugUsers(): string[] {\n return this.parsed?.debugUsers ?? [];\n }\n\n get pendingEvents(): boolean {\n return this.parsed?.pendingEvents ?? false;\n }\n\n get serverEvents(): string[] {\n return this.parsed?.serverEvents ?? [];\n }\n\n get etag(): string | null {\n return this.persisted?.etag ?? null;\n }\n\n /** When the cached config was last written (ms epoch), for TTL checks. */\n get storedAt(): number | null {\n return this.persisted?.storedAt ?? null;\n }\n\n /** Persists the raw config response and refreshes the in-memory parse. */\n save(rawConfig: string, etag: string | null): void {\n const entry: PersistedConfig = { rawConfig, etag, storedAt: Date.now() };\n this.persisted = entry;\n this.parsed = parseConfig(rawConfig);\n this.kv.setItem(CONFIG_KEY, JSON.stringify(entry));\n }\n}\n\n/** Loads/saves `UserTriggerState` keyed by `endUserId`. Cheap enough to read &\n * rewrite the whole blob per evaluation for MVP volumes. */\nexport class TriggerStateStore {\n constructor(private readonly kv: KeyValueStorage) {}\n\n load(endUserId: string): UserTriggerState {\n const data = this.kv.getItem(STATE_PREFIX + endUserId);\n if (!data) return newUserTriggerState();\n try {\n const parsed = JSON.parse(data) as UserTriggerState;\n return { triggers: parsed.triggers ?? {}, surveys: parsed.surveys ?? {} };\n } catch {\n return newUserTriggerState();\n }\n }\n\n save(endUserId: string, state: UserTriggerState): void {\n this.kv.setItem(STATE_PREFIX + endUserId, JSON.stringify(state));\n }\n\n reset(endUserId: string): void {\n this.kv.removeItem(STATE_PREFIX + endUserId);\n }\n}\n","//\n// identity.ts\n//\n// Maintains the current `Identity` snapshot the engine evaluates against,\n// merging signals from an analytics SDK (Amplitude userId/deviceId/identify\n// properties) and the host (`identify`). Mints/persists a stable anonymous id\n// so cap + trigger state stay consistent across reloads before any user is\n// identified. Port of iOS `IdentityStore`.\n//\n\nimport { uuid } from \"./storage\";\nimport type { KeyValueStorage } from \"./storage\";\nimport type { Identity, Json, JsonObject } from \"./types\";\n\nconst ANON_KEY = \"com.microsurveys.anonymousId\";\nconst PROPS_KEY = \"com.microsurveys.userProperties\";\n\n/** An identity update from an analytics SDK (e.g. the Amplitude plugin). Any\n * field may be absent when unknown; absent fields leave the current value. */\nexport interface AnalyticsIdentity {\n userId?: string | null;\n deviceId?: string | null;\n /** Properties to merge into the user properties (`$set` semantics). */\n userProperties?: Record<string, unknown> | null;\n /** Properties to set only where not already present (`$setOnce` semantics). */\n setOnceProperties?: Record<string, unknown> | null;\n /** Property keys to remove (`$unset` semantics). */\n unsetProperties?: string[] | null;\n}\n\nexport class IdentityStore {\n private identity: Identity;\n\n constructor(private readonly kv: KeyValueStorage) {\n let anon = kv.getItem(ANON_KEY);\n if (!anon) {\n anon = \"anon_\" + uuid();\n kv.setItem(ANON_KEY, anon);\n }\n let userProperties: JsonObject = {};\n const props = kv.getItem(PROPS_KEY);\n if (props) {\n try {\n const parsed = JSON.parse(props) as JsonObject;\n if (parsed && typeof parsed === \"object\") userProperties = parsed;\n } catch {\n /* ignore */\n }\n }\n this.identity = { anonymousId: anon, userProperties };\n }\n\n /** Thread-safe not required (single-threaded JS); returns a shallow snapshot. */\n snapshot(): Identity {\n return { ...this.identity, userProperties: { ...this.identity.userProperties } };\n }\n\n /** Apply a host `identify(id, properties)` call. Merges properties. */\n setUser(id: string | null | undefined, properties?: Record<string, unknown>): void {\n if (id) this.identity.hostUserId = id;\n if (properties) {\n for (const key of Object.keys(properties)) {\n this.identity.userProperties[key] = toJson(properties[key]);\n }\n this.persistProperties();\n }\n }\n\n /** Merge an analytics identity update. Called per event, so it only persists\n * when the properties actually changed. */\n updateFromAnalytics(update: AnalyticsIdentity): void {\n if (update.userId) this.identity.amplitudeUserId = update.userId;\n if (update.deviceId) this.identity.amplitudeDeviceId = update.deviceId;\n let changed = false;\n if (update.userProperties) {\n for (const key of Object.keys(update.userProperties)) {\n const value = toJson(update.userProperties[key]);\n if (JSON.stringify(this.identity.userProperties[key]) !== JSON.stringify(value)) {\n this.identity.userProperties[key] = value;\n changed = true;\n }\n }\n }\n if (update.setOnceProperties) {\n for (const key of Object.keys(update.setOnceProperties)) {\n if (key in this.identity.userProperties) continue;\n this.identity.userProperties[key] = toJson(update.setOnceProperties[key]);\n changed = true;\n }\n }\n for (const key of update.unsetProperties ?? []) {\n if (key in this.identity.userProperties) {\n delete this.identity.userProperties[key];\n changed = true;\n }\n }\n if (changed) this.persistProperties();\n }\n\n private persistProperties(): void {\n this.kv.setItem(PROPS_KEY, JSON.stringify(this.identity.userProperties));\n }\n}\n\n/** Best-effort conversion of an arbitrary host value into a JSON value, for\n * snapshotting user properties (port of iOS `JSONValue(any:)`). */\nfunction toJson(value: unknown): Json {\n if (value === null || value === undefined) return null;\n switch (typeof value) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n return value;\n case \"object\":\n if (Array.isArray(value)) return value.map(toJson);\n return Object.fromEntries(Object.entries(value as Record<string, unknown>).map(([k, v]) => [k, toJson(v)]));\n default:\n return String(value);\n }\n}\n","//\n// sampling.ts\n//\n// Pure helpers used by the trigger engine: deterministic 32-bit FNV-1a sampling\n// and the equality `match` / `audienceMatch` evaluator. Faithful port of the iOS\n// `Sampling.swift` — the same hash on both platforms so bucketing is stable and\n// reproducible cross-platform.\n//\n\nimport type { Json, JsonObject, TriggerStep } from \"./types\";\n\n// ── Deterministic sampling ───────────────────────────────────────────────────\n\nconst encoder = typeof TextEncoder !== \"undefined\" ? new TextEncoder() : null;\n\n/** UTF-8 bytes of `s`, matching Swift's `string.utf8`. Exported for tests. */\nexport function utf8Bytes(s: string, useEncoder = true): Uint8Array {\n if (encoder && useEncoder) return encoder.encode(s);\n // Fallback if TextEncoder is unavailable (older Hermes). Iterates code points so\n // astral characters (surrogate pairs) encode to 4 bytes exactly like Swift.\n const out: number[] = [];\n for (const ch of s) {\n const c = ch.codePointAt(0)!;\n if (c < 0x80) out.push(c);\n else if (c < 0x800) {\n out.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));\n } else if (c < 0x10000) {\n out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n } else {\n out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n }\n }\n return Uint8Array.from(out);\n}\n\n/** 32-bit FNV-1a hash of `s`'s UTF-8 bytes. Returns an unsigned 32-bit integer. */\nexport function fnv1a32(s: string): number {\n let hash = 0x811c9dc5; // FNV offset basis\n const bytes = utf8Bytes(s);\n for (let i = 0; i < bytes.length; i++) {\n hash ^= bytes[i]!;\n // FNV prime 0x01000193, 32-bit wrapping multiply.\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n}\n\n/** `inSample = FNV-1a(endUserId + \":\" + surveyId) % 100 < samplePercent`.\n * `samplePercent` clamps: `>= 100` always in, `<= 0` always out. */\nexport function inSample(endUserId: string, surveyId: string, samplePercent: number): boolean {\n if (samplePercent >= 100) return true;\n if (samplePercent <= 0) return false;\n const bucket = fnv1a32(`${endUserId}:${surveyId}`) % 100;\n return bucket < samplePercent;\n}\n\n// ── Equality matching ────────────────────────────────────────────────────────\n\n/** Formats a number as an integer when it has no fractional part, so `42` and\n * `42.0` compare equal (port of iOS `numberString`). */\nfunction numberString(n: number): string {\n if (Number.isFinite(n) && Math.trunc(n) === n && Math.abs(n) < 1e15) {\n return String(Math.trunc(n));\n }\n return String(n);\n}\n\n/** Stringifies a scalar for comparison. Returns `null` for values that never\n * participate in an equality match (null, objects, arrays, undefined). */\nexport function stringify(value: unknown): string | null {\n switch (typeof value) {\n case \"string\":\n return value;\n case \"boolean\":\n return value ? \"true\" : \"false\";\n case \"number\":\n return numberString(value);\n default:\n return null;\n }\n}\n\n/** True iff every key in `filter` is present in `properties` with an equal\n * (stringified) value. Empty filter ⇒ always true. */\nexport function matches(filter: JsonObject, properties: Record<string, unknown>): boolean {\n for (const key of Object.keys(filter)) {\n const expectedStr = stringify(filter[key]);\n if (expectedStr === null) return false;\n const actualStr = stringify(properties[key]);\n if (actualStr === null) return false;\n if (expectedStr !== actualStr) return false;\n }\n return true;\n}\n\n/** True iff `eventName` equals `step.event` AND `step.match ⊆ properties`. */\nexport function eventMatchesStep(eventName: string, properties: Record<string, unknown>, step: TriggerStep): boolean {\n if (eventName !== step.event) return false;\n return matches(step.match, properties);\n}\n\n/** Audience check: `audience ⊆ userProperties` by stringified equality. */\nexport function audienceMatches(audience: JsonObject, userProperties: Record<string, Json>): boolean {\n return matches(audience, userProperties);\n}\n","//\n// triggerSequencer.ts\n//\n// Pure state machine advancing a trigger's SINGLE/SEQUENCE progress on one\n// incoming event. No clock, no storage, no queues — so the sequence + window\n// ordering rules are unit-testable. Faithful port of iOS `TriggerSequencer`.\n//\n\nimport { eventMatchesStep } from \"./sampling\";\nimport type { Trigger, TriggerRecord } from \"./types\";\n\nexport interface AdvanceResult {\n record: TriggerRecord;\n satisfied: boolean;\n}\n\n/** True iff the sequence window has lapsed since step 0 matched. */\nexport function windowExpired(window: number | null, startedAt: number | null, nowT: number): boolean {\n if (window === null || window <= 0 || startedAt === null) return false;\n return nowT - startedAt > window;\n}\n\n/** Advances `record` for one event. On satisfaction, bumps `satisfiedCount` and\n * resets the sequence progress. Returns a new record (input is not mutated).\n * `nowT` is when the event happened: the current time for a live event, its\n * `occurredAt` for a replayed server event. */\nexport function advance(\n trigger: Trigger,\n record: TriggerRecord,\n eventName: string,\n properties: Record<string, unknown>,\n nowT: number,\n): AdvanceResult {\n const next: TriggerRecord = { ...record };\n const steps = [...trigger.steps].sort((a, b) => a.order - b.order);\n if (steps.length === 0) return { record: next, satisfied: false };\n\n const matchesStep = (index: number): boolean => eventMatchesStep(eventName, properties, steps[index]!);\n\n let satisfied = false;\n\n if (trigger.type === \"SINGLE\") {\n // One step (the first); matching it satisfies the condition.\n satisfied = matchesStep(0);\n } else {\n // SEQUENCE\n const expected = Math.min(next.stepIndex, steps.length - 1);\n\n // A later step can't have happened before the sequence started (a replayed\n // server event older than step 0): ignore it for this sequence, no reset.\n if (expected !== 0 && next.startedAt !== null && nowT < next.startedAt) {\n return { record: next, satisfied: false };\n }\n\n if (matchesStep(expected)) {\n if (expected === 0) {\n next.startedAt = nowT;\n next.stepIndex = 1;\n } else if (windowExpired(trigger.sequenceWindowSeconds, next.startedAt, nowT)) {\n // The sequence window lapsed; restart, re-checking step 0.\n if (matchesStep(0)) {\n next.startedAt = nowT;\n next.stepIndex = 1;\n } else {\n next.stepIndex = 0;\n next.startedAt = null;\n }\n } else {\n next.stepIndex = expected + 1;\n }\n\n if (next.stepIndex >= steps.length) {\n satisfied = true;\n next.stepIndex = 0;\n next.startedAt = null;\n }\n } else if (expected !== 0 && matchesStep(0)) {\n // Out-of-order event that *is* step 0 — restart the sequence.\n next.startedAt = nowT;\n next.stepIndex = 1;\n if (steps.length === 1) {\n satisfied = true;\n next.stepIndex = 0;\n next.startedAt = null;\n }\n }\n }\n\n if (satisfied) next.satisfiedCount += 1;\n return { record: next, satisfied };\n}\n","//\n// triggerEngine.ts\n//\n// The evaluator. For each incoming event it advances every active survey's\n// trigger state and, when a trigger's full condition is satisfied, walks the\n// eligibility order from API-CONTRACT §Eligibility:\n//\n// 1. window (startsAt/endsAt) 2. trigger condition (advanced here)\n// 3. frequency (warmupCount + fireEvery)\n// 4. audience (audienceMatch ⊆ user properties)\n// 5. sampling (deterministic, sticky) 6. per-user cap (maxPerUserDays)\n//\n// Eligible surveys are scheduled after `delaySeconds`; the cap is re-checked at\n// fire time and `lastShownAt` recorded before presenting. Port of iOS\n// `TriggerEngine` (JS is single-threaded, so the serial queue is unnecessary).\n//\n\nimport { advance } from \"./triggerSequencer\";\nimport { inSample, audienceMatches, eventMatchesStep } from \"./sampling\";\nimport { newTriggerRecord, endUserIdOf } from \"./types\";\nimport type { TriggerStateStore } from \"./persistence\";\nimport type { Identity, Survey, Trigger, UserTriggerState } from \"./types\";\n\n/** Why the engine did or didn't schedule a survey for an event. Reported to the\n * live debugger for test devices (see `debug.ts`); `eligible` means scheduled. */\nexport type DecisionReason =\n | \"platform\"\n | \"property_mismatch\"\n | \"sequence_in_progress\"\n | \"not_started\"\n | \"ended\"\n | \"frequency\"\n | \"audience\"\n | \"sampled_out\"\n | \"cap\"\n | \"eligible\"\n | \"shown\"\n | \"another_survey_showing\";\n\nexport interface Decision {\n surveyId: string;\n triggerId: string | null;\n reason: DecisionReason;\n /** For `eligible`: seconds until the survey shows. */\n delaySeconds?: number;\n}\n\nexport interface TriggerEngineOptions {\n store: TriggerStateStore;\n surveysProvider: () => Survey[];\n identityProvider: () => Identity;\n onPresent: (survey: Survey, trigger: Trigger, identity: Identity) => void;\n /** This SDK's platform (e.g. \"ios\"). Surveys with a non-empty `platforms` list\n * that excludes this value are skipped for auto-presentation. */\n platform: string;\n /** Injectable clock in **seconds** (tests). Defaults to `Date.now()/1000`. */\n now?: () => number;\n /** Called with each decision about a survey whose trigger names the event.\n * Used by the live debugger; never affects what the engine does. */\n onDecision?: (decision: Decision) => void;\n}\n\nexport class TriggerEngine {\n private readonly store: TriggerStateStore;\n private readonly surveysProvider: () => Survey[];\n private readonly identityProvider: () => Identity;\n private readonly onPresent: (survey: Survey, trigger: Trigger, identity: Identity) => void;\n private readonly platform: string;\n private readonly now: () => number;\n private readonly onDecision: (decision: Decision) => void;\n private readonly timers = new Set<ReturnType<typeof setTimeout>>();\n\n constructor(opts: TriggerEngineOptions) {\n this.store = opts.store;\n this.surveysProvider = opts.surveysProvider;\n this.identityProvider = opts.identityProvider;\n this.onPresent = opts.onPresent;\n this.platform = opts.platform;\n this.now = opts.now ?? (() => Date.now() / 1000);\n this.onDecision = opts.onDecision ?? (() => {});\n }\n\n /** Feed an event into the engine. `eventT` (unix seconds) is when it happened,\n * for a replayed server event; it drives sequence progress and\n * `sequenceWindowSeconds`. The survey window, caps and delay always use now. */\n process(name: string, properties: Record<string, unknown> = {}, eventT?: number): void {\n const identity = this.identityProvider();\n const endUserId = endUserIdOf(identity);\n const state = this.store.load(endUserId);\n const nowT = this.now();\n const atT = eventT ?? nowT;\n\n for (const survey of this.surveysProvider()) {\n const triggers = survey.triggers;\n if (!triggers || triggers.length === 0) continue;\n // Only surveys whose trigger names this event are reported to the debugger;\n // the rest have nothing to say about it.\n const names = (t: Trigger) => t.steps.some((st) => st.event === name);\n // Platform targeting: skip when the list is non-empty and excludes us.\n if (survey.platforms && survey.platforms.length > 0 && !survey.platforms.includes(this.platform)) {\n const t = triggers.find(names);\n if (t) this.onDecision({ surveyId: survey.id, triggerId: t.id, reason: \"platform\" });\n continue;\n }\n\n for (const trigger of triggers) {\n const satisfied = this.advanceTrigger(trigger, state, name, properties, atT);\n const skip = (reason: DecisionReason) => this.onDecision({ surveyId: survey.id, triggerId: trigger.id, reason });\n if (!satisfied) {\n if (names(trigger)) {\n // The event matched a step but the trigger isn't complete (a sequence), or it\n // had the right name with the wrong properties.\n const matchedStep = trigger.steps.some((st) => eventMatchesStep(name, properties, st));\n skip(matchedStep ? \"sequence_in_progress\" : \"property_mismatch\");\n }\n continue;\n }\n\n const occurrence = state.triggers[trigger.id]?.satisfiedCount ?? 0;\n\n // (1) window\n const window = this.windowState(survey, nowT);\n if (window !== \"open\") {\n skip(window);\n continue;\n }\n // (3) frequency\n if (!passesFrequency(trigger, occurrence)) {\n skip(\"frequency\");\n continue;\n }\n // (4) audience\n if (survey.audienceMatch && !audienceMatches(survey.audienceMatch, identity.userProperties)) {\n skip(\"audience\");\n continue;\n }\n // (5) sampling (sticky)\n if (!this.passesSampling(survey, endUserId, state)) {\n skip(\"sampled_out\");\n continue;\n }\n // (6) cap\n if (!passesCap(survey, state, nowT)) {\n skip(\"cap\");\n continue;\n }\n\n this.onDecision({\n surveyId: survey.id,\n triggerId: trigger.id,\n reason: \"eligible\",\n delaySeconds: Math.max(0, trigger.delaySeconds),\n });\n this.scheduleShow(survey, trigger, identity);\n }\n }\n\n this.store.save(endUserId, state);\n }\n\n /** Cancels any pending scheduled presentations. */\n stop(): void {\n for (const t of this.timers) clearTimeout(t);\n this.timers.clear();\n }\n\n // ── Trigger advancement ────────────────────────────────────────────────────\n\n private advanceTrigger(\n trigger: Trigger,\n state: UserTriggerState,\n eventName: string,\n properties: Record<string, unknown>,\n nowT: number,\n ): boolean {\n const record = state.triggers[trigger.id] ?? newTriggerRecord();\n const { record: updated, satisfied } = advance(trigger, record, eventName, properties, nowT);\n state.triggers[trigger.id] = updated;\n return satisfied;\n }\n\n // ── Eligibility checks ─────────────────────────────────────────────────────\n\n private windowState(survey: Survey, nowT: number): \"open\" | \"not_started\" | \"ended\" {\n if (survey.startsAt) {\n const start = Date.parse(survey.startsAt);\n if (!Number.isNaN(start) && nowT < start / 1000) return \"not_started\";\n }\n if (survey.endsAt) {\n const end = Date.parse(survey.endsAt);\n if (!Number.isNaN(end) && nowT > end / 1000) return \"ended\";\n }\n return \"open\";\n }\n\n private passesSampling(survey: Survey, endUserId: string, state: UserTriggerState): boolean {\n const existing = state.surveys[survey.id]?.sampleDecision;\n if (existing !== undefined && existing !== null) return existing;\n const decision = inSample(endUserId, survey.id, survey.samplePercent ?? 100);\n const record = state.surveys[survey.id] ?? {};\n record.sampleDecision = decision;\n state.surveys[survey.id] = record;\n return decision;\n }\n\n // ── Scheduling ─────────────────────────────────────────────────────────────\n\n private scheduleShow(survey: Survey, trigger: Trigger, identity: Identity): void {\n const delayMs = Math.max(0, trigger.delaySeconds) * 1000;\n const timer = setTimeout(() => {\n this.timers.delete(timer);\n const endUserId = endUserIdOf(identity);\n const state = this.store.load(endUserId);\n const nowT = this.now();\n\n // Re-check the cap at fire time (another survey may have shown during the delay).\n if (!passesCap(survey, state, nowT)) {\n this.onDecision({ surveyId: survey.id, triggerId: trigger.id, reason: \"cap\" });\n return;\n }\n\n // Record the show now so the cap holds even before the impression round-trips.\n const record = state.surveys[survey.id] ?? {};\n record.lastShownAt = nowT;\n state.surveys[survey.id] = record;\n this.store.save(endUserId, state);\n\n this.onPresent(survey, trigger, identity);\n }, delayMs);\n this.timers.add(timer);\n }\n}\n\n/** `occurrence` is 1-based. Ignore the first `warmupCount`, then fire on every\n * `fireEvery`-th satisfied occurrence thereafter. */\nexport function passesFrequency(trigger: Trigger, occurrence: number): boolean {\n const fireEvery = Math.max(1, trigger.fireEvery);\n const effective = occurrence - trigger.warmupCount;\n return effective >= 1 && effective % fireEvery === 0;\n}\n\nfunction passesCap(survey: Survey, state: UserTriggerState, nowT: number): boolean {\n const days = survey.maxPerUserDays ?? 0;\n const lastShown = state.surveys[survey.id]?.lastShownAt;\n if (days <= 0 || lastShown === undefined || lastShown === null) return true;\n const elapsed = nowT - lastShown;\n return elapsed >= days * 86_400;\n}\n","//\n// eventCounter.ts\n//\n// Counts tracked events between uploads so the dashboard can show which events\n// the app actually sends, how often, and from which platform (\"event signals\").\n// Only sent when the project turns event signals on (config `eventSignals`).\n//\n// What leaves the device: each event name, how many times it fired since the\n// last upload, when it was first and last seen in that window, and up to\n// MAX_KEYS property *names*. Never property values, never a user id.\n//\n\n/** Distinct event names held per upload window; names past this are dropped\n * until the next upload, so a buggy loop of unique names can't grow memory. */\nexport const MAX_NAMES = 200;\n/** Property names kept per event. */\nexport const MAX_KEYS = 20;\nconst MAX_NAME_LENGTH = 200;\nconst MAX_KEY_LENGTH = 100;\n\nexport interface EventCount {\n name: string;\n count: number;\n firstSeenAt: string;\n lastSeenAt: string;\n propertyKeys: string[];\n}\n\ninterface Entry {\n count: number;\n first: number;\n last: number;\n keys: Set<string>;\n}\n\nexport class EventCounter {\n private entries = new Map<string, Entry>();\n\n get size(): number {\n return this.entries.size;\n }\n\n record(name: string, properties: Record<string, unknown> = {}, now: number = Date.now()): void {\n if (!name || name.length > MAX_NAME_LENGTH) return;\n let e = this.entries.get(name);\n if (!e) {\n if (this.entries.size >= MAX_NAMES) return;\n e = { count: 0, first: now, last: now, keys: new Set() };\n this.entries.set(name, e);\n }\n e.count += 1;\n e.last = Math.max(e.last, now);\n for (const key of Object.keys(properties)) {\n if (e.keys.size >= MAX_KEYS) break;\n if (key && key.length <= MAX_KEY_LENGTH) e.keys.add(key);\n }\n }\n\n /** Everything counted since the last drain, and a fresh window. */\n drain(): EventCount[] {\n const out = [...this.entries].map(([name, e]) => ({\n name,\n count: e.count,\n firstSeenAt: new Date(e.first).toISOString(),\n lastSeenAt: new Date(e.last).toISOString(),\n propertyKeys: [...e.keys],\n }));\n this.entries = new Map();\n return out;\n }\n}\n","//\n// debug.ts\n//\n// The live debugger: on a test device chosen in the dashboard, the SDK sends\n// each tracked event and what the engine decided for every survey whose trigger\n// names it, so a developer can see why a survey did or didn't show.\n//\n// The dashboard never sends test user ids to apps. Config carries `debugUsers`,\n// a list of hashes of \"debug:<projectId>:<userId>\"; the SDK hashes its current\n// user the same way and only reports when it finds a match. Same FNV-1a as\n// sampling, so every SDK computes the same value.\n//\n\nimport { fnv1a32 } from \"./sampling\";\nimport type { Decision } from \"./triggerEngine\";\n\n/** The hash the dashboard puts in config `debugUsers` for one test user. */\nexport function debugKey(projectId: string, endUserId: string): string {\n return fnv1a32(`debug:${projectId}:${endUserId}`).toString(16).padStart(8, \"0\");\n}\n\nexport interface DebugEntry {\n at: string;\n /** The tracked event, or null for a decision made later (shown, capped at fire time). */\n event: string | null;\n properties: Record<string, unknown>;\n decisions: Decision[];\n}\n\nconst MAX_PROPS = 30;\nconst MAX_STRING = 200;\n\n/** A small, JSON-safe copy of an event's properties for display. Test devices\n * only; nested values are summarised rather than sent whole. */\nexport function debugProperties(properties: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(properties).slice(0, MAX_PROPS)) {\n if (typeof v === \"string\") out[k] = v.length > MAX_STRING ? `${v.slice(0, MAX_STRING)}…` : v;\n else if (typeof v === \"number\" || typeof v === \"boolean\" || v === null) out[k] = v;\n else if (Array.isArray(v)) out[k] = `[${v.length} items]`;\n else if (typeof v === \"object\") out[k] = \"{…}\";\n }\n return out;\n}\n","// The published package version. The release workflow writes the real number\n// here before it builds and publishes; \"0.0.0\" means a local build.\nexport const SDK_VERSION = \"0.1.6\";\n","//\n// client.ts\n//\n// `MicroSurveysClient` — the public facade, mirroring iOS `MicroSurveysSDK`. It\n// owns the config cache, identity store, trigger-state store, API client, and\n// trigger engine, and turns engine \"present\" signals into a single active\n// survey at a time (the provider's overlay renders it). No UI here; storage and\n// the foreground signal are passed in by `MicroSurveys`.\n//\n\nimport { ApiClient, PENDING_PAGE_SIZE } from \"./apiClient\";\nimport type { PendingEvent } from \"./apiClient\";\nimport { ConfigStore, TriggerStateStore } from \"./persistence\";\nimport { IdentityStore } from \"./identity\";\nimport type { AnalyticsIdentity } from \"./identity\";\nimport type { KeyValueStorage } from \"./storage\";\nimport { TriggerEngine } from \"./triggerEngine\";\nimport { EventCounter, MAX_NAMES } from \"./eventCounter\";\nimport { debugKey, debugProperties } from \"./debug\";\nimport type { Decision } from \"./triggerEngine\";\nimport { SDK_VERSION } from \"./version\";\nimport { endUserIdOf } from \"./types\";\nimport type { DeviceContext, Identity, ProjectTheme, Survey, SurveyResult, Trigger } from \"./types\";\n\n/** Default API base. Override via `apiBaseURL` for self-hosted deployments. */\nconst DEFAULT_BASE_URL = \"https://console.microsurveys.ai\";\n/** How long a cached config is treated as fresh for foreground refresh. */\nconst DEFAULT_CONFIG_TTL_MS = 30 * 60 * 1000;\n/** How often counted events are uploaded while event signals are on. */\nconst EVENT_COUNTS_INTERVAL_MS = 60 * 1000;\n/** Server events mailbox (API-CONTRACT §6). Follow-up checks after each start or\n * foreground: Amplitude streams within about 60 s, so these catch an event that\n * happened just before the app opened. */\nconst PENDING_FOLLOW_UPS_MS = [30 * 1000, 90 * 1000];\n/** Regular check while the app stays in the foreground. */\nconst PENDING_INTERVAL_MS = 5 * 60 * 1000;\n/** Faster check while a sequence waits on a server event as its next step. */\nconst PENDING_WAITING_INTERVAL_MS = 60 * 1000;\n/** Stop the faster check this long after the waiting sequence started. */\nconst PENDING_WAITING_MAX_SECONDS = 3 * 60 * 60;\n\nexport interface CreateClientOptions {\n apiKey: string;\n /** Override for self-hosted deployments. Defaults to https://console.microsurveys.ai. */\n apiBaseURL?: string;\n /** Foreground-refresh freshness window in ms. Defaults to 30 min. */\n configTTLms?: number;\n /** Auto-refresh config on tab foreground (visibilitychange). Default true. */\n refreshOnForeground?: boolean;\n /** This device's platform for survey targeting (\"ios\" | \"android\"). */\n platform: string;\n /** The OS version, sent with responses. */\n osVersion?: string;\n /** The host app's version, sent with responses so results can be compared\n * across releases. */\n appVersion?: string;\n /** Where config, identity, trigger state and the outbox persist. Must already\n * hold its data when the client is created. */\n storage: KeyValueStorage;\n /** Subscribes to \"app came to the foreground\"; returns an unsubscribe. */\n subscribeForeground: (onForeground: () => void) => () => void;\n /** Subscribes to \"app went to the background\"; returns an unsubscribe. Used\n * to upload event counts before the app may be suspended, and to stop the\n * server events mailbox timers. */\n subscribeBackground?: (onBackground: () => void) => () => void;\n}\n\n/** An auto-triggered survey the host should present. Call `close` exactly once\n * when the UI dismisses (completed, partial, or dismissed). */\nexport interface ActiveSurvey {\n survey: Survey;\n trigger: Trigger | null;\n close(result: SurveyResult): void;\n}\n\ntype PresentListener = (active: ActiveSurvey) => void;\ntype ConfigListener = () => void;\n\ninterface Presentation {\n survey: Survey;\n trigger: Trigger | null;\n identity: Identity;\n shownAt: Date;\n closed: boolean;\n}\n\nexport class MicroSurveysClient {\n private readonly api: ApiClient;\n private readonly configStore: ConfigStore;\n private readonly identityStore: IdentityStore;\n private readonly triggerStateStore: TriggerStateStore;\n private readonly engine: TriggerEngine;\n private readonly configTTLms: number;\n private readonly refreshOnForeground: boolean;\n private readonly platform: string;\n private readonly osVersion: string | undefined;\n private readonly appVersion: string | undefined;\n private readonly subscribeForeground: (onForeground: () => void) => () => void;\n private readonly subscribeBackground: ((onBackground: () => void) => () => void) | undefined;\n private readonly eventCounter = new EventCounter();\n private eventCountsTimer: ReturnType<typeof setInterval> | null = null;\n /** Decisions collected while one event is processed, for the live debugger. */\n private collecting: Decision[] | null = null;\n private unsubscribeBackground: (() => void) | null = null;\n /** Mailbox timers, cleared on background and stop. */\n private pendingTimers: ReturnType<typeof setTimeout>[] = [];\n private pendingIntervals: ReturnType<typeof setInterval>[] = [];\n private pendingInFlight = false;\n\n private readonly presentListeners = new Set<PresentListener>();\n private readonly configListeners = new Set<ConfigListener>();\n private active: Presentation | null = null;\n private started = false;\n private unsubscribeForeground: (() => void) | null = null;\n\n constructor(opts: CreateClientOptions) {\n const kv = opts.storage;\n this.configStore = new ConfigStore(kv);\n this.identityStore = new IdentityStore(kv);\n this.triggerStateStore = new TriggerStateStore(kv);\n this.api = new ApiClient(opts.apiKey, opts.apiBaseURL ?? DEFAULT_BASE_URL, kv);\n this.configTTLms = opts.configTTLms ?? DEFAULT_CONFIG_TTL_MS;\n this.refreshOnForeground = opts.refreshOnForeground ?? true;\n this.platform = opts.platform;\n this.osVersion = opts.osVersion;\n this.appVersion = opts.appVersion;\n this.subscribeForeground = opts.subscribeForeground;\n this.subscribeBackground = opts.subscribeBackground;\n this.engine = new TriggerEngine({\n store: this.triggerStateStore,\n surveysProvider: () => this.configStore.surveys,\n identityProvider: () => this.identityStore.snapshot(),\n onPresent: (survey, trigger, identity) => this.handlePresent(survey, trigger, identity),\n platform: opts.platform,\n onDecision: (d) => this.handleDecision(d),\n });\n }\n\n // ── Lifecycle ────────────────────────────────────────────────────────────────\n\n /** Flush any queued ingest, refresh config, wire the foreground refresh\n * (optional) and the server events mailbox checks. Safe to call once early. */\n start(): void {\n if (this.started) return;\n this.started = true;\n void this.api.flush();\n // Check the server events mailbox once the config says whether there is one.\n void this.refreshConfig().then(() => {\n if (this.started) this.startPendingChecks();\n });\n // Always subscribed: the mailbox is checked on every foreground, whatever the\n // config TTL, and even when `refreshOnForeground` is off.\n this.unsubscribeForeground = this.subscribeForeground(() => {\n if (this.refreshOnForeground) {\n // Retry ingest queued while offline/backgrounded, then refresh if stale.\n void this.api.flush();\n this.refreshConfigIfStale();\n }\n this.startPendingChecks();\n });\n // The app may be suspended or killed in the background: send what was counted first.\n this.unsubscribeBackground =\n this.subscribeBackground?.(() => {\n this.flushEventCounts();\n this.stopPendingChecks();\n }) ?? null;\n this.eventCountsTimer = setInterval(() => this.flushEventCounts(), EVENT_COUNTS_INTERVAL_MS);\n }\n\n /** Tear down listeners + pending timers. */\n stop(): void {\n this.engine.stop();\n this.flushEventCounts();\n if (this.eventCountsTimer) clearInterval(this.eventCountsTimer);\n this.eventCountsTimer = null;\n this.stopPendingChecks();\n this.unsubscribeBackground?.();\n this.unsubscribeBackground = null;\n this.unsubscribeForeground?.();\n this.unsubscribeForeground = null;\n this.started = false;\n }\n\n /** Force an ETag-aware config refresh; keeps the cache on failure. */\n async refreshConfig(): Promise<void> {\n try {\n const result = await this.api.fetchConfig(this.configStore.etag);\n if (result.kind === \"config\") {\n this.configStore.save(result.rawText, result.etag);\n this.configListeners.forEach((l) => l());\n }\n } catch {\n // Keep the cached config; the SDK still works offline.\n }\n }\n\n /** Refresh only when the cache is missing or older than the TTL. */\n refreshConfigIfStale(): void {\n const storedAt = this.configStore.storedAt;\n if (storedAt !== null && Date.now() - storedAt < this.configTTLms) return;\n void this.refreshConfig();\n }\n\n // ── Identity + events ────────────────────────────────────────────────────────\n\n identify(userId: string | null | undefined, properties?: Record<string, unknown>): void {\n this.identityStore.setUser(userId, properties);\n }\n\n track(name: string, properties: Record<string, unknown> = {}): void {\n if (this.configStore.eventSignals) {\n this.eventCounter.record(name, properties);\n if (this.eventCounter.size >= MAX_NAMES) this.flushEventCounts();\n }\n this.processEvent(name, properties);\n }\n\n /** Runs one event through the engine, reporting to the live debugger on test\n * devices. `occurredAt` (ms epoch) is set for a replayed server event. */\n private processEvent(name: string, properties: Record<string, unknown>, occurredAt?: number): void {\n const eventT = occurredAt === undefined ? undefined : occurredAt / 1000;\n if (!this.isDebugDevice()) {\n this.engine.process(name, properties, eventT);\n return;\n }\n this.collecting = [];\n try {\n this.engine.process(name, properties, eventT);\n } finally {\n const decisions = this.collecting;\n this.collecting = null;\n this.sendDebug(name, debugProperties(properties), decisions, occurredAt);\n }\n }\n\n // ── Server events mailbox ────────────────────────────────────────────────────\n\n /** Checks now, then 30 s and 90 s later, every 5 minutes, and every 60 s while\n * a sequence waits on a server event. Restarts the schedule; no-op unless the\n * config has `pendingEvents`. */\n private startPendingChecks(): void {\n this.stopPendingChecks();\n if (!this.configStore.pendingEvents) return;\n void this.checkPending();\n for (const ms of PENDING_FOLLOW_UPS_MS) {\n this.pendingTimers.push(setTimeout(() => void this.checkPending(), ms));\n }\n this.pendingIntervals.push(\n setInterval(() => void this.checkPending(), PENDING_INTERVAL_MS),\n setInterval(() => {\n if (this.isWaitingOnServerEvent()) void this.checkPending();\n }, PENDING_WAITING_INTERVAL_MS),\n );\n }\n\n private stopPendingChecks(): void {\n for (const t of this.pendingTimers) clearTimeout(t);\n for (const t of this.pendingIntervals) clearInterval(t);\n this.pendingTimers = [];\n this.pendingIntervals = [];\n }\n\n /** Fetches and replays this user's waiting server events. One request at a\n * time; a full page is followed by one more call. Failures are silent: the\n * next scheduled check retries. */\n private async checkPending(): Promise<void> {\n if (this.pendingInFlight || !this.configStore.pendingEvents) return;\n const identity = this.identityStore.snapshot();\n const userId = identity.amplitudeUserId ?? identity.hostUserId ?? null;\n const deviceId = identity.amplitudeDeviceId ?? null;\n if (!userId && !deviceId) return;\n this.pendingInFlight = true;\n try {\n for (let call = 0; call < 2; call++) {\n const events = await this.api.fetchPending({ userId, deviceId });\n this.replayPending(events);\n if (events.length < PENDING_PAGE_SIZE) break;\n }\n } catch {\n // Offline or server trouble: the next scheduled check retries.\n } finally {\n this.pendingInFlight = false;\n }\n }\n\n /** Replays server events like `track`, oldest first, at the time each one\n * happened. Not counted in event signals: the app didn't send them. */\n private replayPending(events: PendingEvent[]): void {\n const timed = events.map((e) => ({ e, at: Date.parse(e.occurredAt) }));\n timed.sort((a, b) => a.at - b.at);\n for (const { e, at } of timed) this.processEvent(e.name, e.properties, at);\n }\n\n /** True while a SEQUENCE trigger for the current user has started and its next\n * step's event arrives by server stream, up to 3 hours after it started. */\n private isWaitingOnServerEvent(): boolean {\n const serverEvents = this.configStore.serverEvents;\n if (serverEvents.length === 0) return false;\n const state = this.triggerStateStore.load(endUserIdOf(this.identityStore.snapshot()));\n const nowT = Date.now() / 1000;\n for (const survey of this.configStore.surveys) {\n for (const trigger of survey.triggers ?? []) {\n if (trigger.type !== \"SEQUENCE\") continue;\n const record = state.triggers[trigger.id];\n if (!record || record.stepIndex <= 0 || record.startedAt === null) continue;\n if (nowT - record.startedAt > PENDING_WAITING_MAX_SECONDS) continue;\n const steps = [...trigger.steps].sort((a, b) => a.order - b.order);\n const next = steps[Math.min(record.stepIndex, steps.length - 1)];\n if (next && serverEvents.includes(next.event)) return true;\n }\n }\n return false;\n }\n\n // ── Live debugger ────────────────────────────────────────────────────────────\n\n /** True when the dashboard picked the current user as a test device. */\n private isDebugDevice(): boolean {\n const users = this.configStore.debugUsers;\n const projectId = this.configStore.projectId;\n if (users.length === 0 || !projectId) return false;\n return users.includes(debugKey(projectId, endUserIdOf(this.identityStore.snapshot())));\n }\n\n private handleDecision(d: Decision): void {\n if (this.collecting) this.collecting.push(d);\n // Made outside an event (a delayed survey's cap check at fire time): report on its own.\n else if (this.isDebugDevice()) this.sendDebug(null, {}, [d]);\n }\n\n /** `at` (ms epoch) defaults to now; a replayed server event passes its `occurredAt`. */\n private sendDebug(event: string | null, properties: Record<string, unknown>, decisions: Decision[], at?: number): void {\n const endUserId = endUserIdOf(this.identityStore.snapshot());\n this.api.recordDebug(\n { at: new Date(at ?? Date.now()).toISOString(), event, properties, decisions },\n endUserId,\n { ...this.deviceContext(), sdkVersion: SDK_VERSION },\n );\n }\n\n /** Uploads the events counted since the last upload (no-op when there are none). */\n flushEventCounts(): void {\n if (this.eventCounter.size === 0) return;\n this.api.recordEventCounts(this.eventCounter.drain(), { ...this.deviceContext(), sdkVersion: SDK_VERSION });\n }\n\n /** Merge identity forwarded by an analytics SDK (e.g. the Amplitude plugin).\n * Its user/device id take precedence over `identify()` for `endUserId`. */\n updateAnalyticsIdentity(update: AnalyticsIdentity): void {\n this.identityStore.updateFromAnalytics(update);\n }\n\n // ── Config accessors (for inline rendering) ──────────────────────────────────\n\n getTheme(): ProjectTheme | null {\n return this.configStore.theme;\n }\n\n getSurvey(surveyId: string): Survey | undefined {\n return this.configStore.surveys.find((s) => s.id === surveyId);\n }\n\n /** Subscribe to config refreshes (e.g. to render an inline survey that wasn't\n * cached yet). Returns an unsubscribe function. */\n onConfigChange(cb: ConfigListener): () => void {\n this.configListeners.add(cb);\n return () => this.configListeners.delete(cb);\n }\n\n // ── Presentation ─────────────────────────────────────────────────────────────\n\n /** Subscribe to auto-triggered surveys. Returns an unsubscribe function. If a\n * survey is already active, the new subscriber is notified immediately. */\n onPresent(cb: PresentListener): () => void {\n this.presentListeners.add(cb);\n if (this.active && !this.active.closed) cb(this.toActiveSurvey(this.active));\n return () => this.presentListeners.delete(cb);\n }\n\n private handlePresent(survey: Survey, trigger: Trigger, identity: Identity): void {\n // One survey on screen at a time — drop while one is active.\n if (this.active && !this.active.closed) {\n this.handleDecision({ surveyId: survey.id, triggerId: trigger.id, reason: \"another_survey_showing\" });\n return;\n }\n this.handleDecision({ surveyId: survey.id, triggerId: trigger.id, reason: \"shown\" });\n const p: Presentation = { survey, trigger, identity, shownAt: new Date(), closed: false };\n this.active = p;\n const active = this.toActiveSurvey(p);\n this.presentListeners.forEach((l) => l(active));\n }\n\n private toActiveSurvey(p: Presentation): ActiveSurvey {\n return {\n survey: p.survey,\n trigger: p.trigger,\n close: (result: SurveyResult) => {\n if (p.closed) return;\n p.closed = true;\n this.recordOutcome(p.survey.id, p.trigger?.id ?? null, p.identity, p.shownAt, result);\n if (this.active === p) this.active = null;\n },\n };\n }\n\n /** Records the outcome of an **inline** `<MicroSurvey>` (no trigger/gate). */\n recordInline(survey: Survey, result: SurveyResult, shownAt: Date): void {\n const identity = this.identityStore.snapshot();\n this.recordOutcome(survey.id, null, identity, shownAt, result);\n }\n\n private recordOutcome(\n surveyId: string,\n triggerId: string | null,\n identity: Identity,\n shownAt: Date,\n result: SurveyResult,\n ): void {\n const endUserId = endUserIdOf(identity);\n const context = this.deviceContext();\n // Impression is finalized at close, so `dismissed` is authoritative.\n const impressionId = this.api.recordImpression({\n surveyId,\n triggerId,\n endUserId,\n shownAt,\n dismissed: result.dismissed,\n context,\n });\n // A pure dismissal (no answers) is an impression, NOT a response — don't\n // inflate the response count. Partial multi-step answers still count.\n if (result.completed || result.answers.length > 0) {\n this.api.recordResponse({\n surveyId,\n endUserId,\n completed: result.completed,\n submittedAt: new Date(),\n userProps: identity.userProperties,\n impressionId,\n triggerId,\n context,\n answers: result.answers,\n });\n }\n }\n\n /** Where this showing happened. The language is read at record time: the user\n * can change it while the app runs. */\n private deviceContext(): DeviceContext {\n let locale: string | undefined;\n try {\n locale = Intl.DateTimeFormat().resolvedOptions().locale || undefined;\n } catch {\n // Runtimes built without Intl: leave the language out.\n }\n return { platform: this.platform, appVersion: this.appVersion, osVersion: this.osVersion, locale };\n }\n}\n\n/** Creates and returns a `MicroSurveysClient`. Call `start()` to begin. */\nexport function createClient(opts: CreateClientOptions): MicroSurveysClient {\n return new MicroSurveysClient(opts);\n}\n","//\n// amplitude.ts\n//\n// An Amplitude enrichment plugin for `@amplitude/analytics-react-native`: it\n// reads every tracked event (name + properties), keeps the identity fresh\n// (user id, device id, `$identify` user properties), and forwards both to the\n// SDK — then returns the event **unmodified** (pure pass-through, never drops or\n// rewrites events). Port of iOS `MicroSurveysAmplitudePlugin`.\n//\n// Typed structurally so this package doesn't depend on Amplitude.\n//\n\nimport type { AnalyticsIdentity } from \"./core\";\n\n/** The fields of an Amplitude event this plugin reads. */\nexport interface AmplitudeEvent {\n event_type: string;\n event_properties?: Record<string, unknown> | null;\n user_id?: string | null;\n device_id?: string | null;\n /** On `$identify` events: `{ $set, $setOnce, $unset, … }` operations. */\n user_properties?: Record<string, unknown> | null;\n}\n\n/** An Amplitude enrichment plugin (`amplitude.add(plugin)`). */\nexport interface MicroSurveysAmplitudePlugin {\n name: string;\n type: \"enrichment\";\n setup(config?: unknown, client?: unknown): Promise<void>;\n execute<E extends AmplitudeEvent>(event: E): Promise<E>;\n}\n\n/** What the plugin forwards into. Implemented by `MicroSurveys`. */\nexport interface AmplitudeForwarder {\n updateAnalyticsIdentity(update: AnalyticsIdentity): void;\n track(name: string, properties?: Record<string, unknown>): void;\n}\n\nexport function createAmplitudePlugin(forwarder: AmplitudeForwarder): MicroSurveysAmplitudePlugin {\n return {\n name: \"microsurveys\",\n type: \"enrichment\",\n async setup() {},\n async execute(event) {\n try {\n forwarder.updateAnalyticsIdentity(identityOf(event));\n // System events (`$identify`, `$groupidentify`, …) never match host\n // triggers; skip them rather than churn trigger state.\n if (!event.event_type.startsWith(\"$\")) {\n forwarder.track(event.event_type, event.event_properties ?? {});\n }\n } catch {\n // Never let survey logic break the host's analytics pipeline.\n }\n return event;\n },\n };\n}\n\n/** Maps an event's identity fields (and, for `$identify`, its property\n * operations) onto an identity update. */\nexport function identityOf(event: AmplitudeEvent): AnalyticsIdentity {\n const update: AnalyticsIdentity = { userId: event.user_id, deviceId: event.device_id };\n if (event.event_type !== \"$identify\" || !event.user_properties) return update;\n\n const ops = event.user_properties;\n const set = asRecord(ops.$set);\n const setOnce = asRecord(ops.$setOnce);\n if (set) update.userProperties = set;\n if (setOnce) update.setOnceProperties = setOnce;\n const unset = asRecord(ops.$unset);\n if (unset) update.unsetProperties = Object.keys(unset);\n return update;\n}\n\nfunction asRecord(v: unknown): Record<string, unknown> | null {\n return v && typeof v === \"object\" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;\n}\n","//\n// asyncStorage.ts\n//\n// The engine reads its stores synchronously (config cache, identity,\n// trigger state, outbox), but React Native's AsyncStorage is async. This adapter\n// preloads every MicroSurveys key into memory once, then serves reads from\n// memory and writes through to AsyncStorage in order. Writes are best-effort:\n// a failed write only loses persistence, never breaks the running SDK.\n//\n\nimport { STORAGE_KEY_PREFIX } from \"./core\";\nimport type { KeyValueStorage } from \"./core\";\n\n/** The subset of AsyncStorage this SDK needs. Matches\n * `@react-native-async-storage/async-storage` v1, v2 (`multiGet`) and v3\n * (`getMany`), or any store with the same shape. */\nexport interface AsyncKeyValueStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n getAllKeys(): Promise<readonly string[]>;\n /** v3 batch read. */\n getMany?(keys: string[]): Promise<Record<string, string | null>>;\n /** v1/v2 batch read. */\n multiGet?(keys: readonly string[]): Promise<readonly (readonly [string, string | null])[]>;\n}\n\n/** Loads every MicroSurveys key from `store` and returns a synchronous view of\n * it for the runtime. Never rejects: if the store can't be read, the SDK\n * starts with empty state. */\nexport async function hydrateAsyncStorage(store: AsyncKeyValueStorage): Promise<KeyValueStorage> {\n const cache = new Map<string, string>();\n try {\n const keys = (await store.getAllKeys()).filter((k) => k.startsWith(STORAGE_KEY_PREFIX));\n for (const [key, value] of await readMany(store, keys)) {\n if (value !== null) cache.set(key, value);\n }\n } catch {\n // Unreadable store: start empty rather than not at all.\n }\n\n // One write chain, so writes land in the order the runtime made them.\n let chain: Promise<void> = Promise.resolve();\n const enqueue = (write: () => Promise<void>) => {\n chain = chain.then(write).catch(() => {});\n };\n\n return {\n getItem: (key) => cache.get(key) ?? null,\n setItem(key, value) {\n cache.set(key, value);\n enqueue(() => store.setItem(key, value));\n },\n removeItem(key) {\n cache.delete(key);\n enqueue(() => store.removeItem(key));\n },\n };\n}\n\nasync function readMany(store: AsyncKeyValueStorage, keys: string[]): Promise<[string, string | null][]> {\n if (keys.length === 0) return [];\n if (store.getMany) return Object.entries(await store.getMany(keys));\n if (store.multiGet) return (await store.multiGet(keys)).map(([k, v]) => [k, v]);\n return Promise.all(keys.map(async (k): Promise<[string, string | null]> => [k, await store.getItem(k)]));\n}\n","//\n// provider.tsx\n//\n// `<MicroSurveysProvider>` exposes a `MicroSurveys` instance to the tree,\n// starts it, and mounts the overlay host that presents auto-triggered surveys\n// (port of iOS `Presenter`). Pass `apiKey` for the simple case, or `instance`\n// to share one created at module scope (e.g. for the Amplitude plugin).\n//\n\nimport { createContext, useContext, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { ActiveSurvey } from \"./core\";\nimport { MicroSurveys } from \"./MicroSurveys\";\nimport { SurveyModal } from \"./ui/SurveyModal\";\n\ninterface ContextValue {\n instance: MicroSurveys | null;\n fontFamily?: string;\n}\n\nexport const MicroSurveysContext = createContext<ContextValue>({ instance: null });\n\nexport interface MicroSurveysProviderProps {\n /** Project API key (`ms_live_…` / `ms_test_…`). Ignored when `instance` is passed. */\n apiKey?: string;\n /** Override the API base for self-hosted deployments. Ignored when `instance` is passed. */\n apiBaseURL?: string;\n /** Your app's version (e.g. \"3.2.0\"), sent with responses. Ignored when `instance` is passed. */\n appVersion?: string;\n /** A `MicroSurveys` you created yourself, e.g. to register its Amplitude plugin. */\n instance?: MicroSurveys;\n /** Start automatically on mount (load config, flush queued ingest). Default true. */\n autoStart?: boolean;\n /** A font family your app registered (e.g. with expo-font) to render surveys in.\n * Defaults to the system font. */\n fontFamily?: string;\n children?: ReactNode;\n}\n\nexport function MicroSurveysProvider({ apiKey, apiBaseURL, appVersion, instance, autoStart = true, fontFamily, children }: MicroSurveysProviderProps) {\n // Created once; later prop changes are ignored (remount the provider to switch keys).\n const [owned] = useState<MicroSurveys | null>(() => (!instance && apiKey ? new MicroSurveys({ apiKey, apiBaseURL, appVersion }) : null));\n const ms = instance ?? owned;\n\n useEffect(() => {\n if (!ms || !autoStart) return;\n ms.start();\n // Only stop an instance this provider created; a shared one outlives it.\n return () => owned?.stop();\n }, [ms, owned, autoStart]);\n\n const value = useMemo(() => ({ instance: ms, fontFamily }), [ms, fontFamily]);\n return (\n <MicroSurveysContext.Provider value={value}>\n {children}\n {ms && <OverlayHost instance={ms} fontFamily={fontFamily} />}\n </MicroSurveysContext.Provider>\n );\n}\n\n/** Presents auto-triggered surveys one at a time. A survey triggered while\n * another is still on screen (e.g. during its \"Thanks\") waits its turn. */\nfunction OverlayHost({ instance, fontFamily }: { instance: MicroSurveys; fontFamily?: string }) {\n const [current, setCurrent] = useState<{ active: ActiveSurvey; id: number } | null>(null);\n const queue = useRef<ActiveSurvey[]>([]);\n const showing = useRef(false);\n const nextId = useRef(0);\n\n useEffect(\n () =>\n instance.onPresent((active) => {\n if (showing.current) {\n queue.current.push(active);\n return;\n }\n showing.current = true;\n setCurrent({ active, id: nextId.current++ });\n }),\n [instance],\n );\n\n function showNext() {\n const next = queue.current.shift();\n if (next) {\n setCurrent({ active: next, id: nextId.current++ });\n } else {\n showing.current = false;\n setCurrent(null);\n }\n }\n\n return (\n <SurveyModal\n // A fresh modal per presentation, even when the same survey shows twice.\n key={current?.id ?? \"none\"}\n survey={current?.active.survey ?? null}\n theme={instance.getTheme()}\n fontFamily={fontFamily}\n onResult={(result) => current?.active.close(result)}\n onClose={showNext}\n />\n );\n}\n\n/** The `MicroSurveys` instance from the nearest provider (or null outside one). */\nexport function useMicroSurveysInstance(): MicroSurveys | null {\n return useContext(MicroSurveysContext).instance;\n}\n\n/** Event + identity helpers bound to the provider's instance. Safe no-ops\n * outside a provider. */\nexport function useMicroSurveys() {\n const instance = useMicroSurveysInstance();\n return useMemo(\n () => ({\n instance,\n track: (name: string, properties?: Record<string, unknown>) => instance?.track(name, properties),\n identify: (userId: string | null | undefined, properties?: Record<string, unknown>) => instance?.identify(userId, properties),\n refresh: () => instance?.refreshConfig(),\n }),\n [instance],\n );\n}\n","//\n// SurveyModal.tsx\n//\n// Presents one survey over the app as a bottom sheet (grabber, swipe down to\n// dismiss) or a centered dialog, per the survey's `presentation` or the project\n// theme's `position`. Port of iOS `SurveyViewController`'s presentation: dims\n// the app, avoids the keyboard, respects safe areas, and blocks every dismissal\n// path for `dismissible: false` surveys.\n//\n// Exported so hosts can preview a survey without a backend (as the demo app\n// does); auto-triggered surveys are presented by <MicroSurveysProvider>.\n//\n\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport type { RefObject } from \"react\";\nimport {\n Animated,\n Easing,\n Keyboard,\n KeyboardAvoidingView,\n Modal,\n PanResponder,\n Platform,\n Pressable,\n StyleSheet,\n View,\n useColorScheme,\n useWindowDimensions,\n} from \"react-native\";\nimport type { LayoutChangeEvent, PanResponderGestureState } from \"react-native\";\nimport { SafeAreaProvider, initialWindowMetrics, useSafeAreaInsets } from \"react-native-safe-area-context\";\nimport type { ProjectTheme, Survey, SurveyResult } from \"../core\";\nimport { SurveyCard } from \"./SurveyCard\";\nimport type { SurveyCardHandle } from \"./SurveyCard\";\nimport { FLOATING_SHEET_INSET, FLOATING_SHEET_RADIUS, usesGlassChrome } from \"./platform\";\nimport { resolveTheme } from \"./theme\";\nimport type { SurveyTheme } from \"./theme\";\n\nexport interface SurveyModalProps {\n /** The survey to show; the modal is visible while this is non-null. */\n survey: Survey | null;\n /** The dashboard theme (`/api/sdk/config` → `theme`). Defaults apply when absent. */\n theme?: ProjectTheme | null;\n /** A font family your app registered (e.g. with expo-font). Defaults to the system font. */\n fontFamily?: string;\n /** Called once with the outcome, as soon as it is known. */\n onResult?: (result: SurveyResult) => void;\n /** Called after the survey has animated away. Clear `survey` here. */\n onClose?: () => void;\n}\n\nexport function SurveyModal({ survey, theme: projectTheme, fontFamily, onResult, onClose }: SurveyModalProps) {\n const scheme = useColorScheme() === \"dark\" ? \"dark\" : \"light\";\n const theme = useMemo(\n () => resolveTheme(projectTheme, { scheme, presentation: survey?.presentation, fontFamily }),\n [projectTheme, scheme, survey?.presentation, fontFamily],\n );\n\n const card = useRef<SurveyCardHandle>(null);\n\n if (!survey) return null;\n return (\n <Modal\n visible\n transparent\n animationType=\"none\"\n statusBarTranslucent\n navigationBarTranslucent\n // Android back button.\n onRequestClose={() => {\n if (survey.dismissible !== false) card.current?.dismiss();\n }}\n >\n {/* The modal is its own native window; give it its own safe-area context. */}\n <SafeAreaProvider initialMetrics={initialWindowMetrics}>\n <Presentation key={survey.id} card={card} survey={survey} theme={theme} onResult={onResult} onClose={onClose} />\n </SafeAreaProvider>\n </Modal>\n );\n}\n\ninterface PresentationProps {\n card: RefObject<SurveyCardHandle | null>;\n survey: Survey;\n theme: SurveyTheme;\n onResult?: (result: SurveyResult) => void;\n onClose?: () => void;\n}\n\nfunction Presentation({ card, survey, theme, onResult, onClose }: PresentationProps) {\n const insets = useSafeAreaInsets();\n const window = useWindowDimensions();\n const isSheet = theme.position === \"bottom\";\n const dismissible = survey.dismissible !== false;\n // iOS 26+ sheets float inset from the edges on Face ID iPhones (home-button\n // devices have no bottom inset and keep an edge-to-edge sheet). UIKit doesn't\n // lay a floating sheet out narrower: it lays out the full-width sheet and\n // scales it down to fit the inset, so everything inside renders at ~96%.\n // Do the same so text wraps and controls size exactly like the native SDK.\n const floating = isSheet && usesGlassChrome && insets.bottom > 0;\n const floatScale = floating ? (window.width - 2 * FLOATING_SHEET_INSET) / window.width : 1;\n // Radii are drawn before the scale, so pre-divide to land on the native value.\n const sheetRadius = floating && theme.nativeSheetCorners ? FLOATING_SHEET_RADIUS / floatScale : theme.sheetCornerRadius;\n // Dim behind the survey: a system sheet dims 20% black on iOS (32% scrim on\n // Android, per Material); the dialog uses the configured background at 40%,\n // as the iOS SDK's custom card does.\n const scrim = isSheet ? (Platform.OS === \"ios\" ? \"rgba(0, 0, 0, 0.2)\" : \"rgba(0, 0, 0, 0.32)\") : theme.scrim;\n\n // 0 = hidden, 1 = shown. `drag` follows a swipe-down on the sheet.\n const progress = useRef(new Animated.Value(0)).current;\n const drag = useRef(new Animated.Value(0)).current;\n const [sheetHeight, setSheetHeight] = useState(window.height);\n const sheetTop = useRef(window.height);\n // Height of the on-screen keyboard (0 when hidden).\n const [keyboard, setKeyboard] = useState(0);\n const keyboardUp = keyboard > 0;\n // On iOS the sheet stays pinned to the bottom and extends behind the keyboard,\n // insetting its content instead of lifting as a whole (as the native SDK does\n // via additionalSafeAreaInsets). Dialogs and Android sheets just move up.\n const insetForKeyboard = isSheet && Platform.OS === \"ios\";\n // That inset is a spacer under the card, animated alongside the keyboard. It's\n // local on purpose: LayoutAnimation is app-wide, and replaying committed props\n // made native-driven views (the dialog mid fade-in) snap back to opacity 0.\n const keyboardSpacer = useRef(new Animated.Value(0)).current;\n const keyboardDuration = useRef(250);\n\n // These run on the JS driver on purpose. A native-driven value never reaches\n // React, so when the keyboard re-lays out the modal, React re-commits the\n // starting value (opacity 0, off-screen) and the survey vanishes on screen.\n useEffect(() => {\n Animated.timing(progress, {\n toValue: 1,\n duration: isSheet ? 320 : 280,\n easing: Easing.out(Easing.cubic),\n useNativeDriver: false,\n }).start();\n }, [progress, isSheet]);\n\n useEffect(() => {\n const update = (height: number, duration?: number) => {\n // iOS reports the keyboard's animation duration; match it.\n if (duration) keyboardDuration.current = duration;\n setKeyboard(height);\n };\n const show = Keyboard.addListener(Platform.OS === \"ios\" ? \"keyboardWillShow\" : \"keyboardDidShow\", (e) =>\n update(e.endCoordinates.height, e.duration),\n );\n const hide = Keyboard.addListener(Platform.OS === \"ios\" ? \"keyboardWillHide\" : \"keyboardDidHide\", (e) => update(0, e.duration));\n return () => {\n show.remove();\n hide.remove();\n };\n }, []);\n\n // The card keeps `pad` above the keyboard; the spacer covers the rest. The\n // floating sheet's bottom edge sits FLOATING_SHEET_INSET up and its content is scaled.\n const spacerTarget = insetForKeyboard && keyboard > 0 ? (keyboard - (floating ? FLOATING_SHEET_INSET : 0)) / floatScale : 0;\n useEffect(() => {\n Animated.timing(keyboardSpacer, {\n toValue: spacerTarget,\n duration: keyboardDuration.current,\n easing: Easing.bezier(0.17, 0.59, 0.4, 0.77), // close to the iOS keyboard curve\n useNativeDriver: false,\n }).start();\n }, [keyboardSpacer, spacerTarget]);\n\n function animateOut() {\n Keyboard.dismiss();\n Animated.timing(progress, { toValue: 0, duration: 240, easing: Easing.in(Easing.cubic), useNativeDriver: false }).start(() => onClose?.());\n }\n\n function requestDismiss() {\n if (dismissible) card.current?.dismiss();\n }\n\n const pan = useMemo(\n () =>\n PanResponder.create({\n // Own touches that start in the sheet's header band (grabber, progress) from\n // the start: otherwise a responder higher up the tree (e.g. a draggable\n // dev overlay at the app root) claims them and the sheet never sees the\n // drag. Buttons in the band (close) are deeper and still win taps.\n onStartShouldSetPanResponder: (e) => isSheet && dismissible && e.nativeEvent.pageY - sheetTop.current < DRAG_HEADER_HEIGHT,\n // Elsewhere, take over a downward drag nothing inside wanted.\n onMoveShouldSetPanResponder: (_, g) => isSheet && dismissible && isDownwardDrag(g),\n onPanResponderTerminationRequest: () => false,\n onPanResponderMove: (_, g) => drag.setValue(Math.max(0, g.dy)),\n onPanResponderRelease: (_, g) => {\n if (isDownwardDrag(g) && (g.dy > 120 || g.vy > 1)) requestDismiss();\n else Animated.spring(drag, { toValue: 0, useNativeDriver: false, bounciness: 0 }).start();\n },\n onPanResponderTerminate: () => Animated.spring(drag, { toValue: 0, useNativeDriver: false, bounciness: 0 }).start(),\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [isSheet, dismissible],\n );\n\n const cardContent = (\n <SurveyCard\n ref={card}\n survey={survey}\n theme={theme}\n variant={isSheet ? \"sheet\" : \"dialog\"}\n // The sheet runs under the home indicator; keep the button above it\n // (unless the keyboard is up, which already lifts the sheet).\n bottomInset={isSheet && !keyboardUp ? insets.bottom : 0}\n onResult={(r) => onResult?.(r)}\n onClose={animateOut}\n />\n );\n\n return (\n <View style={StyleSheet.absoluteFill} accessibilityViewIsModal>\n <Animated.View style={[StyleSheet.absoluteFill, { backgroundColor: scrim, opacity: progress }]}>\n <Pressable\n style={StyleSheet.absoluteFill}\n onPress={requestDismiss}\n // Not a VoiceOver/TalkBack element (as on iOS): the close button and\n // the platform's escape gesture already dismiss.\n accessible={false}\n importantForAccessibility=\"no\"\n />\n </Animated.View>\n\n <KeyboardAvoidingView\n behavior={insetForKeyboard ? undefined : Platform.OS === \"ios\" ? \"padding\" : \"height\"}\n // The dialog centers in the safe area, like iOS. (Its bottom inset is a\n // margin on the dialog: this view's paddingBottom belongs to the keyboard.)\n style={[styles.fill, isSheet ? styles.bottom : [styles.center, { paddingTop: insets.top }]]}\n pointerEvents=\"box-none\"\n >\n {isSheet ? (\n <Animated.View\n {...pan.panHandlers}\n onLayout={(e: LayoutChangeEvent) => {\n setSheetHeight(e.nativeEvent.layout.height);\n sheetTop.current = e.nativeEvent.layout.y;\n }}\n style={[\n styles.sheet,\n shadow,\n floating\n ? {\n borderRadius: sheetRadius,\n borderCurve: \"continuous\",\n borderWidth: StyleSheet.hairlineWidth / floatScale,\n borderColor: theme.dark ? \"rgba(255, 255, 255, 0.14)\" : \"rgba(0, 0, 0, 0.18)\",\n }\n : { borderTopLeftRadius: sheetRadius, borderTopRightRadius: sheetRadius, borderCurve: \"continuous\" },\n {\n maxHeight: window.height - insets.top - 24,\n backgroundColor: theme.surface,\n transform: [\n {\n translateY: Animated.add(\n progress.interpolate({\n inputRange: [0, 1],\n // Shown: scaling about the center lifts the bottom edge by\n // h(1-s)/2; shift so it rests FLOATING_SHEET_INSET above the screen edge.\n outputRange: [sheetHeight, floating ? (sheetHeight * (1 - floatScale)) / 2 - FLOATING_SHEET_INSET : 0],\n }),\n drag,\n ),\n },\n { scale: floatScale },\n ],\n },\n ]}\n >\n <View style={[styles.grabber, { backgroundColor: theme.secondaryText }]} />\n {cardContent}\n {insetForKeyboard && <Animated.View style={{ height: keyboardSpacer }} />}\n </Animated.View>\n ) : (\n <Animated.View\n style={[\n styles.dialog,\n shadow,\n {\n maxHeight: window.height - insets.top - insets.bottom - 48,\n marginBottom: insets.bottom,\n backgroundColor: theme.surface,\n borderRadius: theme.cornerRadius,\n borderCurve: \"continuous\",\n opacity: progress,\n transform: [{ scale: progress.interpolate({ inputRange: [0, 1], outputRange: [0.94, 1] }) }],\n },\n ]}\n >\n {cardContent}\n </Animated.View>\n )}\n </KeyboardAvoidingView>\n </View>\n );\n}\n\n/** Height of the sheet's top band that always drags the sheet. */\nconst DRAG_HEADER_HEIGHT = 72;\n\nfunction isDownwardDrag(g: PanResponderGestureState): boolean {\n return g.dy > 6 && Math.abs(g.dy) > Math.abs(g.dx);\n}\n\nconst shadow = {\n shadowColor: \"#000\",\n shadowOpacity: 0.18,\n shadowRadius: 24,\n shadowOffset: { width: 0, height: -4 },\n elevation: 16,\n} as const;\n\nconst styles = StyleSheet.create({\n fill: { flex: 1 },\n bottom: { justifyContent: \"flex-end\" },\n center: { justifyContent: \"center\", paddingHorizontal: 20 },\n sheet: { width: \"100%\", maxWidth: 640, alignSelf: \"center\" },\n dialog: { width: \"100%\", maxWidth: 480, alignSelf: \"center\", overflow: \"hidden\" },\n grabber: { position: \"absolute\", top: 6, alignSelf: \"center\", width: 36, height: 5, borderRadius: 3, opacity: 0.35, zIndex: 1 },\n});\n","//\n// SurveyCard.tsx\n//\n// The content of a survey: progress (\"1 of 3\"), close button, the current\n// question's prompt + input, and a primary Next/Submit button. Handles\n// multi-step navigation, required-answer gating, the closing \"Thanks\" state and\n// reporting the result. Port of iOS `SurveyViewController`'s card; the caller\n// supplies the chrome (sheet, dialog, or inline container).\n//\n\nimport { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { Animated, Platform, Pressable, ScrollView, StyleSheet, Text, View } from \"react-native\";\nimport type { LayoutChangeEvent } from \"react-native\";\nimport type { AnswerValue, Survey, SurveyAnswer, SurveyResult } from \"../core\";\nimport { CloseButton } from \"./CloseButton\";\nimport { QuestionInput, font, isAnswerValid } from \"./questions\";\nimport type { SurveyTheme } from \"./theme\";\n\n/** Bottom padding inside the scroll area, taken back from the button's margin. */\nconst CLIP_ROOM = 4;\n\n/** How long the \"Thanks\" confirmation shows before the card closes. */\nconst THANKS_MS = 1300;\n\nexport interface SurveyCardHandle {\n /** Dismiss as the user closing the survey (scrim tap, swipe, back button). */\n dismiss(): void;\n}\n\nexport interface SurveyCardProps {\n survey: Survey;\n theme: SurveyTheme;\n /** \"sheet\" adds room for the drag grabber above the content. */\n variant: \"sheet\" | \"dialog\" | \"inline\";\n /** Space to keep below the primary button (e.g. the home-indicator inset). */\n bottomInset?: number;\n /** Called exactly once, as soon as the outcome is known (submit or dismiss). */\n onResult: (result: SurveyResult) => void;\n /** Called when the card is done: right after a dismissal, or after the\n * \"Thanks\" confirmation following a submit. */\n onClose: () => void;\n}\n\nexport const SurveyCard = forwardRef<SurveyCardHandle, SurveyCardProps>(function SurveyCard(\n { survey, theme, variant, bottomInset, onResult, onClose },\n ref,\n) {\n const questions = useMemo(() => [...survey.questions].sort((a, b) => a.order - b.order), [survey]);\n const dismissible = survey.dismissible !== false;\n\n const [index, setIndex] = useState(0);\n // Answers commit when the user advances (Next/Submit), as on iOS, so a\n // dismissal reports only questions the user moved past.\n const committed = useRef<Record<string, AnswerValue>>({});\n const [current, setCurrent] = useState<AnswerValue | undefined>(undefined);\n const [done, setDone] = useState(false);\n const [height, setHeight] = useState(0);\n const reported = useRef(false);\n const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => () => {\n if (closeTimer.current) clearTimeout(closeTimer.current);\n }, []);\n\n const question = questions[index];\n const isLast = index >= questions.length - 1;\n const valid = question ? isAnswerValid(question, current) : false;\n\n function collected(): SurveyAnswer[] {\n return questions.filter((q) => committed.current[q.id] !== undefined).map((q) => ({ questionId: q.id, value: committed.current[q.id]! }));\n }\n\n function report(completed: boolean) {\n if (reported.current) return false;\n reported.current = true;\n onResult({ answers: collected(), completed, dismissed: !completed });\n return true;\n }\n\n function dismiss() {\n if (report(false)) onClose();\n }\n\n useImperativeHandle(ref, () => ({ dismiss }));\n\n // A survey with no questions (misconfigured) has nothing to show.\n useEffect(() => {\n if (questions.length === 0) dismiss();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n function advance() {\n if (!question || !valid) return;\n if (current !== undefined) committed.current[question.id] = current;\n if (!isLast) {\n setIndex(index + 1);\n setCurrent(undefined);\n return;\n }\n if (report(true)) {\n setDone(true);\n closeTimer.current = setTimeout(onClose, THANKS_MS);\n }\n }\n\n const pad = theme.spacing + 4;\n // Extra top room on the sheet so the title and close button clear the grabber.\n const topInset = variant === \"sheet\" ? pad + 12 : pad;\n const hasProgress = questions.length > 1;\n\n if (!question) return null;\n\n if (done) {\n const custom = survey.successMessage?.trim();\n return (\n // Keep the card's height so the sheet doesn't jump when the content swaps.\n <View style={[styles.thanks, { minHeight: height, padding: pad }]} accessibilityLiveRegion=\"polite\">\n <FadeIn>\n <View style={styles.thanksStack}>\n <View style={[styles.check, { backgroundColor: theme.accent }]}>\n <Text allowFontScaling={false} style={[styles.checkGlyph, { color: theme.accentText }]}>\n ✓\n </Text>\n </View>\n <Text style={[promptStyle(theme), { color: theme.text, textAlign: \"center\", marginTop: theme.spacing }]}>{custom || \"Thanks!\"}</Text>\n </View>\n </FadeIn>\n </View>\n );\n }\n\n return (\n <View onLayout={(e: LayoutChangeEvent) => setHeight(e.nativeEvent.layout.height)} style={styles.card}>\n {hasProgress && (\n <Text style={[font(theme, 13), { color: theme.secondaryText, marginTop: topInset, marginHorizontal: pad }]}>\n {index + 1} of {questions.length}\n </Text>\n )}\n\n <ScrollView\n style={styles.scroll}\n // A little room under the last control, so its border never sits on the\n // scroll view's clipping edge (Android snaps that edge to whole pixels and\n // shaved the bottom of the text field). The button's margin gives it back.\n contentContainerStyle={{ paddingHorizontal: pad, paddingTop: hasProgress ? theme.spacing : topInset, paddingBottom: CLIP_ROOM, gap: theme.spacing + 8 }}\n keyboardShouldPersistTaps=\"handled\"\n showsVerticalScrollIndicator={false}\n bounces={false}\n >\n <FadeIn key={question.id}>\n <View style={{ gap: theme.spacing + 8 }}>\n <Text accessibilityRole=\"header\" style={[promptStyle(theme), { color: theme.text, paddingRight: dismissible ? 48 : 0 }]}>\n {question.prompt}\n </Text>\n <QuestionInput question={question} theme={theme} value={current} onChange={setCurrent} autoFocus={variant !== \"inline\"} />\n </View>\n </FadeIn>\n </ScrollView>\n\n <Pressable\n accessibilityRole=\"button\"\n accessibilityState={{ disabled: !valid }}\n disabled={!valid}\n onPress={advance}\n style={({ pressed }) => [\n styles.button,\n {\n height: theme.controlHeight,\n marginTop: theme.spacing - CLIP_ROOM,\n marginHorizontal: pad,\n marginBottom: Math.max(pad, bottomInset ?? 0),\n borderRadius: Math.min(theme.controlRadius, theme.controlHeight / 2),\n backgroundColor: theme.accent,\n opacity: !valid ? 0.45 : pressed ? 0.9 : 1,\n },\n ]}\n >\n <Text maxFontSizeMultiplier={1.6} style={[font(theme, 16, \"600\"), { color: theme.accentText }]}>\n {isLast ? \"Submit\" : \"Next\"}\n </Text>\n </Pressable>\n\n {dismissible && (\n <CloseButton\n theme={theme}\n onPress={dismiss}\n // iOS pins the 44pt button `pad` from the card's top-right corner.\n style={Platform.OS === \"ios\" ? { top: pad, right: pad } : { top: variant === \"sheet\" ? pad + 4 : pad - 6, right: pad - 6 }}\n />\n )}\n </View>\n );\n});\n\nfunction promptStyle(theme: SurveyTheme) {\n return {\n fontSize: theme.titleSize,\n fontWeight: theme.titleWeight,\n fontFamily: theme.fontFamily,\n // iOS applies `lineHeightMultiple` to the font's natural line height (~1.2em).\n lineHeight: Math.round(theme.titleSize * 1.2 * theme.titleLineHeight),\n letterSpacing: theme.titleLetterSpacing,\n textAlign: theme.align,\n } as const;\n}\n\n/** Fades its children in on mount (question changes, the thanks state). */\nfunction FadeIn({ children }: { children: ReactNode }) {\n const opacity = useRef(new Animated.Value(0)).current;\n useEffect(() => {\n // JS driver: a native-driven opacity is re-committed as 0 when the keyboard\n // re-lays out the card (see SurveyModal).\n Animated.timing(opacity, { toValue: 1, duration: 220, useNativeDriver: false }).start();\n }, [opacity]);\n return <Animated.View style={{ opacity }}>{children}</Animated.View>;\n}\n\nconst styles = StyleSheet.create({\n card: { flexShrink: 1 },\n scroll: { flexGrow: 0, flexShrink: 1 },\n button: { alignItems: \"center\", justifyContent: \"center\" },\n thanks: { alignItems: \"center\", justifyContent: \"center\" },\n thanksStack: { alignItems: \"center\" },\n check: { width: 48, height: 48, borderRadius: 24, alignItems: \"center\", justifyContent: \"center\" },\n checkGlyph: { fontSize: 26, fontWeight: \"700\", lineHeight: 30 },\n});\n","//\n// CloseButton.tsx\n//\n// The survey's close button, drawn to match the iOS SDK on the same device:\n// • iOS 26+: a glass circle (`UIButton.Configuration.glass()`, 44pt, bold xmark).\n// • iOS < 26: `xmark.circle.fill` tinted secondary label (the cross is cut out).\n// • Android: a neutral filled circle.\n// The cross is two rounded bars rather than a text glyph, so its weight matches\n// SF Symbols instead of depending on the font's \"✕\".\n//\n\nimport { Platform, Pressable, StyleSheet, View } from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { usesGlassChrome } from \"./platform\";\nimport type { SurveyTheme } from \"./theme\";\n\nexport function CloseButton({ theme, onPress, style }: { theme: SurveyTheme; onPress: () => void; style?: ViewStyle }) {\n let circle: ViewStyle;\n let cross: { color: string; length: number; thickness: number };\n if (usesGlassChrome) {\n circle = {\n width: 44,\n height: 44,\n borderRadius: 22,\n backgroundColor: theme.dark ? \"rgba(72, 72, 74, 0.92)\" : \"rgba(255, 255, 255, 0.94)\",\n borderWidth: StyleSheet.hairlineWidth,\n borderColor: theme.dark ? \"rgba(255, 255, 255, 0.16)\" : \"rgba(0, 0, 0, 0.14)\",\n shadowColor: \"#000\",\n shadowOpacity: theme.dark ? 0.3 : 0.08,\n shadowRadius: 8,\n shadowOffset: { width: 0, height: 2 },\n };\n cross = { color: theme.dark ? \"rgba(255, 255, 255, 0.92)\" : \"rgba(0, 0, 0, 0.88)\", length: 19, thickness: 2.6 };\n } else if (Platform.OS === \"ios\") {\n circle = { width: 31, height: 31, borderRadius: 15.5, backgroundColor: theme.dark ? \"rgba(235, 235, 245, 0.6)\" : \"rgba(60, 60, 67, 0.6)\" };\n cross = { color: theme.surface, length: 12, thickness: 2.4 };\n } else {\n circle = { width: 32, height: 32, borderRadius: 16, backgroundColor: theme.track };\n cross = { color: theme.secondaryText, length: 13, thickness: 2 };\n }\n\n return (\n <Pressable accessibilityRole=\"button\" accessibilityLabel=\"Close survey\" onPress={onPress} hitSlop={6} style={[styles.hit, style]}>\n {({ pressed }) => (\n <View style={[circle, styles.center, pressed && { opacity: 0.7 }]}>\n {[45, -45].map((deg) => (\n <View\n key={deg}\n style={{\n position: \"absolute\",\n width: cross.length,\n height: cross.thickness,\n borderRadius: cross.thickness / 2,\n backgroundColor: cross.color,\n transform: [{ rotate: `${deg}deg` }],\n }}\n />\n ))}\n </View>\n )}\n </Pressable>\n );\n}\n\nconst styles = StyleSheet.create({\n hit: { position: \"absolute\", width: 44, height: 44, alignItems: \"center\", justifyContent: \"center\" },\n center: { alignItems: \"center\", justifyContent: \"center\" },\n});\n","//\n// platform.ts\n//\n// iOS 26 redesigned system chrome (\"Liquid Glass\"): sheets float inset from the\n// screen edges with corners concentric to the display, and close buttons are\n// glass circles. The iOS SDK gets these from UIKit (`UISheetPresentationController`,\n// `UIButton.Configuration.glass()`); this SDK draws its own, so it mirrors them\n// here to look the same on the same device. Android keeps Material conventions.\n//\n\nimport { Platform } from \"react-native\";\n\n/** True on iOS 26+, where the native SDK's sheet floats and its close button is glass. */\nexport const usesGlassChrome = Platform.OS === \"ios\" && parseInt(String(Platform.Version), 10) >= 26;\n\n/** Inset of a floating iOS 26 sheet from the screen edges, measured from the native sheet. */\nexport const FLOATING_SHEET_INSET = 8;\n\n/** Corner radius of a floating iOS 26 sheet on Face ID iPhones (concentric with\n * the display corners), measured from the native sheet. */\nexport const FLOATING_SHEET_RADIUS = 52;\n","//\n// questions.tsx\n//\n// One renderer per question type, ported from the iOS UI/*View.swift files.\n// Each takes the question, the current answer, and an `onChange`, and emits the\n// exact `AnswerValue` JSON the backend expects (API-CONTRACT §Answer value\n// shapes). Every visual value comes from the resolved `SurveyTheme`.\n//\n\nimport { useState } from \"react\";\nimport { Pressable, StyleSheet, Text, TextInput, View } from \"react-native\";\nimport type { LayoutChangeEvent, TextStyle } from \"react-native\";\nimport type { AnswerValue, ChoiceOption, EmojiOption, Question } from \"../core\";\nimport { clampRadius } from \"./theme\";\nimport type { FontWeight, SurveyTheme } from \"./theme\";\n\nexport interface QuestionInputProps {\n question: Question;\n theme: SurveyTheme;\n value: AnswerValue | undefined;\n onChange: (value: AnswerValue | undefined) => void;\n /** Focus text inputs as soon as they show (overlays; not inline embeds). */\n autoFocus?: boolean;\n}\n\nexport function QuestionInput({ question, theme, value, onChange, autoFocus }: QuestionInputProps) {\n const cfg = question.config;\n switch (cfg.kind) {\n case \"scale\":\n return <ScaleInput min={cfg.min} max={cfg.max} minLabel={cfg.minLabel} maxLabel={cfg.maxLabel} theme={theme} value={numValue(value)} onPick={(n) => onChange({ value: n })} />;\n case \"stars\":\n return <StarsInput count={cfg.count} theme={theme} value={numValue(value)} onPick={(n) => onChange({ value: n })} />;\n case \"emoji\":\n return <EmojiInput options={cfg.options} theme={theme} value={strValue(value)} onPick={(v) => onChange({ value: v })} />;\n case \"thumbs\":\n return <ThumbsInput theme={theme} value={strValue(value)} onPick={(v) => onChange({ value: v })} />;\n case \"singleChoice\":\n return <ChoiceInput options={cfg.options} theme={theme} value={value && \"choice\" in value ? value.choice : undefined} onPick={(v) => onChange({ choice: v })} />;\n case \"openText\":\n return (\n <OpenTextInput\n placeholder={cfg.placeholder}\n maxLength={cfg.maxLength}\n theme={theme}\n autoFocus={autoFocus}\n // Like iOS: the answer is the trimmed text, and empty text is no answer.\n onText={(t) => onChange(t.trim().length > 0 ? { text: t.trim() } : undefined)}\n />\n );\n }\n}\n\n/** Whether `value` satisfies the question's `required` rule. */\nexport function isAnswerValid(question: Question, value: AnswerValue | undefined): boolean {\n return question.required ? value !== undefined : true;\n}\n\n// ── helpers ───────────────────────────────────────────────────────────────────\n\nfunction numValue(v: AnswerValue | undefined): number | undefined {\n return v && \"value\" in v && typeof v.value === \"number\" ? v.value : undefined;\n}\nfunction strValue(v: AnswerValue | undefined): string | undefined {\n return v && \"value\" in v && typeof v.value === \"string\" ? v.value : undefined;\n}\n\n/** A text style at `size` (scaled by the theme's text scale) in the theme font. */\nexport function font(theme: SurveyTheme, size: number, weight: FontWeight = \"400\"): TextStyle {\n return { fontSize: size * theme.textScale, fontWeight: weight, fontFamily: theme.fontFamily };\n}\n\n/** Large controls shouldn't grow without bound under accessibility text sizes. */\nconst MAX_FONT_SCALE = 1.6;\n\n// ── Scale (NPS / CES) ─────────────────────────────────────────────────────────\n\nconst CHIP_GAP = 8;\n/** Minimum chip side, as iOS `ChipButton(minSide: 44)`. */\nconst CHIP_MIN_SIDE = 44;\n\nfunction ScaleInput({ min, max, minLabel, maxLabel, theme, value, onPick }: { min: number; max: number; minLabel?: string; maxLabel?: string; theme: SurveyTheme; value: number | undefined; onPick: (n: number) => void }) {\n const [width, setWidth] = useState(0);\n // Defend against a malformed (reversed/equal) range from the backend.\n const lo = Math.min(min, max);\n const hi = Math.max(min, max);\n const points: number[] = [];\n for (let i = lo; i <= hi; i++) points.push(i);\n\n // Compact scales (≤7, e.g. CES 1–7) stretch to fill the row like a segmented\n // control, never taller than wide (so pills stay round). Wider scales (NPS\n // 0–10) wrap as centered rows of square chips.\n const compact = points.length <= 7;\n const chipWidth = compact && width > 0 ? (width - CHIP_GAP * (points.length - 1)) / points.length : CHIP_MIN_SIDE;\n const chipHeight = compact ? Math.min(theme.controlHeight, chipWidth) : CHIP_MIN_SIDE;\n const hasLabels = !!minLabel || !!maxLabel;\n\n return (\n <View onLayout={(e: LayoutChangeEvent) => setWidth(e.nativeEvent.layout.width)}>\n <View style={[styles.scaleRow, !compact && styles.wrap]}>\n {width > 0 &&\n points.map((n) => {\n const on = value === n;\n return (\n <Pressable\n key={n}\n accessibilityRole=\"button\"\n accessibilityLabel={String(n)}\n accessibilityState={{ selected: on }}\n onPress={() => onPick(n)}\n style={({ pressed }) => [\n styles.chip,\n {\n width: compact ? chipWidth : undefined,\n minWidth: compact ? undefined : CHIP_MIN_SIDE,\n height: chipHeight,\n borderRadius: clampRadius(theme.controlRadius, compact ? chipWidth : CHIP_MIN_SIDE, chipHeight),\n backgroundColor: on ? theme.accent : theme.surface,\n borderColor: on ? theme.accent : theme.border,\n opacity: pressed ? 0.85 : 1,\n },\n ]}\n >\n <Text maxFontSizeMultiplier={MAX_FONT_SCALE} style={[font(theme, 16, \"500\"), { color: on ? theme.accentText : theme.text }]}>\n {n}\n </Text>\n </Pressable>\n );\n })}\n </View>\n {hasLabels && (\n <View style={styles.endLabels}>\n <Text style={[font(theme, 13), styles.endLabel, { color: theme.secondaryText }]} numberOfLines={2}>\n {minLabel}\n </Text>\n <Text style={[font(theme, 13), styles.endLabel, { color: theme.secondaryText, textAlign: \"right\" }]} numberOfLines={2}>\n {maxLabel}\n </Text>\n </View>\n )}\n </View>\n );\n}\n\n// ── Stars (CSAT_STAR) ─────────────────────────────────────────────────────────\n\nfunction StarsInput({ count, theme, value, onPick }: { count: number; theme: SurveyTheme; value: number | undefined; onPick: (n: number) => void }) {\n const stars: number[] = [];\n for (let i = 1; i <= Math.max(1, count); i++) stars.push(i);\n return (\n <View style={styles.starsRow}>\n {stars.map((n) => {\n const on = value !== undefined && n <= value;\n return (\n <Pressable\n key={n}\n accessibilityRole=\"button\"\n accessibilityLabel={`${n} star${n === 1 ? \"\" : \"s\"}`}\n accessibilityState={{ selected: value === n }}\n onPress={() => onPick(n)}\n hitSlop={4}\n style={styles.star}\n >\n <Text allowFontScaling={false} style={{ fontSize: 38, lineHeight: 46, color: theme.accent }}>\n {on ? \"★\" : \"☆\"}\n </Text>\n </Pressable>\n );\n })}\n </View>\n );\n}\n\n// ── Emoji (CSAT_EMOJI) ────────────────────────────────────────────────────────\n\nfunction EmojiInput({ options, theme, value, onPick }: { options: EmojiOption[]; theme: SurveyTheme; value: string | undefined; onPick: (v: string) => void }) {\n return (\n <View style={styles.emojiRow}>\n {options.map((o) => {\n const on = value === o.value;\n return (\n <Pressable\n key={o.value}\n accessibilityRole=\"button\"\n accessibilityLabel={o.label || o.value}\n accessibilityState={{ selected: on }}\n onPress={() => onPick(o.value)}\n style={({ pressed }) => [\n styles.emojiCell,\n {\n borderRadius: theme.controlRadius,\n backgroundColor: on ? theme.accentTintStrong : theme.surface,\n borderColor: on ? theme.accent : theme.border,\n opacity: pressed ? 0.85 : 1,\n },\n ]}\n >\n <Text allowFontScaling={false} style={styles.emojiGlyph}>\n {o.emoji}\n </Text>\n {!!o.label && (\n <Text maxFontSizeMultiplier={MAX_FONT_SCALE} style={[font(theme, 13), { color: theme.secondaryText, textAlign: \"center\" }]}>\n {o.label}\n </Text>\n )}\n </Pressable>\n );\n })}\n </View>\n );\n}\n\n// ── Thumbs ────────────────────────────────────────────────────────────────────\n\nfunction ThumbsInput({ theme, value, onPick }: { theme: SurveyTheme; value: string | undefined; onPick: (v: \"up\" | \"down\") => void }) {\n const sides = [\n { value: \"up\" as const, emoji: \"👍\", label: \"Thumbs up\" },\n { value: \"down\" as const, emoji: \"👎\", label: \"Thumbs down\" },\n ];\n return (\n <View style={styles.thumbsRow}>\n {sides.map((s) => {\n const on = value === s.value;\n return (\n <Pressable\n key={s.value}\n accessibilityRole=\"button\"\n accessibilityLabel={s.label}\n accessibilityState={{ selected: on }}\n onPress={() => onPick(s.value)}\n style={({ pressed }) => [\n styles.thumb,\n {\n height: theme.controlHeight,\n borderRadius: clampRadius(theme.controlRadius, Infinity, theme.controlHeight),\n backgroundColor: on ? theme.accent : theme.surface,\n borderColor: on ? theme.accent : theme.border,\n opacity: pressed ? 0.85 : 1,\n },\n ]}\n >\n <Text allowFontScaling={false} style={styles.thumbGlyph}>\n {s.emoji}\n </Text>\n </Pressable>\n );\n })}\n </View>\n );\n}\n\n// ── Single choice ─────────────────────────────────────────────────────────────\n\nfunction ChoiceInput({ options, theme, value, onPick }: { options: ChoiceOption[]; theme: SurveyTheme; value: string | undefined; onPick: (v: string) => void }) {\n return (\n <View style={styles.choices}>\n {options.map((o) => {\n const on = value === o.value;\n return (\n <Pressable\n key={o.value}\n accessibilityRole=\"radio\"\n accessibilityLabel={o.label}\n accessibilityState={{ checked: on }}\n onPress={() => onPick(o.value)}\n style={({ pressed }) => [\n styles.choice,\n {\n minHeight: theme.controlHeight,\n borderRadius: clampRadius(theme.controlRadius, Infinity, theme.controlHeight),\n backgroundColor: on ? theme.accentTint : theme.surface,\n borderColor: on ? theme.accent : theme.border,\n opacity: pressed ? 0.85 : 1,\n },\n ]}\n >\n <Text style={[font(theme, 16), styles.choiceLabel, { color: theme.text }]}>{o.label}</Text>\n <View\n style={[\n styles.radio,\n on ? { backgroundColor: theme.accent, borderColor: theme.accent } : { borderColor: theme.border },\n ]}\n >\n {on && (\n <Text allowFontScaling={false} style={[styles.radioCheck, { color: theme.accentText }]}>\n ✓\n </Text>\n )}\n </View>\n </Pressable>\n );\n })}\n </View>\n );\n}\n\n// ── Open text ─────────────────────────────────────────────────────────────────\n\nfunction OpenTextInput({ placeholder, maxLength, theme, autoFocus, onText }: { placeholder?: string; maxLength?: number; theme: SurveyTheme; autoFocus?: boolean; onText: (t: string) => void }) {\n const [text, setText] = useState(\"\");\n const [focused, setFocused] = useState(false);\n return (\n <View>\n <TextInput\n multiline\n // Raise the keyboard as soon as the question shows, like iOS `activate()`.\n autoFocus={autoFocus}\n value={text}\n onChangeText={(t) => {\n setText(t);\n onText(t);\n }}\n onFocus={() => setFocused(true)}\n onBlur={() => setFocused(false)}\n placeholder={placeholder}\n placeholderTextColor={theme.secondaryText}\n maxLength={maxLength}\n textAlignVertical=\"top\"\n style={[\n font(theme, 16),\n styles.textArea,\n {\n minHeight: theme.controlHeight * 2,\n borderRadius: theme.controlRadius,\n borderColor: focused ? theme.accent : theme.border,\n backgroundColor: theme.surface,\n color: theme.text,\n },\n ]}\n />\n {maxLength !== undefined && (\n <Text style={[font(theme, 13), styles.counter, { color: theme.secondaryText }]}>\n {text.length}/{maxLength}\n </Text>\n )}\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n scaleRow: { flexDirection: \"row\", gap: CHIP_GAP },\n wrap: { flexWrap: \"wrap\", justifyContent: \"center\" },\n chip: { borderWidth: 1, alignItems: \"center\", justifyContent: \"center\", paddingHorizontal: 10 },\n endLabels: { flexDirection: \"row\", gap: 12, marginTop: 10, paddingHorizontal: 2 },\n endLabel: { flex: 1 },\n starsRow: { flexDirection: \"row\", justifyContent: \"center\", gap: 6, height: 48, alignItems: \"center\" },\n star: { paddingHorizontal: 2 },\n emojiRow: { flexDirection: \"row\", flexWrap: \"wrap\", justifyContent: \"center\", columnGap: 10, rowGap: 12 },\n emojiCell: { minWidth: 64, paddingVertical: 8, paddingHorizontal: 10, borderWidth: 1, alignItems: \"center\", gap: 2 },\n emojiGlyph: { fontSize: 32, lineHeight: 40 },\n thumbsRow: { flexDirection: \"row\", gap: 16 },\n thumb: { flex: 1, borderWidth: 1, alignItems: \"center\", justifyContent: \"center\" },\n thumbGlyph: { fontSize: 32, lineHeight: 40 },\n choices: { gap: 10 },\n choice: { flexDirection: \"row\", alignItems: \"center\", borderWidth: 1, paddingVertical: 14, paddingHorizontal: 16, gap: 12 },\n choiceLabel: { flex: 1 },\n radio: { width: 22, height: 22, borderRadius: 11, borderWidth: 1.5, alignItems: \"center\", justifyContent: \"center\" },\n radioCheck: { fontSize: 13, lineHeight: 16, fontWeight: \"700\" },\n textArea: { borderWidth: 1, paddingHorizontal: 16, paddingTop: 12, paddingBottom: 12 },\n counter: { marginTop: 6, textAlign: \"right\" },\n});\n","//\n// theme.ts\n//\n// Maps the dashboard's `ProjectTheme` onto concrete style values, starting from\n// the same light/dark defaults as iOS `SurveyTheme.default` and overriding only\n// the keys provided (port of iOS `Presenter.makeTheme`). Pure, so it's unit\n// tested without a device.\n//\n\nimport type { ProjectTheme } from \"../core\";\n\nexport type ColorScheme = \"light\" | \"dark\";\nexport type FontWeight = \"400\" | \"500\" | \"600\" | \"700\";\n\nexport interface SurveyTheme {\n /** Dim behind the sheet/dialog. */\n scrim: string;\n surface: string;\n text: string;\n secondaryText: string;\n accent: string;\n accentText: string;\n border: string;\n /** Neutral fill (close button, unselected tracks). */\n track: string;\n /** Selected-control tints (accent at low opacity). */\n accentTint: string;\n accentTintStrong: string;\n\n /** Dialog corner radius, and the sheet's when `cornerRadius` is configured. */\n cornerRadius: number;\n /** Sheet top-corner radius: device-like by default, `cornerRadius` if set. */\n sheetCornerRadius: number;\n /** No `cornerRadius` configured: sheets keep the platform's native corners. */\n nativeSheetCorners: boolean;\n /** Resolved for dark mode (drives chrome the dashboard theme doesn't cover). */\n dark: boolean;\n controlRadius: number;\n controlHeight: number;\n spacing: number;\n\n /** Body/option/button/caption text multiplier (not the title). */\n textScale: number;\n titleSize: number;\n titleWeight: FontWeight;\n titleLineHeight: number;\n titleLetterSpacing: number;\n\n position: \"bottom\" | \"center\";\n align: \"left\" | \"center\";\n /** A host-registered font family, or undefined for the system font. */\n fontFamily?: string;\n}\n\nconst PALETTES: Record<ColorScheme, Pick<SurveyTheme, \"surface\" | \"text\" | \"secondaryText\" | \"accent\" | \"accentText\" | \"border\" | \"track\"> & { background: string }> = {\n light: {\n background: \"#09090B\",\n surface: \"#FFFFFF\",\n text: \"#18181B\",\n secondaryText: \"#71717A\",\n accent: \"#2E7272\", // Slate Teal (brand primary)\n accentText: \"#FFFFFF\",\n border: \"#E4E4E7\",\n track: \"#F4F4F5\",\n },\n dark: {\n background: \"#000000\",\n surface: \"#1A1A1E\",\n text: \"#FAFAFA\",\n secondaryText: \"#A1A1AA\",\n accent: \"#41B2B2\",\n accentText: \"#FFFFFF\",\n border: \"#333338\",\n track: \"#27272A\",\n },\n};\n\nconst WEIGHTS: Record<string, FontWeight> = { regular: \"400\", medium: \"500\", semibold: \"600\", bold: \"700\" };\n\nexport interface ResolveThemeOptions {\n scheme?: ColorScheme;\n /** Per-survey `presentation` (\"sheet\" | \"dialog\"), overriding the theme position. */\n presentation?: string | null;\n /** Font family the host registered (e.g. via expo-font). */\n fontFamily?: string;\n}\n\nexport function resolveTheme(project: ProjectTheme | null | undefined, opts: ResolveThemeOptions = {}): SurveyTheme {\n const p = project ?? {};\n const base = PALETTES[opts.scheme ?? \"light\"];\n\n const accent = color(p.accent) ?? base.accent;\n const controlHeight = num(p.controlHeight) ?? 48;\n let cornerRadius = 16;\n let sheetCornerRadius = 28;\n let controlRadius = 12;\n // A configured cornerRadius overrides the device-like sheet corner too, and\n // seeds the control radius (iOS: radius - 2) unless controlRadius is set.\n const cr = num(p.cornerRadius);\n if (cr !== undefined) {\n cornerRadius = cr;\n sheetCornerRadius = cr;\n controlRadius = Math.max(0, cr - 2);\n }\n controlRadius = num(p.controlRadius) ?? controlRadius;\n if (p.controlPill === true) controlRadius = controlHeight / 2;\n\n let position: SurveyTheme[\"position\"] = p.position === \"center\" ? \"center\" : \"bottom\";\n switch (opts.presentation) {\n case \"dialog\":\n case \"center\":\n position = \"center\";\n break;\n case \"sheet\":\n case \"bottom\":\n position = \"bottom\";\n break;\n }\n\n return {\n // A fixed ~40% dim of the (opaque) configured background, like iOS.\n scrim: withAlpha(color(p.background) ?? base.background, 0.4),\n surface: color(p.surface) ?? base.surface,\n text: color(p.text) ?? base.text,\n secondaryText: color(p.secondaryText) ?? base.secondaryText,\n accent,\n accentText: color(p.accentText) ?? base.accentText,\n border: color(p.border) ?? base.border,\n track: base.track,\n accentTint: withAlpha(accent, 0.1),\n accentTintStrong: withAlpha(accent, 0.12),\n cornerRadius,\n sheetCornerRadius,\n nativeSheetCorners: cr === undefined,\n dark: opts.scheme === \"dark\",\n controlRadius,\n controlHeight,\n spacing: num(p.spacing) ?? 16,\n textScale: Math.max(0.5, num(p.textScale) ?? 1),\n titleSize: num(p.titleSize) ?? 20,\n titleWeight: WEIGHTS[(p.titleWeight ?? \"\").toLowerCase()] ?? \"600\",\n titleLineHeight: num(p.titleLineHeight) ?? 1.1,\n titleLetterSpacing: num(p.titleLetterSpacing) ?? 0,\n position,\n align: p.alignment === \"center\" ? \"center\" : \"left\",\n fontFamily: opts.fontFamily,\n };\n}\n\n/** Corner radius for a control of the given size: a pill radius past half the\n * shorter side would distort, so clamp it (as iOS `ChipButton` does). */\nexport function clampRadius(radius: number, width: number, height: number): number {\n return Math.min(radius, Math.min(width, height) / 2);\n}\n\nfunction num(v: unknown): number | undefined {\n return typeof v === \"number\" && Number.isFinite(v) ? v : undefined;\n}\n\n/** Normalizes `#RGB`, `#RRGGBB` or `#RRGGBBAA` (with or without `#`) to\n * `#RRGGBB[AA]`. Returns undefined for empty/invalid input so callers keep\n * their default. */\nexport function color(hex: string | null | undefined): string | undefined {\n if (typeof hex !== \"string\") return undefined;\n let h = hex.trim().replace(/^#/, \"\");\n if (h.length === 3) h = h.replace(/./g, (c) => c + c);\n if (!/^[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(h)) return undefined;\n return \"#\" + h.toUpperCase();\n}\n\n/** `#RRGGBB[AA]` → `rgba(r, g, b, alpha)` (replacing any existing alpha). */\nexport function withAlpha(hex: string, alpha: number): string {\n const h = (color(hex) ?? \"#000000\").slice(1);\n const r = parseInt(h.slice(0, 2), 16);\n const g = parseInt(h.slice(2, 4), 16);\n const b = parseInt(h.slice(4, 6), 16);\n return `rgba(${r}, ${g}, ${b}, ${alpha})`;\n}\n","//\n// MicroSurvey.tsx\n//\n// `<MicroSurvey surveyId>` — renders a specific survey **inline** in a screen\n// (no overlay), e.g. in a settings or feedback screen. Pulls the survey from\n// the cached config and records an impression + response when it closes. It\n// ignores triggers and platform targeting: rendering it is an explicit choice.\n//\n\nimport { useContext, useEffect, useMemo, useRef, useState } from \"react\";\nimport { View, useColorScheme } from \"react-native\";\nimport type { StyleProp, ViewStyle } from \"react-native\";\nimport type { Survey, SurveyResult } from \"./core\";\nimport { MicroSurveysContext } from \"./provider\";\nimport { SurveyCard } from \"./ui/SurveyCard\";\nimport { resolveTheme } from \"./ui/theme\";\n\nexport interface MicroSurveyProps {\n surveyId: string;\n /** Called with the outcome after the survey closes. */\n onComplete?: (result: SurveyResult) => void;\n /** Style for the card container (margins, width, …). */\n style?: StyleProp<ViewStyle>;\n}\n\nexport function MicroSurvey({ surveyId, onComplete, style }: MicroSurveyProps) {\n const { instance, fontFamily } = useContext(MicroSurveysContext);\n const scheme = useColorScheme() === \"dark\" ? \"dark\" : \"light\";\n const [survey, setSurvey] = useState<Survey | null>(null);\n const [closed, setClosed] = useState(false);\n const shownAt = useRef<Date | null>(null);\n const result = useRef<SurveyResult | null>(null);\n\n useEffect(() => {\n if (!instance) return;\n // Fires once config is loaded, then on every refresh (the survey may not be cached yet).\n return instance.onConfigChange(() => setSurvey(instance.getSurvey(surveyId) ?? null));\n }, [instance, surveyId]);\n\n const projectTheme = instance?.getTheme();\n const theme = useMemo(() => resolveTheme(projectTheme, { scheme, fontFamily }), [projectTheme, scheme, fontFamily]);\n\n if (!instance || !survey || closed) return null;\n if (!shownAt.current) shownAt.current = new Date();\n\n return (\n <View\n style={[\n { backgroundColor: theme.surface, borderRadius: theme.cornerRadius, borderWidth: 1, borderColor: theme.border, overflow: \"hidden\" },\n style,\n ]}\n >\n <SurveyCard\n survey={survey}\n theme={theme}\n variant=\"inline\"\n onResult={(r) => {\n result.current = r;\n instance.recordInline(survey, r, shownAt.current ?? new Date());\n }}\n onClose={() => {\n setClosed(true);\n if (result.current) onComplete?.(result.current);\n }}\n />\n </View>\n );\n}\n"],"mappings":";;;;;AAiBA,OAAO,kBAAkB;AACzB,SAAS,UAAU,gBAAgB;;;ACC5B,IAAM,qBAAqB;AAa3B,SAAS,OAAe;AAC7B,MAAI;AAEF,UAAM,SAAU,WAA0D;AAC1E,QAAI,UAAU,OAAO,OAAO,eAAe,YAAY;AACrD,aAAO,OAAO,WAAW;AAAA,IAC3B;AAAA,EACF,QAAQ;AAAA,EAER;AAEA,SAAO,uCAAuC,QAAQ,SAAS,CAAC,MAAM;AACpE,UAAM,IAAK,KAAK,OAAO,IAAI,KAAM;AACjC,UAAM,IAAI,MAAM,MAAM,IAAK,IAAI,IAAO;AACtC,WAAO,EAAE,SAAS,EAAE;AAAA,EACtB,CAAC;AACH;;;ACpCA,IAAM,MAAM;AACZ,IAAM,cAAc;AAQb,IAAM,SAAN,MAAa;AAAA,EAClB,YAA6B,IAAqB;AAArB;AAAA,EAAsB;AAAA,EAE3C,OAAsB;AAC5B,UAAM,OAAO,KAAK,GAAG,QAAQ,GAAG;AAChC,QAAI,CAAC,KAAM,QAAO,CAAC;AACnB,QAAI;AACF,YAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,aAAO,MAAM,QAAQ,MAAM,IAAI,SAAS,CAAC;AAAA,IAC3C,QAAQ;AACN,aAAO,CAAC;AAAA,IACV;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AA,MACC,OAAO;AAAA,QACL,EAAE,iBAAiB,MAAM,SAAS,cAAc,MAAM,cAAc,aAAa,GAAG,aAAa,MAAM,QAAQ,UAAU,SAAS;AAAA,QAClI;AAAA,MACF;AAAA,MAEA,0BAAAP;AAAA,QAAC;AAAA;AAAA,UACC;AAAA,UACA;AAAA,UACA,SAAQ;AAAA,UACR,UAAU,CAAC,MAAM;AACf,mBAAO,UAAU;AACjB,qBAAS,aAAa,QAAQ,GAAG,QAAQ,WAAW,oBAAI,KAAK,CAAC;AAAA,UAChE;AAAA,UACA,SAAS,MAAM;AACb,sBAAU,IAAI;AACd,gBAAI,OAAO,QAAS,cAAa,OAAO,OAAO;AAAA,UACjD;AAAA;AAAA,MACF;AAAA;AAAA,EACF;AAEJ;","names":["DEFAULT_BASE_URL","DEFAULT_CONFIG_TTL_MS","useEffect","useMemo","useRef","useState","useEffect","useMemo","useRef","useState","Animated","Platform","Pressable","StyleSheet","View","useState","Platform","Pressable","StyleSheet","Text","View","Platform","Platform","Platform","Pressable","StyleSheet","View","jsx","View","styles","Pressable","StyleSheet","jsx","jsxs","SurveyCard","useState","advance","View","styles","Text","Pressable","Platform","StyleSheet","jsx","jsxs","useMemo","useRef","Platform","Animated","useState","useEffect","View","StyleSheet","Pressable","styles","jsx","jsxs","useState","useEffect","useMemo","useRef","useContext","useEffect","useMemo","useRef","useState","View","useColorScheme","jsx","useContext","useColorScheme","useState","useRef","useEffect","useMemo","View"]}
1
+ {"version":3,"sources":["../src/MicroSurveys.ts","../src/core/storage.ts","../src/core/outbox.ts","../src/core/types.ts","../src/core/apiClient.ts","../src/core/persistence.ts","../src/core/identity.ts","../src/core/sampling.ts","../src/core/triggerSequencer.ts","../src/core/triggerEngine.ts","../src/core/eventCounter.ts","../src/core/debug.ts","../src/core/version.ts","../src/core/client.ts","../src/amplitude.ts","../src/asyncStorage.ts","../src/provider.tsx","../src/ui/SurveyModal.tsx","../src/ui/SurveyCard.tsx","../src/ui/CloseButton.tsx","../src/ui/platform.ts","../src/ui/questions.tsx","../src/ui/theme.ts","../src/MicroSurvey.tsx"],"sourcesContent":["//\n// MicroSurveys.ts\n//\n// Public entry point, mirroring iOS `MicroSurveysSDK`. A host wires it up in a\n// few lines, usually at module scope so it can be shared:\n//\n// export const ms = new MicroSurveys({ apiKey: \"ms_live_…\" });\n// amplitude.add(ms.amplitudePlugin()); // forward events + identity\n// ms.start(); // fetch config + flush outbox\n//\n// then mounts <MicroSurveysProvider instance={ms}> to render surveys. It wraps\n// the survey engine (./core) with React Native storage (AsyncStorage), the\n// `AppState` foreground signal and the device platform. Storage loads\n// asynchronously, so calls made before it's ready are buffered and replayed in\n// order.\n//\n\nimport AsyncStorage from \"@react-native-async-storage/async-storage\";\nimport { AppState, Platform } from \"react-native\";\nimport { createClient } from \"./core\";\nimport type {\n ActiveSurvey,\n AnalyticsIdentity,\n KeyValueStorage,\n MicroSurveysClient,\n ProjectTheme,\n Survey,\n SurveyResult,\n} from \"./core\";\nimport { createAmplitudePlugin } from \"./amplitude\";\nimport type { MicroSurveysAmplitudePlugin } from \"./amplitude\";\nimport { hydrateAsyncStorage } from \"./asyncStorage\";\nimport type { AsyncKeyValueStorage } from \"./asyncStorage\";\n\n/** Default API base. Override via `apiBaseURL` for self-hosted deployments. */\nconst DEFAULT_BASE_URL = \"https://console.microsurveys.ai\";\n/** Cached config counts as fresh for 12h on app-foreground, like iOS. */\nconst DEFAULT_CONFIG_TTL_MS = 12 * 60 * 60 * 1000;\n\nexport interface MicroSurveysOptions {\n /** Project API key (`ms_live_…` / `ms_test_…`) from the dashboard. */\n apiKey: string;\n /** Override for self-hosted deployments. Defaults to https://console.microsurveys.ai. */\n apiBaseURL?: string;\n /** Refresh config (when stale) whenever the app returns to the foreground.\n * Default true. (Queued impressions/responses are retried on every foreground\n * either way.) */\n refreshOnForeground?: boolean;\n /** Foreground freshness window for the cached config, in ms. Default 12h. */\n configTTLms?: number;\n /** A synchronous store (e.g. MMKV) to persist into instead of AsyncStorage. */\n storage?: KeyValueStorage;\n /** An async store to persist into. Defaults to `@react-native-async-storage/async-storage`. */\n asyncStorage?: AsyncKeyValueStorage;\n /** Your app's version (e.g. \"3.2.0\"), sent with responses so results can be\n * compared across releases. With Expo: `Application.nativeApplicationVersion`. */\n appVersion?: string;\n}\n\nfunction appStateForeground(onForeground: () => void): () => void {\n const sub = AppState.addEventListener(\"change\", (state) => {\n if (state === \"active\") onForeground();\n });\n return () => sub.remove();\n}\n\nfunction appStateBackground(onBackground: () => void): () => void {\n const sub = AppState.addEventListener(\"change\", (state) => {\n if (state === \"background\") onBackground();\n });\n return () => sub.remove();\n}\n\nexport class MicroSurveys {\n readonly apiKey: string;\n /** Resolves with the underlying runtime once storage has loaded. */\n readonly ready: Promise<MicroSurveysClient>;\n\n private client: MicroSurveysClient | null = null;\n private pending: ((client: MicroSurveysClient) => void)[] = [];\n\n constructor(opts: MicroSurveysOptions) {\n this.apiKey = opts.apiKey;\n const storage: Promise<KeyValueStorage> = opts.storage\n ? Promise.resolve(opts.storage)\n : hydrateAsyncStorage(opts.asyncStorage ?? (AsyncStorage as unknown as AsyncKeyValueStorage));\n\n this.ready = storage.then((kv) => {\n const client = createClient({\n apiKey: opts.apiKey,\n apiBaseURL: opts.apiBaseURL ?? DEFAULT_BASE_URL,\n configTTLms: opts.configTTLms ?? DEFAULT_CONFIG_TTL_MS,\n refreshOnForeground: opts.refreshOnForeground ?? true,\n // Survey platform targeting: \"ios\" | \"android\".\n platform: Platform.OS,\n osVersion: String(Platform.Version),\n appVersion: opts.appVersion,\n storage: kv,\n subscribeForeground: appStateForeground,\n subscribeBackground: appStateBackground,\n });\n this.client = client;\n const queued = this.pending;\n this.pending = [];\n for (const run of queued) run(client);\n return client;\n });\n }\n\n /** Runs `fn` now if the runtime is ready, otherwise as soon as it is. */\n private withClient(fn: (client: MicroSurveysClient) => void): void {\n if (this.client) fn(this.client);\n else this.pending.push(fn);\n }\n\n // ── Lifecycle ────────────────────────────────────────────────────────────────\n\n /** Flushes queued impressions/responses, refreshes the config, and starts the\n * foreground refresh. Safe to call once early in app launch (the provider\n * calls it for you unless `autoStart={false}`). */\n start(): void {\n this.withClient((c) => c.start());\n }\n\n /** Stops foreground refresh and cancels pending (delayed) presentations. */\n stop(): void {\n this.withClient((c) => c.stop());\n }\n\n /** Forces an ETag-aware config refresh. Keeps the cache on failure. */\n async refreshConfig(): Promise<void> {\n const client = await this.ready;\n await client.refreshConfig();\n }\n\n // ── Identity + events ────────────────────────────────────────────────────────\n\n /** Identify the current user and/or attach properties used by audience\n * targeting. Optional with Amplitude (identity flows in via the plugin). */\n identify(userId: string | null | undefined, properties?: Record<string, unknown>): void {\n this.withClient((c) => c.identify(userId, properties));\n }\n\n /** Record an event. An eligible survey presents itself after its configured\n * delay. Not needed for events that already flow through Amplitude. */\n track(name: string, properties?: Record<string, unknown>): void {\n this.withClient((c) => c.track(name, properties));\n }\n\n /** Identity forwarded by an analytics SDK. Used by the Amplitude plugin. */\n updateAnalyticsIdentity(update: AnalyticsIdentity): void {\n this.withClient((c) => c.updateAnalyticsIdentity(update));\n }\n\n /** The enrichment plugin to register on your Amplitude instance:\n * `amplitude.add(ms.amplitudePlugin())`. Forwards events + identity into the\n * SDK and returns every event unmodified. */\n amplitudePlugin(): MicroSurveysAmplitudePlugin {\n return createAmplitudePlugin(this);\n }\n\n // ── Config + presentation (used by the provider and inline surveys) ──────────\n\n getTheme(): ProjectTheme | null {\n return this.client?.getTheme() ?? null;\n }\n\n getSurvey(surveyId: string): Survey | undefined {\n return this.client?.getSurvey(surveyId);\n }\n\n /** Subscribe to config loads/refreshes. Fires once when the cached config\n * becomes available. Returns an unsubscribe function. */\n onConfigChange(cb: () => void): () => void {\n let unsubscribe: (() => void) | null = null;\n let cancelled = false;\n this.withClient((c) => {\n if (cancelled) return;\n unsubscribe = c.onConfigChange(cb);\n cb();\n });\n return () => {\n cancelled = true;\n unsubscribe?.();\n };\n }\n\n /** Subscribe to auto-triggered surveys. Returns an unsubscribe function. */\n onPresent(cb: (active: ActiveSurvey) => void): () => void {\n let unsubscribe: (() => void) | null = null;\n let cancelled = false;\n this.withClient((c) => {\n if (!cancelled) unsubscribe = c.onPresent(cb);\n });\n return () => {\n cancelled = true;\n unsubscribe?.();\n };\n }\n\n /** Starts one showing of an inline `<MicroSurvey>`: call `shown` once it\n * renders (sends the impression) and `close` with its outcome. */\n presentInline(survey: Survey): ActiveSurvey {\n let inner: ActiveSurvey | null = null;\n const withShowing = (fn: (s: ActiveSurvey) => void) =>\n this.withClient((c) => {\n inner ??= c.presentInline(survey);\n fn(inner);\n });\n return {\n survey,\n trigger: null,\n shown: () => withShowing((s) => s.shown()),\n close: (result) => withShowing((s) => s.close(result)),\n };\n }\n\n /** Records the outcome of an inline survey in one go, at close. Prefer\n * `presentInline`, which sends the impression when the survey appears. */\n recordInline(survey: Survey, result: SurveyResult, shownAt: Date): void {\n this.withClient((c) => c.recordInline(survey, result, shownAt));\n }\n}\n","//\n// storage.ts\n//\n// Primitives shared by the persistence layers. Every store takes a\n// `KeyValueStorage`: AsyncStorage preloaded into memory (see ../asyncStorage.ts),\n// or a synchronous store such as MMKV.\n//\n\n/** Synchronous string key/value storage the runtime persists into.\n * Implementations should swallow their own errors\n * (quota, disabled storage): persistence is best-effort. */\nexport interface KeyValueStorage {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\n/** Prefix of every key the runtime writes, so adapters can scope reads (e.g.\n * preloading only MicroSurveys keys from an async store). */\nexport const STORAGE_KEY_PREFIX = \"com.microsurveys.\";\n\n/** In-memory storage (nothing survives a restart). Useful for tests. */\nexport function memoryStorage(initial?: Record<string, string>): KeyValueStorage {\n const map = new Map<string, string>(Object.entries(initial ?? {}));\n return {\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => void map.set(key, value),\n removeItem: (key) => void map.delete(key),\n };\n}\n\n/** A v4 UUID, using `crypto.randomUUID` when available with a safe fallback. */\nexport function uuid(): string {\n try {\n // Hermes has no `crypto` unless a polyfill (e.g. expo-crypto) installs one.\n const crypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (crypto && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n /* fall through */\n }\n // RFC-4122-ish fallback.\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/** Current time in **seconds** since the Unix epoch — matches the iOS runtime's\n * `Date.timeIntervalSince1970`, which all persisted timestamps use. */\nexport function nowSeconds(): number {\n return Date.now() / 1000;\n}\n","//\n// outbox.ts\n//\n// FIFO, persisted queue of pending POSTs (impressions/responses), so\n// ingest survives offline restarts. The API client retries it with a backoff,\n// on every return to the foreground, and on the next start. Each entry\n// carries a UUID so it can be removed after a successful send. Port of the\n// `Outbox` in iOS `APIClient.swift`.\n//\n\nimport { uuid } from \"./storage\";\nimport type { KeyValueStorage } from \"./storage\";\n\nconst KEY = \"com.microsurveys.outbox\";\nconst MAX_ENTRIES = 200;\n\nexport interface OutboxEntry {\n id: string;\n path: string; // e.g. \"/api/sdk/impressions\"\n body: string; // pre-encoded JSON body\n}\n\nexport class Outbox {\n constructor(private readonly kv: KeyValueStorage) {}\n\n private read(): OutboxEntry[] {\n const data = this.kv.getItem(KEY);\n if (!data) return [];\n try {\n const parsed = JSON.parse(data) as OutboxEntry[];\n return Array.isArray(parsed) ? parsed : [];\n } catch {\n return [];\n }\n }\n\n private write(entries: OutboxEntry[]): void {\n this.kv.setItem(KEY, JSON.stringify(entries));\n }\n\n enqueue(path: string, body: string): void {\n const entries = this.read();\n entries.push({ id: uuid(), path, body });\n if (entries.length > MAX_ENTRIES) entries.splice(0, entries.length - MAX_ENTRIES);\n this.write(entries);\n }\n\n snapshot(): OutboxEntry[] {\n return this.read();\n }\n\n remove(id: string): void {\n this.write(this.read().filter((e) => e.id !== id));\n }\n}\n","//\n// types.ts\n//\n// TypeScript mirror of the SDK API wire contract and the iOS\n// `Models.swift` / `RuntimeModels.swift`. Also includes the loose→typed config\n// normalization (port of `Question.buildConfig` / `Trigger.init(from:)`) so the\n// rest of the engine works against fully-defaulted values.\n//\n\n// ── JSON ────────────────────────────────────────────────────────────────────\n\nexport type Json = string | number | boolean | null | Json[] | { [key: string]: Json };\nexport type JsonObject = { [key: string]: Json };\n\n// ── Questions ───────────────────────────────────────────────────────────────\n\nexport type QuestionType =\n | \"NPS\"\n | \"CES\"\n | \"CSAT_STAR\"\n | \"CSAT_EMOJI\"\n | \"THUMBS\"\n | \"SINGLE_CHOICE\"\n | \"OPEN_TEXT\";\n\nexport interface EmojiOption {\n value: string;\n emoji: string;\n label?: string;\n}\n\nexport interface ChoiceOption {\n value: string;\n label: string;\n}\n\n/** Typed, defaulted per-type config — port of iOS `QuestionConfig`. NPS and CES\n * share the numeric-scale shape; `type` disambiguates defaults + answer shape. */\nexport type QuestionConfig =\n | { kind: \"scale\"; min: number; max: number; minLabel?: string; maxLabel?: string }\n | { kind: \"stars\"; count: number }\n | { kind: \"emoji\"; options: EmojiOption[] }\n | { kind: \"thumbs\" }\n | { kind: \"singleChoice\"; options: ChoiceOption[] }\n | { kind: \"openText\"; placeholder?: string; maxLength?: number };\n\nexport interface Question {\n id: string;\n order: number;\n type: QuestionType;\n prompt: string;\n required: boolean;\n config: QuestionConfig;\n}\n\n// ── Triggers ──────────────────────────────────────────────────────────────\n\nexport type TriggerType = \"SINGLE\" | \"SEQUENCE\";\n\nexport interface TriggerStep {\n order: number;\n event: string;\n match: JsonObject;\n}\n\nexport interface Trigger {\n id: string;\n type: TriggerType;\n delaySeconds: number;\n sequenceWindowSeconds: number | null;\n fireEvery: number;\n warmupCount: number;\n steps: TriggerStep[];\n}\n\n// ── Survey + config envelope ─────────────────────────────────────────────────\n\nexport interface Survey {\n id: string;\n name: string;\n questions: Question[];\n audienceMatch?: JsonObject | null;\n samplePercent?: number | null;\n maxPerUserDays?: number | null;\n startsAt?: string | null;\n endsAt?: string | null;\n triggers?: Trigger[] | null;\n /** `false` = required: hide the close button + block scrim/swipe dismissal. */\n dismissible?: boolean | null;\n /** `\"sheet\"` | `\"dialog\"` | null (inherit the project theme's position). */\n presentation?: string | null;\n successMessage?: string | null;\n /** Platform targeting for auto-presentation. Empty/absent = all platforms.\n * The engine skips a survey whose list is non-empty and excludes the client's\n * platform. Explicit inline `<MicroSurvey>` embeds ignore this. */\n platforms?: string[] | null;\n}\n\nexport interface SDKConfig {\n projectId: string;\n fetchedAt?: string | null;\n theme: ProjectTheme | null;\n surveys: Survey[];\n /** The project turned event signals on: count tracked events and upload the\n * counts (see eventCounter.ts). Absent on older servers, which means off. */\n eventSignals: boolean;\n /** Hashes of the project's test devices for the live debugger (see debug.ts).\n * Empty when none are set, or on older servers. */\n debugUsers: string[];\n /** The project has server events waiting to be picked up: check the mailbox\n * (`POST /api/sdk/pending`). Absent on older servers, which means off. */\n pendingEvents: boolean;\n /** Trigger event names that arrive by server stream rather than from the app.\n * A sequence waiting on one of them as its next step checks more often. */\n serverEvents: string[];\n}\n\n/** Brand-level survey appearance (API-CONTRACT §Theme). All keys optional. */\nexport interface ProjectTheme {\n accent?: string;\n accentText?: string;\n background?: string;\n surface?: string;\n text?: string;\n secondaryText?: string;\n border?: string;\n cornerRadius?: number | null;\n controlRadius?: number;\n controlPill?: boolean;\n controlHeight?: number;\n spacing?: number;\n textScale?: number;\n position?: string; // \"bottom\" | \"center\"\n alignment?: string; // \"leading\" | \"center\"\n font?: string;\n titleSize?: number;\n titleWeight?: string;\n titleLineHeight?: number;\n titleLetterSpacing?: number;\n}\n\n// ── Device context ───────────────────────────────────────────────────────────\n\n/** Where a survey was shown, sent with impressions and responses so results can\n * be broken down by platform, release and language (API-CONTRACT \"Device\n * context\"). Every field is optional; unknown ones are left out. */\nexport interface DeviceContext {\n platform?: string;\n appVersion?: string;\n osVersion?: string;\n locale?: string;\n}\n\n// ── Identity ─────────────────────────────────────────────────────────────────\n\nexport interface Identity {\n /** Amplitude user id, forwarded by an analytics plugin (e.g. React Native's). */\n amplitudeUserId?: string;\n /** Amplitude device id, forwarded by an analytics plugin. */\n amplitudeDeviceId?: string;\n /** Host-supplied id from `identify()`, for non-Amplitude integrations. */\n hostUserId?: string;\n /** Stable, persisted anonymous id — the final fallback. */\n anonymousId: string;\n /** User properties used for `audienceMatch`. */\n userProperties: JsonObject;\n}\n\n/** `endUserId` = Amplitude userId ?? deviceId ?? host id ?? anonymous id — the\n * same order as iOS `MSIdentity.endUserId`. */\nexport function endUserIdOf(identity: Identity): string {\n return identity.amplitudeUserId ?? identity.amplitudeDeviceId ?? identity.hostUserId ?? identity.anonymousId;\n}\n\n// ── Answers / result ─────────────────────────────────────────────────────────\n\n/** The exact JSON submitted under `answers[].value`, keyed per question type\n * (API-CONTRACT §Answer value shapes). */\nexport type AnswerValue =\n | { value: number } // NPS / CES / CSAT_STAR\n | { value: \"up\" | \"down\" } // THUMBS\n | { value: string } // CSAT_EMOJI (chosen option value)\n | { choice: string } // SINGLE_CHOICE\n | { text: string }; // OPEN_TEXT\n\nexport interface SurveyAnswer {\n questionId: string;\n value: AnswerValue;\n}\n\n/** Outcome handed back when the survey UI closes. */\nexport interface SurveyResult {\n answers: SurveyAnswer[];\n /** `true` if the user advanced through and submitted the final question. */\n completed: boolean;\n /** `true` if closed/dismissed before completing. */\n dismissed: boolean;\n}\n\n// ── Persisted trigger state (port of Persistence.swift structs) ──────────────\n\nexport interface TriggerRecord {\n /** Next sequence step index expected (0 = waiting for step 0). */\n stepIndex: number;\n /** Unix seconds when step 0 was matched, to enforce `sequenceWindowSeconds`. */\n startedAt: number | null;\n /** How many times the trigger's full condition has been satisfied. */\n satisfiedCount: number;\n}\n\nexport interface SurveyRecord {\n /** Unix seconds the survey was last shown to this user, for `maxPerUserDays`. */\n lastShownAt?: number | null;\n /** Sticky sampling decision (computed once, reused forever). */\n sampleDecision?: boolean | null;\n}\n\nexport interface UserTriggerState {\n triggers: Record<string, TriggerRecord>;\n surveys: Record<string, SurveyRecord>;\n}\n\nexport function newTriggerRecord(): TriggerRecord {\n return { stepIndex: 0, startedAt: null, satisfiedCount: 0 };\n}\n\nexport function newUserTriggerState(): UserTriggerState {\n return { triggers: {}, surveys: {} };\n}\n\n// ── Config parsing / normalization (port of the Codable inits) ───────────────\n\nfunction asObject(v: unknown): Record<string, unknown> {\n return v && typeof v === \"object\" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};\n}\n\nfunction numOr(v: unknown, fallback: number): number {\n return typeof v === \"number\" && Number.isFinite(v) ? v : fallback;\n}\n\nfunction strOrUndef(v: unknown): string | undefined {\n return typeof v === \"string\" ? v : undefined;\n}\n\n// Upper bounds on what a config can make the SDK draw. A scale, star row or option list is drawn\n// one control per item, so an absurd value (count: 1000000000) would freeze the app. Real surveys\n// sit far below these; the server applies the same bounds before sending the config.\nconst MAX_SCALE_POINTS = 101;\nconst MAX_SCALE_ABS = 1000;\nconst MAX_STARS = 100;\nconst MAX_OPTIONS = 100;\n\nconst QUESTION_TYPES: readonly QuestionType[] = [\"NPS\", \"CES\", \"CSAT_STAR\", \"CSAT_EMOJI\", \"THUMBS\", \"SINGLE_CHOICE\", \"OPEN_TEXT\"];\n\nfunction boundedScale(min: number, max: number): { min: number; max: number } {\n const lo = Math.min(Math.max(min, -MAX_SCALE_ABS), MAX_SCALE_ABS);\n let hi = Math.min(Math.max(max, -MAX_SCALE_ABS), MAX_SCALE_ABS);\n if (hi - lo > MAX_SCALE_POINTS - 1) hi = lo + MAX_SCALE_POINTS - 1;\n return { min: lo, max: hi };\n}\n\nfunction boundedOptions(raw: unknown): unknown[] {\n return Array.isArray(raw) ? raw.slice(0, MAX_OPTIONS) : [];\n}\n\nfunction normalizeConfig(type: QuestionType, raw: Record<string, unknown>): QuestionConfig {\n switch (type) {\n case \"NPS\":\n return { kind: \"scale\", ...boundedScale(numOr(raw.min, 0), numOr(raw.max, 10)), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };\n case \"CES\":\n return { kind: \"scale\", ...boundedScale(numOr(raw.min, 1), numOr(raw.max, 7)), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };\n case \"CSAT_STAR\":\n return { kind: \"stars\", count: Math.min(numOr(raw.count, 5), MAX_STARS) };\n case \"CSAT_EMOJI\": {\n const opts = boundedOptions(raw.options);\n const options: EmojiOption[] = opts.map((o) => {\n const oo = asObject(o);\n return { value: String(oo.value ?? \"\"), emoji: typeof oo.emoji === \"string\" ? oo.emoji : \"\", label: strOrUndef(oo.label) };\n });\n return { kind: \"emoji\", options };\n }\n case \"THUMBS\":\n return { kind: \"thumbs\" };\n case \"SINGLE_CHOICE\": {\n const opts = boundedOptions(raw.options);\n const options: ChoiceOption[] = opts.map((o) => {\n const oo = asObject(o);\n const value = String(oo.value ?? \"\");\n return { value, label: typeof oo.label === \"string\" ? oo.label : value };\n });\n return { kind: \"singleChoice\", options };\n }\n case \"OPEN_TEXT\":\n return { kind: \"openText\", placeholder: strOrUndef(raw.placeholder), maxLength: typeof raw.maxLength === \"number\" ? raw.maxLength : undefined };\n }\n}\n\nfunction normalizeQuestion(raw: Record<string, unknown>): Question | null {\n const id = strOrUndef(raw.id);\n const type = strOrUndef(raw.type) as QuestionType | undefined;\n const prompt = strOrUndef(raw.prompt);\n if (!id || !type || prompt === undefined) return null;\n return {\n id,\n order: numOr(raw.order, 0),\n type,\n prompt,\n required: raw.required === true,\n config: normalizeConfig(type, asObject(raw.config)),\n };\n}\n\nfunction normalizeTrigger(raw: Record<string, unknown>): Trigger | null {\n const id = strOrUndef(raw.id);\n if (!id) return null;\n const type: TriggerType = raw.type === \"SEQUENCE\" ? \"SEQUENCE\" : \"SINGLE\";\n const steps: TriggerStep[] = (Array.isArray(raw.steps) ? raw.steps : [])\n .map((s) => {\n const so = asObject(s);\n const event = strOrUndef(so.event);\n if (!event) return null;\n return { order: numOr(so.order, 0), event, match: asObject(so.match) as JsonObject };\n })\n .filter((s): s is TriggerStep => s !== null);\n return {\n id,\n type,\n delaySeconds: numOr(raw.delaySeconds, 0),\n sequenceWindowSeconds: typeof raw.sequenceWindowSeconds === \"number\" ? raw.sequenceWindowSeconds : null,\n fireEvery: numOr(raw.fireEvery, 1),\n warmupCount: numOr(raw.warmupCount, 0),\n steps,\n };\n}\n\nfunction normalizeSurvey(raw: Record<string, unknown>): Survey | null {\n const id = strOrUndef(raw.id);\n const name = strOrUndef(raw.name);\n if (!id || name === undefined) return null;\n const rawQuestions = Array.isArray(raw.questions) ? raw.questions : [];\n const rawTriggers = Array.isArray(raw.triggers) ? raw.triggers : [];\n // Skip a survey this SDK version can't show (a newer question or trigger type):\n // there's no renderer for the question, and the trigger would fire by the wrong rule.\n if (\n rawQuestions.some((q) => !QUESTION_TYPES.includes(asObject(q).type as QuestionType)) ||\n rawTriggers.some((t) => { const type = asObject(t).type; return type != null && type !== \"SINGLE\" && type !== \"SEQUENCE\"; })\n ) return null;\n const questions = rawQuestions\n .map((q) => normalizeQuestion(asObject(q)))\n .filter((q): q is Question => q !== null);\n const triggers = rawTriggers\n .map((t) => normalizeTrigger(asObject(t)))\n .filter((t): t is Trigger => t !== null);\n return {\n id,\n name,\n questions,\n audienceMatch: (raw.audienceMatch as JsonObject | null) ?? null,\n samplePercent: typeof raw.samplePercent === \"number\" ? raw.samplePercent : null,\n maxPerUserDays: typeof raw.maxPerUserDays === \"number\" ? raw.maxPerUserDays : null,\n startsAt: strOrUndef(raw.startsAt) ?? null,\n endsAt: strOrUndef(raw.endsAt) ?? null,\n triggers,\n dismissible: typeof raw.dismissible === \"boolean\" ? raw.dismissible : null,\n presentation: strOrUndef(raw.presentation) ?? null,\n successMessage: strOrUndef(raw.successMessage) ?? null,\n platforms: Array.isArray(raw.platforms) ? raw.platforms.filter((p): p is string => typeof p === \"string\") : null,\n };\n}\n\n/** Parse a raw `/api/sdk/config` JSON string into a fully-normalized `SDKConfig`.\n * Returns `null` if the payload is unusable. Lenient by design — the SDK must\n * keep working against an older/newer server shape. */\nexport function parseConfig(rawText: string): SDKConfig | null {\n let root: Record<string, unknown>;\n try {\n root = asObject(JSON.parse(rawText));\n } catch {\n return null;\n }\n const projectId = strOrUndef(root.projectId);\n if (!projectId) return null;\n const surveys = (Array.isArray(root.surveys) ? root.surveys : [])\n .map((s) => normalizeSurvey(asObject(s)))\n .filter((s): s is Survey => s !== null);\n const theme = root.theme && typeof root.theme === \"object\" && !Array.isArray(root.theme) ? (root.theme as ProjectTheme) : null;\n return { projectId, fetchedAt: strOrUndef(root.fetchedAt) ?? null, theme,\n surveys,\n eventSignals: root.eventSignals === true,\n debugUsers: Array.isArray(root.debugUsers) ? root.debugUsers.filter((h): h is string => typeof h === \"string\") : [],\n pendingEvents: root.pendingEvents === true,\n serverEvents: Array.isArray(root.serverEvents) ? root.serverEvents.filter((n): n is string => typeof n === \"string\") : [],\n };\n}\n","//\n// apiClient.ts\n//\n// `fetch`-based client for the SDK endpoints plus outbox flush. Every\n// impression/response carries a UUID `clientId` so the server upserts and\n// retries never duplicate (API-CONTRACT §Idempotency). Port of iOS `APIClient`.\n//\n// A flush that stops on a retryable failure (offline, 429, 5xx) schedules its\n// own retry: 2 s, doubling per failure in a row, capped at 30 s.\n//\n\nimport { Outbox } from \"./outbox\";\nimport { uuid } from \"./storage\";\nimport type { KeyValueStorage } from \"./storage\";\nimport type { EventCount } from \"./eventCounter\";\nimport type { DebugEntry } from \"./debug\";\nimport { parseConfig } from \"./types\";\nimport type { SDKConfig, SurveyAnswer, JsonObject, DeviceContext } from \"./types\";\n\nconst API_VERSION = \"2026-06-30\";\n\nexport type ConfigFetchResult =\n | { kind: \"notModified\" }\n | { kind: \"config\"; rawText: string; config: SDKConfig | null; etag: string | null };\n\n/** One server event waiting in the mailbox (API-CONTRACT §6). */\nexport interface PendingEvent {\n id: string;\n name: string;\n properties: Record<string, unknown>;\n /** ISO 8601: when it happened, not when it arrived. */\n occurredAt: string;\n}\n\n/** The most events `/api/sdk/pending` returns per call. */\nexport const PENDING_PAGE_SIZE = 50;\n\n/** First retry after a failed flush; doubles per failure in a row. */\nexport const RETRY_BASE_MS = 2_000;\n/** Longest wait between retries. */\nexport const RETRY_MAX_MS = 30_000;\n/** An ingest POST that hasn't answered by then is aborted and retried later. */\nexport const INGEST_TIMEOUT_MS = 15_000;\n\n/** One impression as sent to `/api/sdk/impressions`. */\nexport interface ImpressionInput {\n /** Idempotency key; the response from the same showing points back to it.\n * Generated when omitted. */\n clientId?: string;\n surveyId: string;\n triggerId: string | null;\n endUserId: string;\n shownAt: Date;\n dismissed: boolean;\n context: DeviceContext;\n}\n\nexport class ApiClient {\n private readonly apiKey: string;\n private readonly baseURL: string;\n private readonly outbox: Outbox;\n private isFlushing = false;\n /** The flush in progress, returned to callers that ask for another meanwhile. */\n private flushPromise: Promise<void> = Promise.resolve();\n /** Set when flush() is called during a flush: run another pass before finishing. */\n private flushAgain = false;\n private retryTimer: ReturnType<typeof setTimeout> | null = null;\n /** Failed flushes in a row, for the retry backoff. */\n private failures = 0;\n /** After `cancelRetry()`: no new retry timers until the next `resumeRetry()`. */\n private retryStopped = false;\n\n constructor(apiKey: string, baseURL: string, storage: KeyValueStorage) {\n this.apiKey = apiKey;\n this.outbox = new Outbox(storage);\n // Normalize: no trailing slash so `${base}${path}` is clean.\n this.baseURL = baseURL.replace(/\\/+$/, \"\");\n }\n\n // ── Config ─────────────────────────────────────────────────────────────────\n\n /** `GET /api/sdk/config` with optional `If-None-Match`. Resolves `notModified`\n * on 304 so the caller keeps its cache. Throws on network/5xx errors. */\n async fetchConfig(etag: string | null): Promise<ConfigFetchResult> {\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n \"MS-Api-Version\": API_VERSION,\n };\n if (etag) headers[\"If-None-Match\"] = etag;\n\n const res = await fetch(this.endpoint(\"/api/sdk/config\"), { method: \"GET\", headers });\n if (res.status === 304) return { kind: \"notModified\" };\n if (!res.ok) throw new Error(`config fetch failed: ${res.status}`);\n\n const rawText = await res.text();\n return { kind: \"config\", rawText, config: parseConfig(rawText), etag: res.headers.get(\"ETag\") };\n }\n\n // ── Server events mailbox ───────────────────────────────────────────────────\n\n /** `POST /api/sdk/pending`: the server events waiting for this user, oldest\n * first. Each is handed out once, so this is not queued in the outbox. Resolves\n * `[]` without a request when there's no id to ask for. Throws on network/HTTP\n * errors; malformed entries are dropped. */\n async fetchPending(ids: { userId: string | null; deviceId: string | null }): Promise<PendingEvent[]> {\n const body: Record<string, string> = {};\n if (ids.userId) body.userId = ids.userId;\n if (ids.deviceId) body.deviceId = ids.deviceId;\n if (Object.keys(body).length === 0) return [];\n\n const res = await fetch(this.endpoint(\"/api/sdk/pending\"), {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"MS-Api-Version\": API_VERSION,\n \"Content-Type\": \"application/json; charset=utf-8\",\n },\n body: JSON.stringify(body),\n });\n if (!res.ok) throw new Error(`pending fetch failed: ${res.status}`);\n\n const root = (await res.json()) as { events?: unknown };\n const events = Array.isArray(root?.events) ? root.events : [];\n return events.flatMap((raw): PendingEvent[] => {\n const e = raw as Record<string, unknown> | null;\n if (!e || typeof e.id !== \"string\" || typeof e.name !== \"string\" || typeof e.occurredAt !== \"string\") return [];\n if (Number.isNaN(Date.parse(e.occurredAt))) return [];\n const properties =\n e.properties && typeof e.properties === \"object\" && !Array.isArray(e.properties)\n ? (e.properties as Record<string, unknown>)\n : {};\n return [{ id: e.id, name: e.name, properties, occurredAt: e.occurredAt }];\n });\n }\n\n // ── Impressions / responses ─────────────────────────────────────────────────\n\n /** Queues the impression and returns its `clientId`, so the response from the\n * same showing can point back to it. Pass the `clientId` to send the same\n * impression again (e.g. with `dismissed: true` once the user dismissed it):\n * the server updates the one it has. */\n recordImpression(input: ImpressionInput): string {\n const clientId = input.clientId ?? uuid();\n const payload = {\n clientId,\n surveyId: input.surveyId,\n triggerId: input.triggerId ?? undefined,\n endUserId: input.endUserId,\n shownAt: input.shownAt.toISOString(),\n dismissed: input.dismissed,\n context: input.context,\n };\n this.enqueue(\"/api/sdk/impressions\", { impressions: [payload] });\n return clientId;\n }\n\n recordResponse(input: {\n surveyId: string;\n endUserId: string;\n completed: boolean;\n submittedAt: Date;\n userProps: JsonObject;\n impressionId: string;\n triggerId: string | null;\n context: DeviceContext;\n answers: SurveyAnswer[];\n }): void {\n const payload = {\n clientId: uuid(),\n surveyId: input.surveyId,\n endUserId: input.endUserId,\n completed: input.completed,\n submittedAt: input.submittedAt.toISOString(),\n userProps: input.userProps,\n impressionId: input.impressionId,\n triggerId: input.triggerId ?? undefined,\n context: input.context,\n answers: input.answers,\n };\n this.enqueue(\"/api/sdk/responses\", { responses: [payload] });\n }\n\n // ── Event signals ─────────────────────────────────────────────────────────\n\n /** Queues one upload window of event counts. No clientId: a re-sent batch\n * can count twice, which is fine for \"last seen\" and trend lines. */\n recordEventCounts(events: EventCount[], context: DeviceContext & { sdkVersion: string }): void {\n if (events.length === 0) return;\n this.enqueue(\"/api/sdk/events\", { events, context });\n }\n\n // ── Live debugger ─────────────────────────────────────────────────────────\n\n /** Sends one debugger entry from a test device. */\n recordDebug(entry: DebugEntry, endUserId: string, context: DeviceContext & { sdkVersion: string }): void {\n this.enqueue(\"/api/sdk/debug\", { entries: [entry], endUserId, context });\n }\n\n private enqueue(path: string, value: unknown): void {\n this.outbox.enqueue(path, JSON.stringify(value));\n void this.flush();\n }\n\n // ── Flush ────────────────────────────────────────────────────────────────────\n\n /** POSTs queued entries in order. Stops at the first retryable failure (likely\n * offline) and schedules a retry (2 s, doubling, capped at 30 s). Entries\n * queued while a flush is running are sent by the same flush, so nothing waits\n * for the next event. Idempotency keys make re-sends safe. Resolves when the\n * flush in progress is done; never throws. */\n flush(): Promise<void> {\n if (this.isFlushing) {\n // The running flush makes one more pass, so an entry queued after its last\n // look at the outbox isn't left behind.\n this.flushAgain = true;\n return this.flushPromise;\n }\n this.isFlushing = true;\n this.clearRetryTimer();\n this.flushPromise = this.runFlush();\n return this.flushPromise;\n }\n\n /** Stops retrying (the client is stopping). Queued entries stay for later. */\n cancelRetry(): void {\n this.retryStopped = true;\n this.clearRetryTimer();\n }\n\n /** Allows retries again after `cancelRetry()`. */\n resumeRetry(): void {\n this.retryStopped = false;\n }\n\n private async runFlush(): Promise<void> {\n let failed = false;\n // Guards against re-sending an entry whose removal didn't persist (storage full).\n const sent = new Set<string>();\n try {\n do {\n this.flushAgain = false;\n for (;;) {\n const pending = this.outbox.snapshot().filter((e) => !sent.has(e.id));\n if (pending.length === 0) break;\n for (const entry of pending) {\n try {\n await this.post(entry.path, entry.body);\n this.outbox.remove(entry.id);\n sent.add(entry.id);\n } catch {\n failed = true; // network/server problem: retry after a backoff\n break;\n }\n }\n if (failed) break;\n }\n } while (!failed && this.flushAgain);\n } finally {\n // Synchronously after the last look at the outbox: a flush() from here on\n // starts a new pass instead of joining this one.\n this.flushAgain = false;\n this.isFlushing = false;\n }\n\n if (failed) {\n this.failures += 1;\n this.scheduleRetry();\n } else {\n this.failures = 0;\n }\n }\n\n /** One pending retry at most. */\n private scheduleRetry(): void {\n if (this.retryStopped || this.retryTimer) return;\n const delay = Math.min(RETRY_BASE_MS * 2 ** Math.max(0, this.failures - 1), RETRY_MAX_MS);\n this.retryTimer = setTimeout(() => {\n this.retryTimer = null;\n void this.flush();\n }, delay);\n }\n\n private clearRetryTimer(): void {\n if (this.retryTimer) clearTimeout(this.retryTimer);\n this.retryTimer = null;\n }\n\n private async post(path: string, body: string): Promise<void> {\n // A stalled request would hold up the queue; give up on it and retry later.\n const controller = typeof AbortController !== \"undefined\" ? new AbortController() : null;\n const timeout = controller ? setTimeout(() => controller.abort(), INGEST_TIMEOUT_MS) : null;\n try {\n const res = await fetch(this.endpoint(path), {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"MS-Api-Version\": API_VERSION,\n \"Content-Type\": \"application/json; charset=utf-8\",\n },\n body,\n signal: controller?.signal,\n });\n // 429/5xx → throw to retry later. Other 4xx are permanent for this body;\n // treat as done so we don't wedge the queue (matches iOS retry rules).\n if (res.status === 429 || (res.status >= 500 && res.status < 600)) {\n throw new Error(`retryable ${res.status}`);\n }\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n }\n\n private endpoint(path: string): string {\n return this.baseURL + path;\n }\n}\n","//\n// persistence.ts\n//\n// On-device state so the SDK works immediately/offline and trigger progress\n// survives reloads:\n// • ConfigStore — the latest config JSON + parsed surveys/theme + ETag.\n// • TriggerStateStore — per-endUserId sequence progress, occurrence counters,\n// sticky sampling, and last-shown timestamps for the cap.\n//\n// Ports iOS `Persistence.swift`, backed by a `KeyValueStorage` instead of\n// UserDefaults.\n//\n\nimport type { KeyValueStorage } from \"./storage\";\nimport { parseConfig, newUserTriggerState } from \"./types\";\nimport type { SDKConfig, Survey, ProjectTheme, UserTriggerState } from \"./types\";\n\nconst CONFIG_KEY = \"com.microsurveys.config.cache\";\nconst STATE_PREFIX = \"com.microsurveys.triggerstate.\";\n\ninterface PersistedConfig {\n rawConfig: string; // raw response body — parsed losslessly on load\n etag: string | null;\n storedAt: number; // ms epoch\n}\n\n/** Persists the most recent `/api/sdk/config` result so the SDK can evaluate\n * triggers and render surveys immediately on load, before/without a network\n * refresh. We store the raw response text and re-parse it (lossless). */\nexport class ConfigStore {\n private persisted: PersistedConfig | null = null;\n private parsed: SDKConfig | null = null;\n\n constructor(private readonly kv: KeyValueStorage) {\n const data = kv.getItem(CONFIG_KEY);\n if (data) {\n try {\n const entry = JSON.parse(data) as PersistedConfig;\n if (entry && typeof entry.rawConfig === \"string\") {\n this.persisted = entry;\n this.parsed = parseConfig(entry.rawConfig);\n }\n } catch {\n /* corrupt cache — ignore */\n }\n }\n }\n\n get config(): SDKConfig | null {\n return this.parsed;\n }\n\n get surveys(): Survey[] {\n return this.parsed?.surveys ?? [];\n }\n\n get theme(): ProjectTheme | null {\n return this.parsed?.theme ?? null;\n }\n\n get eventSignals(): boolean {\n return this.parsed?.eventSignals ?? false;\n }\n\n get projectId(): string | null {\n return this.parsed?.projectId ?? null;\n }\n\n get debugUsers(): string[] {\n return this.parsed?.debugUsers ?? [];\n }\n\n get pendingEvents(): boolean {\n return this.parsed?.pendingEvents ?? false;\n }\n\n get serverEvents(): string[] {\n return this.parsed?.serverEvents ?? [];\n }\n\n get etag(): string | null {\n return this.persisted?.etag ?? null;\n }\n\n /** When the cached config was last written (ms epoch), for TTL checks. */\n get storedAt(): number | null {\n return this.persisted?.storedAt ?? null;\n }\n\n /** Persists the raw config response and refreshes the in-memory parse. */\n save(rawConfig: string, etag: string | null): void {\n const entry: PersistedConfig = { rawConfig, etag, storedAt: Date.now() };\n this.persisted = entry;\n this.parsed = parseConfig(rawConfig);\n this.kv.setItem(CONFIG_KEY, JSON.stringify(entry));\n }\n}\n\n/** Loads/saves `UserTriggerState` keyed by `endUserId`. Cheap enough to read &\n * rewrite the whole blob per evaluation for MVP volumes. */\nexport class TriggerStateStore {\n constructor(private readonly kv: KeyValueStorage) {}\n\n load(endUserId: string): UserTriggerState {\n const data = this.kv.getItem(STATE_PREFIX + endUserId);\n if (!data) return newUserTriggerState();\n try {\n const parsed = JSON.parse(data) as UserTriggerState;\n return { triggers: parsed.triggers ?? {}, surveys: parsed.surveys ?? {} };\n } catch {\n return newUserTriggerState();\n }\n }\n\n save(endUserId: string, state: UserTriggerState): void {\n this.kv.setItem(STATE_PREFIX + endUserId, JSON.stringify(state));\n }\n\n reset(endUserId: string): void {\n this.kv.removeItem(STATE_PREFIX + endUserId);\n }\n}\n","//\n// identity.ts\n//\n// Maintains the current `Identity` snapshot the engine evaluates against,\n// merging signals from an analytics SDK (Amplitude userId/deviceId/identify\n// properties) and the host (`identify`). Mints/persists a stable anonymous id\n// so cap + trigger state stay consistent across reloads before any user is\n// identified. Port of iOS `IdentityStore`.\n//\n\nimport { uuid } from \"./storage\";\nimport type { KeyValueStorage } from \"./storage\";\nimport type { Identity, Json, JsonObject } from \"./types\";\n\nconst ANON_KEY = \"com.microsurveys.anonymousId\";\nconst PROPS_KEY = \"com.microsurveys.userProperties\";\n\n/** An identity update from an analytics SDK (e.g. the Amplitude plugin). Any\n * field may be absent when unknown; absent fields leave the current value. */\nexport interface AnalyticsIdentity {\n userId?: string | null;\n deviceId?: string | null;\n /** Properties to merge into the user properties (`$set` semantics). */\n userProperties?: Record<string, unknown> | null;\n /** Properties to set only where not already present (`$setOnce` semantics). */\n setOnceProperties?: Record<string, unknown> | null;\n /** Property keys to remove (`$unset` semantics). */\n unsetProperties?: string[] | null;\n}\n\nexport class IdentityStore {\n private identity: Identity;\n\n constructor(private readonly kv: KeyValueStorage) {\n let anon = kv.getItem(ANON_KEY);\n if (!anon) {\n anon = \"anon_\" + uuid();\n kv.setItem(ANON_KEY, anon);\n }\n let userProperties: JsonObject = {};\n const props = kv.getItem(PROPS_KEY);\n if (props) {\n try {\n const parsed = JSON.parse(props) as JsonObject;\n if (parsed && typeof parsed === \"object\") userProperties = parsed;\n } catch {\n /* ignore */\n }\n }\n this.identity = { anonymousId: anon, userProperties };\n }\n\n /** Thread-safe not required (single-threaded JS); returns a shallow snapshot. */\n snapshot(): Identity {\n return { ...this.identity, userProperties: { ...this.identity.userProperties } };\n }\n\n /** Apply a host `identify(id, properties)` call. Merges properties. */\n setUser(id: string | null | undefined, properties?: Record<string, unknown>): void {\n if (id) this.identity.hostUserId = id;\n if (properties) {\n for (const key of Object.keys(properties)) {\n this.identity.userProperties[key] = toJson(properties[key]);\n }\n this.persistProperties();\n }\n }\n\n /** Merge an analytics identity update. Called per event, so it only persists\n * when the properties actually changed. */\n updateFromAnalytics(update: AnalyticsIdentity): void {\n if (update.userId) this.identity.amplitudeUserId = update.userId;\n if (update.deviceId) this.identity.amplitudeDeviceId = update.deviceId;\n let changed = false;\n if (update.userProperties) {\n for (const key of Object.keys(update.userProperties)) {\n const value = toJson(update.userProperties[key]);\n if (JSON.stringify(this.identity.userProperties[key]) !== JSON.stringify(value)) {\n this.identity.userProperties[key] = value;\n changed = true;\n }\n }\n }\n if (update.setOnceProperties) {\n for (const key of Object.keys(update.setOnceProperties)) {\n if (key in this.identity.userProperties) continue;\n this.identity.userProperties[key] = toJson(update.setOnceProperties[key]);\n changed = true;\n }\n }\n for (const key of update.unsetProperties ?? []) {\n if (key in this.identity.userProperties) {\n delete this.identity.userProperties[key];\n changed = true;\n }\n }\n if (changed) this.persistProperties();\n }\n\n private persistProperties(): void {\n this.kv.setItem(PROPS_KEY, JSON.stringify(this.identity.userProperties));\n }\n}\n\n/** Best-effort conversion of an arbitrary host value into a JSON value, for\n * snapshotting user properties (port of iOS `JSONValue(any:)`). */\nfunction toJson(value: unknown): Json {\n if (value === null || value === undefined) return null;\n switch (typeof value) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n return value;\n case \"object\":\n if (Array.isArray(value)) return value.map(toJson);\n return Object.fromEntries(Object.entries(value as Record<string, unknown>).map(([k, v]) => [k, toJson(v)]));\n default:\n return String(value);\n }\n}\n","//\n// sampling.ts\n//\n// Pure helpers used by the trigger engine: deterministic 32-bit FNV-1a sampling\n// and the equality `match` / `audienceMatch` evaluator. Faithful port of the iOS\n// `Sampling.swift` — the same hash on both platforms so bucketing is stable and\n// reproducible cross-platform.\n//\n\nimport type { Json, JsonObject, TriggerStep } from \"./types\";\n\n// ── Deterministic sampling ───────────────────────────────────────────────────\n\nconst encoder = typeof TextEncoder !== \"undefined\" ? new TextEncoder() : null;\n\n/** UTF-8 bytes of `s`, matching Swift's `string.utf8`. Exported for tests. */\nexport function utf8Bytes(s: string, useEncoder = true): Uint8Array {\n if (encoder && useEncoder) return encoder.encode(s);\n // Fallback if TextEncoder is unavailable (older Hermes). Iterates code points so\n // astral characters (surrogate pairs) encode to 4 bytes exactly like Swift.\n const out: number[] = [];\n for (const ch of s) {\n const c = ch.codePointAt(0)!;\n if (c < 0x80) out.push(c);\n else if (c < 0x800) {\n out.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));\n } else if (c < 0x10000) {\n out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n } else {\n out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n }\n }\n return Uint8Array.from(out);\n}\n\n/** 32-bit FNV-1a hash of `s`'s UTF-8 bytes. Returns an unsigned 32-bit integer. */\nexport function fnv1a32(s: string): number {\n let hash = 0x811c9dc5; // FNV offset basis\n const bytes = utf8Bytes(s);\n for (let i = 0; i < bytes.length; i++) {\n hash ^= bytes[i]!;\n // FNV prime 0x01000193, 32-bit wrapping multiply.\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n}\n\n/** `inSample = FNV-1a(endUserId + \":\" + surveyId) % 100 < samplePercent`.\n * `samplePercent` clamps: `>= 100` always in, `<= 0` always out. */\nexport function inSample(endUserId: string, surveyId: string, samplePercent: number): boolean {\n if (samplePercent >= 100) return true;\n if (samplePercent <= 0) return false;\n const bucket = fnv1a32(`${endUserId}:${surveyId}`) % 100;\n return bucket < samplePercent;\n}\n\n// ── Equality matching ────────────────────────────────────────────────────────\n\n/** Formats a number as an integer when it has no fractional part, so `42` and\n * `42.0` compare equal (port of iOS `numberString`). */\nfunction numberString(n: number): string {\n if (Number.isFinite(n) && Math.trunc(n) === n && Math.abs(n) < 1e15) {\n return String(Math.trunc(n));\n }\n return String(n);\n}\n\n/** Stringifies a scalar for comparison. Returns `null` for values that never\n * participate in an equality match (null, objects, arrays, undefined). */\nexport function stringify(value: unknown): string | null {\n switch (typeof value) {\n case \"string\":\n return value;\n case \"boolean\":\n return value ? \"true\" : \"false\";\n case \"number\":\n return numberString(value);\n default:\n return null;\n }\n}\n\n/** True iff every key in `filter` is present in `properties` with an equal\n * (stringified) value. Empty filter ⇒ always true. */\nexport function matches(filter: JsonObject, properties: Record<string, unknown>): boolean {\n for (const key of Object.keys(filter)) {\n const expectedStr = stringify(filter[key]);\n if (expectedStr === null) return false;\n const actualStr = stringify(properties[key]);\n if (actualStr === null) return false;\n if (expectedStr !== actualStr) return false;\n }\n return true;\n}\n\n/** True iff `eventName` equals `step.event` AND `step.match ⊆ properties`. */\nexport function eventMatchesStep(eventName: string, properties: Record<string, unknown>, step: TriggerStep): boolean {\n if (eventName !== step.event) return false;\n return matches(step.match, properties);\n}\n\n/** Audience check: `audience ⊆ userProperties` by stringified equality. */\nexport function audienceMatches(audience: JsonObject, userProperties: Record<string, Json>): boolean {\n return matches(audience, userProperties);\n}\n","//\n// triggerSequencer.ts\n//\n// Pure state machine advancing a trigger's SINGLE/SEQUENCE progress on one\n// incoming event. No clock, no storage, no queues — so the sequence + window\n// ordering rules are unit-testable. Faithful port of iOS `TriggerSequencer`.\n//\n\nimport { eventMatchesStep } from \"./sampling\";\nimport type { Trigger, TriggerRecord } from \"./types\";\n\nexport interface AdvanceResult {\n record: TriggerRecord;\n satisfied: boolean;\n}\n\n/** True iff the sequence window has lapsed since step 0 matched. */\nexport function windowExpired(window: number | null, startedAt: number | null, nowT: number): boolean {\n if (window === null || window <= 0 || startedAt === null) return false;\n return nowT - startedAt > window;\n}\n\n/** Advances `record` for one event. On satisfaction, bumps `satisfiedCount` and\n * resets the sequence progress. Returns a new record (input is not mutated).\n * `nowT` is when the event happened: the current time for a live event, its\n * `occurredAt` for a replayed server event. */\nexport function advance(\n trigger: Trigger,\n record: TriggerRecord,\n eventName: string,\n properties: Record<string, unknown>,\n nowT: number,\n): AdvanceResult {\n const next: TriggerRecord = { ...record };\n const steps = [...trigger.steps].sort((a, b) => a.order - b.order);\n if (steps.length === 0) return { record: next, satisfied: false };\n\n const matchesStep = (index: number): boolean => eventMatchesStep(eventName, properties, steps[index]!);\n\n let satisfied = false;\n\n if (trigger.type === \"SINGLE\") {\n // One step (the first); matching it satisfies the condition.\n satisfied = matchesStep(0);\n } else {\n // SEQUENCE\n const expected = Math.min(next.stepIndex, steps.length - 1);\n\n // A later step can't have happened before the sequence started (a replayed\n // server event older than step 0): ignore it for this sequence, no reset.\n if (expected !== 0 && next.startedAt !== null && nowT < next.startedAt) {\n return { record: next, satisfied: false };\n }\n\n if (matchesStep(expected)) {\n if (expected === 0) {\n next.startedAt = nowT;\n next.stepIndex = 1;\n } else if (windowExpired(trigger.sequenceWindowSeconds, next.startedAt, nowT)) {\n // The sequence window lapsed; restart, re-checking step 0.\n if (matchesStep(0)) {\n next.startedAt = nowT;\n next.stepIndex = 1;\n } else {\n next.stepIndex = 0;\n next.startedAt = null;\n }\n } else {\n next.stepIndex = expected + 1;\n }\n\n if (next.stepIndex >= steps.length) {\n satisfied = true;\n next.stepIndex = 0;\n next.startedAt = null;\n }\n } else if (expected !== 0 && matchesStep(0)) {\n // Out-of-order event that *is* step 0 — restart the sequence.\n next.startedAt = nowT;\n next.stepIndex = 1;\n if (steps.length === 1) {\n satisfied = true;\n next.stepIndex = 0;\n next.startedAt = null;\n }\n }\n }\n\n if (satisfied) next.satisfiedCount += 1;\n return { record: next, satisfied };\n}\n","//\n// triggerEngine.ts\n//\n// The evaluator. For each incoming event it advances every active survey's\n// trigger state and, when a trigger's full condition is satisfied, walks the\n// eligibility order from API-CONTRACT §Eligibility:\n//\n// 1. window (startsAt/endsAt) 2. trigger condition (advanced here)\n// 3. frequency (warmupCount + fireEvery)\n// 4. audience (audienceMatch ⊆ user properties)\n// 5. sampling (deterministic, sticky) 6. per-user cap (maxPerUserDays)\n//\n// Eligible surveys are scheduled after `delaySeconds`; the cap is re-checked at\n// fire time and `lastShownAt` recorded before presenting. Port of iOS\n// `TriggerEngine` (JS is single-threaded, so the serial queue is unnecessary).\n//\n\nimport { advance } from \"./triggerSequencer\";\nimport { inSample, audienceMatches, eventMatchesStep } from \"./sampling\";\nimport { newTriggerRecord, endUserIdOf } from \"./types\";\nimport type { TriggerStateStore } from \"./persistence\";\nimport type { Identity, Survey, Trigger, UserTriggerState } from \"./types\";\n\n/** Why the engine did or didn't schedule a survey for an event. Reported to the\n * live debugger for test devices (see `debug.ts`); `eligible` means scheduled. */\nexport type DecisionReason =\n | \"platform\"\n | \"property_mismatch\"\n | \"sequence_in_progress\"\n | \"not_started\"\n | \"ended\"\n | \"frequency\"\n | \"audience\"\n | \"sampled_out\"\n | \"cap\"\n | \"eligible\"\n | \"shown\"\n | \"another_survey_showing\";\n\nexport interface Decision {\n surveyId: string;\n triggerId: string | null;\n reason: DecisionReason;\n /** For `eligible`: seconds until the survey shows. */\n delaySeconds?: number;\n}\n\nexport interface TriggerEngineOptions {\n store: TriggerStateStore;\n surveysProvider: () => Survey[];\n identityProvider: () => Identity;\n onPresent: (survey: Survey, trigger: Trigger, identity: Identity) => void;\n /** This SDK's platform (e.g. \"ios\"). Surveys with a non-empty `platforms` list\n * that excludes this value are skipped for auto-presentation. */\n platform: string;\n /** Injectable clock in **seconds** (tests). Defaults to `Date.now()/1000`. */\n now?: () => number;\n /** Called with each decision about a survey whose trigger names the event.\n * Used by the live debugger; never affects what the engine does. */\n onDecision?: (decision: Decision) => void;\n}\n\nexport class TriggerEngine {\n private readonly store: TriggerStateStore;\n private readonly surveysProvider: () => Survey[];\n private readonly identityProvider: () => Identity;\n private readonly onPresent: (survey: Survey, trigger: Trigger, identity: Identity) => void;\n private readonly platform: string;\n private readonly now: () => number;\n private readonly onDecision: (decision: Decision) => void;\n private readonly timers = new Set<ReturnType<typeof setTimeout>>();\n\n constructor(opts: TriggerEngineOptions) {\n this.store = opts.store;\n this.surveysProvider = opts.surveysProvider;\n this.identityProvider = opts.identityProvider;\n this.onPresent = opts.onPresent;\n this.platform = opts.platform;\n this.now = opts.now ?? (() => Date.now() / 1000);\n this.onDecision = opts.onDecision ?? (() => {});\n }\n\n /** Feed an event into the engine. `eventT` (unix seconds) is when it happened,\n * for a replayed server event; it drives sequence progress and\n * `sequenceWindowSeconds`. The survey window, caps and delay always use now. */\n process(name: string, properties: Record<string, unknown> = {}, eventT?: number): void {\n const identity = this.identityProvider();\n const endUserId = endUserIdOf(identity);\n const state = this.store.load(endUserId);\n const nowT = this.now();\n const atT = eventT ?? nowT;\n\n for (const survey of this.surveysProvider()) {\n const triggers = survey.triggers;\n if (!triggers || triggers.length === 0) continue;\n // Only surveys whose trigger names this event are reported to the debugger;\n // the rest have nothing to say about it.\n const names = (t: Trigger) => t.steps.some((st) => st.event === name);\n // Platform targeting: skip when the list is non-empty and excludes us.\n if (survey.platforms && survey.platforms.length > 0 && !survey.platforms.includes(this.platform)) {\n const t = triggers.find(names);\n if (t) this.onDecision({ surveyId: survey.id, triggerId: t.id, reason: \"platform\" });\n continue;\n }\n\n for (const trigger of triggers) {\n const satisfied = this.advanceTrigger(trigger, state, name, properties, atT);\n const skip = (reason: DecisionReason) => this.onDecision({ surveyId: survey.id, triggerId: trigger.id, reason });\n if (!satisfied) {\n if (names(trigger)) {\n // The event matched a step but the trigger isn't complete (a sequence), or it\n // had the right name with the wrong properties.\n const matchedStep = trigger.steps.some((st) => eventMatchesStep(name, properties, st));\n skip(matchedStep ? \"sequence_in_progress\" : \"property_mismatch\");\n }\n continue;\n }\n\n const occurrence = state.triggers[trigger.id]?.satisfiedCount ?? 0;\n\n // (1) window\n const window = this.windowState(survey, nowT);\n if (window !== \"open\") {\n skip(window);\n continue;\n }\n // (3) frequency\n if (!passesFrequency(trigger, occurrence)) {\n skip(\"frequency\");\n continue;\n }\n // (4) audience\n if (survey.audienceMatch && !audienceMatches(survey.audienceMatch, identity.userProperties)) {\n skip(\"audience\");\n continue;\n }\n // (5) sampling (sticky)\n if (!this.passesSampling(survey, endUserId, state)) {\n skip(\"sampled_out\");\n continue;\n }\n // (6) cap\n if (!passesCap(survey, state, nowT)) {\n skip(\"cap\");\n continue;\n }\n\n this.onDecision({\n surveyId: survey.id,\n triggerId: trigger.id,\n reason: \"eligible\",\n delaySeconds: Math.max(0, trigger.delaySeconds),\n });\n this.scheduleShow(survey, trigger, identity);\n }\n }\n\n this.store.save(endUserId, state);\n }\n\n /** Cancels any pending scheduled presentations. */\n stop(): void {\n for (const t of this.timers) clearTimeout(t);\n this.timers.clear();\n }\n\n // ── Trigger advancement ────────────────────────────────────────────────────\n\n private advanceTrigger(\n trigger: Trigger,\n state: UserTriggerState,\n eventName: string,\n properties: Record<string, unknown>,\n nowT: number,\n ): boolean {\n const record = state.triggers[trigger.id] ?? newTriggerRecord();\n const { record: updated, satisfied } = advance(trigger, record, eventName, properties, nowT);\n state.triggers[trigger.id] = updated;\n return satisfied;\n }\n\n // ── Eligibility checks ─────────────────────────────────────────────────────\n\n private windowState(survey: Survey, nowT: number): \"open\" | \"not_started\" | \"ended\" {\n if (survey.startsAt) {\n const start = Date.parse(survey.startsAt);\n if (!Number.isNaN(start) && nowT < start / 1000) return \"not_started\";\n }\n if (survey.endsAt) {\n const end = Date.parse(survey.endsAt);\n if (!Number.isNaN(end) && nowT > end / 1000) return \"ended\";\n }\n return \"open\";\n }\n\n private passesSampling(survey: Survey, endUserId: string, state: UserTriggerState): boolean {\n const existing = state.surveys[survey.id]?.sampleDecision;\n if (existing !== undefined && existing !== null) return existing;\n const decision = inSample(endUserId, survey.id, survey.samplePercent ?? 100);\n const record = state.surveys[survey.id] ?? {};\n record.sampleDecision = decision;\n state.surveys[survey.id] = record;\n return decision;\n }\n\n // ── Scheduling ─────────────────────────────────────────────────────────────\n\n private scheduleShow(survey: Survey, trigger: Trigger, identity: Identity): void {\n const delayMs = Math.max(0, trigger.delaySeconds) * 1000;\n const timer = setTimeout(() => {\n this.timers.delete(timer);\n const endUserId = endUserIdOf(identity);\n const state = this.store.load(endUserId);\n const nowT = this.now();\n\n // Re-check the cap at fire time (another survey may have shown during the delay).\n if (!passesCap(survey, state, nowT)) {\n this.onDecision({ surveyId: survey.id, triggerId: trigger.id, reason: \"cap\" });\n return;\n }\n\n // Record the show now so the cap holds even before the impression round-trips.\n const record = state.surveys[survey.id] ?? {};\n record.lastShownAt = nowT;\n state.surveys[survey.id] = record;\n this.store.save(endUserId, state);\n\n this.onPresent(survey, trigger, identity);\n }, delayMs);\n this.timers.add(timer);\n }\n}\n\n/** `occurrence` is 1-based. Ignore the first `warmupCount`, then fire on every\n * `fireEvery`-th satisfied occurrence thereafter. */\nexport function passesFrequency(trigger: Trigger, occurrence: number): boolean {\n const fireEvery = Math.max(1, trigger.fireEvery);\n const effective = occurrence - trigger.warmupCount;\n return effective >= 1 && effective % fireEvery === 0;\n}\n\nfunction passesCap(survey: Survey, state: UserTriggerState, nowT: number): boolean {\n const days = survey.maxPerUserDays ?? 0;\n const lastShown = state.surveys[survey.id]?.lastShownAt;\n if (days <= 0 || lastShown === undefined || lastShown === null) return true;\n const elapsed = nowT - lastShown;\n return elapsed >= days * 86_400;\n}\n","//\n// eventCounter.ts\n//\n// Counts tracked events between uploads so the dashboard can show which events\n// the app actually sends, how often, and from which platform (\"event signals\").\n// Only sent when the project turns event signals on (config `eventSignals`).\n//\n// What leaves the device: each event name, how many times it fired since the\n// last upload, when it was first and last seen in that window, and up to\n// MAX_KEYS property *names*. Never property values, never a user id.\n//\n\n/** Distinct event names held per upload window; names past this are dropped\n * until the next upload, so a buggy loop of unique names can't grow memory. */\nexport const MAX_NAMES = 200;\n/** Property names kept per event. */\nexport const MAX_KEYS = 20;\nconst MAX_NAME_LENGTH = 200;\nconst MAX_KEY_LENGTH = 100;\n\nexport interface EventCount {\n name: string;\n count: number;\n firstSeenAt: string;\n lastSeenAt: string;\n propertyKeys: string[];\n}\n\ninterface Entry {\n count: number;\n first: number;\n last: number;\n keys: Set<string>;\n}\n\nexport class EventCounter {\n private entries = new Map<string, Entry>();\n\n get size(): number {\n return this.entries.size;\n }\n\n record(name: string, properties: Record<string, unknown> = {}, now: number = Date.now()): void {\n if (!name || name.length > MAX_NAME_LENGTH) return;\n let e = this.entries.get(name);\n if (!e) {\n if (this.entries.size >= MAX_NAMES) return;\n e = { count: 0, first: now, last: now, keys: new Set() };\n this.entries.set(name, e);\n }\n e.count += 1;\n e.last = Math.max(e.last, now);\n for (const key of Object.keys(properties)) {\n if (e.keys.size >= MAX_KEYS) break;\n if (key && key.length <= MAX_KEY_LENGTH) e.keys.add(key);\n }\n }\n\n /** Everything counted since the last drain, and a fresh window. */\n drain(): EventCount[] {\n const out = [...this.entries].map(([name, e]) => ({\n name,\n count: e.count,\n firstSeenAt: new Date(e.first).toISOString(),\n lastSeenAt: new Date(e.last).toISOString(),\n propertyKeys: [...e.keys],\n }));\n this.entries = new Map();\n return out;\n }\n}\n","//\n// debug.ts\n//\n// The live debugger: on a test device chosen in the dashboard, the SDK sends\n// each tracked event and what the engine decided for every survey whose trigger\n// names it, so a developer can see why a survey did or didn't show.\n//\n// The dashboard never sends test user ids to apps. Config carries `debugUsers`,\n// a list of hashes of \"debug:<projectId>:<userId>\"; the SDK hashes its current\n// user the same way and only reports when it finds a match. Same FNV-1a as\n// sampling, so every SDK computes the same value.\n//\n\nimport { fnv1a32 } from \"./sampling\";\nimport type { Decision } from \"./triggerEngine\";\n\n/** The hash the dashboard puts in config `debugUsers` for one test user. */\nexport function debugKey(projectId: string, endUserId: string): string {\n return fnv1a32(`debug:${projectId}:${endUserId}`).toString(16).padStart(8, \"0\");\n}\n\nexport interface DebugEntry {\n at: string;\n /** The tracked event, or null for a decision made later (shown, capped at fire time). */\n event: string | null;\n properties: Record<string, unknown>;\n decisions: Decision[];\n}\n\nconst MAX_PROPS = 30;\nconst MAX_STRING = 200;\n\n/** A small, JSON-safe copy of an event's properties for display. Test devices\n * only; nested values are summarised rather than sent whole. */\nexport function debugProperties(properties: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(properties).slice(0, MAX_PROPS)) {\n if (typeof v === \"string\") out[k] = v.length > MAX_STRING ? `${v.slice(0, MAX_STRING)}…` : v;\n else if (typeof v === \"number\" || typeof v === \"boolean\" || v === null) out[k] = v;\n else if (Array.isArray(v)) out[k] = `[${v.length} items]`;\n else if (typeof v === \"object\") out[k] = \"{…}\";\n }\n return out;\n}\n","// The published package version. The release workflow writes the real number\n// here before it builds and publishes; \"0.0.0\" means a local build.\nexport const SDK_VERSION = \"0.1.7\";\n","//\n// client.ts\n//\n// `MicroSurveysClient` — the public facade, mirroring iOS `MicroSurveysSDK`. It\n// owns the config cache, identity store, trigger-state store, API client, and\n// trigger engine, and turns engine \"present\" signals into a single active\n// survey at a time (the provider's overlay renders it). No UI here; storage and\n// the foreground signal are passed in by `MicroSurveys`.\n//\n\nimport { ApiClient, PENDING_PAGE_SIZE } from \"./apiClient\";\nimport type { ImpressionInput } from \"./apiClient\";\nimport { uuid } from \"./storage\";\nimport type { PendingEvent } from \"./apiClient\";\nimport { ConfigStore, TriggerStateStore } from \"./persistence\";\nimport { IdentityStore } from \"./identity\";\nimport type { AnalyticsIdentity } from \"./identity\";\nimport type { KeyValueStorage } from \"./storage\";\nimport { TriggerEngine } from \"./triggerEngine\";\nimport { EventCounter, MAX_NAMES } from \"./eventCounter\";\nimport { debugKey, debugProperties } from \"./debug\";\nimport type { Decision } from \"./triggerEngine\";\nimport { SDK_VERSION } from \"./version\";\nimport { endUserIdOf } from \"./types\";\nimport type { DeviceContext, Identity, ProjectTheme, Survey, SurveyResult, Trigger } from \"./types\";\n\n/** Default API base. Override via `apiBaseURL` for self-hosted deployments. */\nconst DEFAULT_BASE_URL = \"https://console.microsurveys.ai\";\n/** How long a cached config is treated as fresh for foreground refresh. */\nconst DEFAULT_CONFIG_TTL_MS = 30 * 60 * 1000;\n/** How often counted events are uploaded while event signals are on. */\nconst EVENT_COUNTS_INTERVAL_MS = 60 * 1000;\n/** Server events mailbox (API-CONTRACT §6). Follow-up checks after each start or\n * foreground: Amplitude streams within about 60 s, so these catch an event that\n * happened just before the app opened. */\nconst PENDING_FOLLOW_UPS_MS = [30 * 1000, 90 * 1000];\n/** Regular check while the app stays in the foreground. */\nconst PENDING_INTERVAL_MS = 5 * 60 * 1000;\n/** Faster check while a sequence waits on a server event as its next step. */\nconst PENDING_WAITING_INTERVAL_MS = 60 * 1000;\n/** Stop the faster check this long after the waiting sequence started. */\nconst PENDING_WAITING_MAX_SECONDS = 3 * 60 * 60;\n\nexport interface CreateClientOptions {\n apiKey: string;\n /** Override for self-hosted deployments. Defaults to https://console.microsurveys.ai. */\n apiBaseURL?: string;\n /** Foreground-refresh freshness window in ms. Defaults to 30 min. */\n configTTLms?: number;\n /** Auto-refresh config on tab foreground (visibilitychange). Default true. */\n refreshOnForeground?: boolean;\n /** This device's platform for survey targeting (\"ios\" | \"android\"). */\n platform: string;\n /** The OS version, sent with responses. */\n osVersion?: string;\n /** The host app's version, sent with responses so results can be compared\n * across releases. */\n appVersion?: string;\n /** Where config, identity, trigger state and the outbox persist. Must already\n * hold its data when the client is created. */\n storage: KeyValueStorage;\n /** Subscribes to \"app came to the foreground\"; returns an unsubscribe. */\n subscribeForeground: (onForeground: () => void) => () => void;\n /** Subscribes to \"app went to the background\"; returns an unsubscribe. Used\n * to upload event counts before the app may be suspended, and to stop the\n * server events mailbox timers. */\n subscribeBackground?: (onBackground: () => void) => () => void;\n}\n\n/** A survey the host should present. Call `shown` once it is on screen (this\n * sends the impression), then `close` once when the UI goes away (completed,\n * partial, or dismissed). Both are safe to call more than once. */\nexport interface ActiveSurvey {\n survey: Survey;\n /** The trigger that fired; null for an inline survey. */\n trigger: Trigger | null;\n /** The survey is on screen: queues its impression (`dismissed: false`). */\n shown(): void;\n /** The survey went away. A dismissal re-sends the impression with\n * `dismissed: true`; answers are sent as a response. Without a result (the\n * survey never got to show), nothing more is sent. If `shown` was never\n * called, the impression is sent now, with the final `dismissed`. */\n close(result?: SurveyResult | null): void;\n}\n\ntype PresentListener = (active: ActiveSurvey) => void;\ntype ConfigListener = () => void;\n\ninterface Presentation {\n survey: Survey;\n trigger: Trigger | null;\n identity: Identity;\n /** The impression's clientId, made when the survey is handed to the host. */\n impressionId: string;\n /** When the survey was handed to the host; the impression's time if the host\n * never reports it shown. */\n presentedAt: Date;\n /** The impression as queued when the survey appeared; re-sent on dismissal. */\n impression: ImpressionInput | null;\n closed: boolean;\n}\n\nexport class MicroSurveysClient {\n private readonly api: ApiClient;\n private readonly configStore: ConfigStore;\n private readonly identityStore: IdentityStore;\n private readonly triggerStateStore: TriggerStateStore;\n private readonly engine: TriggerEngine;\n private readonly configTTLms: number;\n private readonly refreshOnForeground: boolean;\n private readonly platform: string;\n private readonly osVersion: string | undefined;\n private readonly appVersion: string | undefined;\n private readonly subscribeForeground: (onForeground: () => void) => () => void;\n private readonly subscribeBackground: ((onBackground: () => void) => () => void) | undefined;\n private readonly eventCounter = new EventCounter();\n private eventCountsTimer: ReturnType<typeof setInterval> | null = null;\n /** Decisions collected while one event is processed, for the live debugger. */\n private collecting: Decision[] | null = null;\n private unsubscribeBackground: (() => void) | null = null;\n /** Mailbox timers, cleared on background and stop. */\n private pendingTimers: ReturnType<typeof setTimeout>[] = [];\n private pendingIntervals: ReturnType<typeof setInterval>[] = [];\n private pendingInFlight = false;\n\n private readonly presentListeners = new Set<PresentListener>();\n private readonly configListeners = new Set<ConfigListener>();\n private active: Presentation | null = null;\n private started = false;\n private unsubscribeForeground: (() => void) | null = null;\n\n constructor(opts: CreateClientOptions) {\n const kv = opts.storage;\n this.configStore = new ConfigStore(kv);\n this.identityStore = new IdentityStore(kv);\n this.triggerStateStore = new TriggerStateStore(kv);\n this.api = new ApiClient(opts.apiKey, opts.apiBaseURL ?? DEFAULT_BASE_URL, kv);\n this.configTTLms = opts.configTTLms ?? DEFAULT_CONFIG_TTL_MS;\n this.refreshOnForeground = opts.refreshOnForeground ?? true;\n this.platform = opts.platform;\n this.osVersion = opts.osVersion;\n this.appVersion = opts.appVersion;\n this.subscribeForeground = opts.subscribeForeground;\n this.subscribeBackground = opts.subscribeBackground;\n this.engine = new TriggerEngine({\n store: this.triggerStateStore,\n surveysProvider: () => this.configStore.surveys,\n identityProvider: () => this.identityStore.snapshot(),\n onPresent: (survey, trigger, identity) => this.handlePresent(survey, trigger, identity),\n platform: opts.platform,\n onDecision: (d) => this.handleDecision(d),\n });\n }\n\n // ── Lifecycle ────────────────────────────────────────────────────────────────\n\n /** Flush any queued ingest, refresh config, wire the foreground refresh\n * (optional) and the server events mailbox checks. Safe to call once early. */\n start(): void {\n if (this.started) return;\n this.started = true;\n this.api.resumeRetry();\n void this.api.flush();\n // Check the server events mailbox once the config says whether there is one.\n void this.refreshConfig().then(() => {\n if (this.started) this.startPendingChecks();\n });\n // Always subscribed: the mailbox is checked on every foreground, whatever the\n // config TTL, and even when `refreshOnForeground` is off.\n this.unsubscribeForeground = this.subscribeForeground(() => {\n // Send ingest queued while offline or in the background.\n void this.api.flush();\n if (this.refreshOnForeground) this.refreshConfigIfStale();\n this.startPendingChecks();\n });\n // The app may be suspended or killed in the background: send what was counted first.\n this.unsubscribeBackground =\n this.subscribeBackground?.(() => {\n this.flushEventCounts();\n this.stopPendingChecks();\n }) ?? null;\n this.eventCountsTimer = setInterval(() => this.flushEventCounts(), EVENT_COUNTS_INTERVAL_MS);\n }\n\n /** Tear down listeners + pending timers. */\n stop(): void {\n this.engine.stop();\n this.flushEventCounts();\n if (this.eventCountsTimer) clearInterval(this.eventCountsTimer);\n this.eventCountsTimer = null;\n this.stopPendingChecks();\n this.unsubscribeBackground?.();\n this.unsubscribeBackground = null;\n this.unsubscribeForeground?.();\n this.unsubscribeForeground = null;\n // Queued entries stay in the outbox for the next start.\n this.api.cancelRetry();\n this.started = false;\n }\n\n /** Force an ETag-aware config refresh; keeps the cache on failure. */\n async refreshConfig(): Promise<void> {\n try {\n const result = await this.api.fetchConfig(this.configStore.etag);\n if (result.kind === \"config\") {\n this.configStore.save(result.rawText, result.etag);\n this.configListeners.forEach((l) => l());\n }\n } catch {\n // Keep the cached config; the SDK still works offline.\n }\n }\n\n /** Refresh only when the cache is missing or older than the TTL. */\n refreshConfigIfStale(): void {\n const storedAt = this.configStore.storedAt;\n if (storedAt !== null && Date.now() - storedAt < this.configTTLms) return;\n void this.refreshConfig();\n }\n\n // ── Identity + events ────────────────────────────────────────────────────────\n\n identify(userId: string | null | undefined, properties?: Record<string, unknown>): void {\n this.identityStore.setUser(userId, properties);\n }\n\n track(name: string, properties: Record<string, unknown> = {}): void {\n if (this.configStore.eventSignals) {\n this.eventCounter.record(name, properties);\n if (this.eventCounter.size >= MAX_NAMES) this.flushEventCounts();\n }\n this.processEvent(name, properties);\n }\n\n /** Runs one event through the engine, reporting to the live debugger on test\n * devices. `occurredAt` (ms epoch) is set for a replayed server event. */\n private processEvent(name: string, properties: Record<string, unknown>, occurredAt?: number): void {\n const eventT = occurredAt === undefined ? undefined : occurredAt / 1000;\n if (!this.isDebugDevice()) {\n this.engine.process(name, properties, eventT);\n return;\n }\n this.collecting = [];\n try {\n this.engine.process(name, properties, eventT);\n } finally {\n const decisions = this.collecting;\n this.collecting = null;\n this.sendDebug(name, debugProperties(properties), decisions, occurredAt);\n }\n }\n\n // ── Server events mailbox ────────────────────────────────────────────────────\n\n /** Checks now, then 30 s and 90 s later, every 5 minutes, and every 60 s while\n * a sequence waits on a server event. Restarts the schedule; no-op unless the\n * config has `pendingEvents`. */\n private startPendingChecks(): void {\n this.stopPendingChecks();\n if (!this.configStore.pendingEvents) return;\n void this.checkPending();\n for (const ms of PENDING_FOLLOW_UPS_MS) {\n this.pendingTimers.push(setTimeout(() => void this.checkPending(), ms));\n }\n this.pendingIntervals.push(\n setInterval(() => void this.checkPending(), PENDING_INTERVAL_MS),\n setInterval(() => {\n if (this.isWaitingOnServerEvent()) void this.checkPending();\n }, PENDING_WAITING_INTERVAL_MS),\n );\n }\n\n private stopPendingChecks(): void {\n for (const t of this.pendingTimers) clearTimeout(t);\n for (const t of this.pendingIntervals) clearInterval(t);\n this.pendingTimers = [];\n this.pendingIntervals = [];\n }\n\n /** Fetches and replays this user's waiting server events. One request at a\n * time; a full page is followed by one more call. Failures are silent: the\n * next scheduled check retries. */\n private async checkPending(): Promise<void> {\n if (this.pendingInFlight || !this.configStore.pendingEvents) return;\n const identity = this.identityStore.snapshot();\n const userId = identity.amplitudeUserId ?? identity.hostUserId ?? null;\n const deviceId = identity.amplitudeDeviceId ?? null;\n if (!userId && !deviceId) return;\n this.pendingInFlight = true;\n try {\n for (let call = 0; call < 2; call++) {\n const events = await this.api.fetchPending({ userId, deviceId });\n this.replayPending(events);\n if (events.length < PENDING_PAGE_SIZE) break;\n }\n } catch {\n // Offline or server trouble: the next scheduled check retries.\n } finally {\n this.pendingInFlight = false;\n }\n }\n\n /** Replays server events like `track`, oldest first, at the time each one\n * happened. Not counted in event signals: the app didn't send them. */\n private replayPending(events: PendingEvent[]): void {\n const timed = events.map((e) => ({ e, at: Date.parse(e.occurredAt) }));\n timed.sort((a, b) => a.at - b.at);\n for (const { e, at } of timed) this.processEvent(e.name, e.properties, at);\n }\n\n /** True while a SEQUENCE trigger for the current user has started and its next\n * step's event arrives by server stream, up to 3 hours after it started. */\n private isWaitingOnServerEvent(): boolean {\n const serverEvents = this.configStore.serverEvents;\n if (serverEvents.length === 0) return false;\n const state = this.triggerStateStore.load(endUserIdOf(this.identityStore.snapshot()));\n const nowT = Date.now() / 1000;\n for (const survey of this.configStore.surveys) {\n for (const trigger of survey.triggers ?? []) {\n if (trigger.type !== \"SEQUENCE\") continue;\n const record = state.triggers[trigger.id];\n if (!record || record.stepIndex <= 0 || record.startedAt === null) continue;\n if (nowT - record.startedAt > PENDING_WAITING_MAX_SECONDS) continue;\n const steps = [...trigger.steps].sort((a, b) => a.order - b.order);\n const next = steps[Math.min(record.stepIndex, steps.length - 1)];\n if (next && serverEvents.includes(next.event)) return true;\n }\n }\n return false;\n }\n\n // ── Live debugger ────────────────────────────────────────────────────────────\n\n /** True when the dashboard picked the current user as a test device. */\n private isDebugDevice(): boolean {\n const users = this.configStore.debugUsers;\n const projectId = this.configStore.projectId;\n if (users.length === 0 || !projectId) return false;\n return users.includes(debugKey(projectId, endUserIdOf(this.identityStore.snapshot())));\n }\n\n private handleDecision(d: Decision): void {\n if (this.collecting) this.collecting.push(d);\n // Made outside an event (a delayed survey's cap check at fire time): report on its own.\n else if (this.isDebugDevice()) this.sendDebug(null, {}, [d]);\n }\n\n /** `at` (ms epoch) defaults to now; a replayed server event passes its `occurredAt`. */\n private sendDebug(event: string | null, properties: Record<string, unknown>, decisions: Decision[], at?: number): void {\n const endUserId = endUserIdOf(this.identityStore.snapshot());\n this.api.recordDebug(\n { at: new Date(at ?? Date.now()).toISOString(), event, properties, decisions },\n endUserId,\n { ...this.deviceContext(), sdkVersion: SDK_VERSION },\n );\n }\n\n /** Uploads the events counted since the last upload (no-op when there are none). */\n flushEventCounts(): void {\n if (this.eventCounter.size === 0) return;\n this.api.recordEventCounts(this.eventCounter.drain(), { ...this.deviceContext(), sdkVersion: SDK_VERSION });\n }\n\n /** Merge identity forwarded by an analytics SDK (e.g. the Amplitude plugin).\n * Its user/device id take precedence over `identify()` for `endUserId`. */\n updateAnalyticsIdentity(update: AnalyticsIdentity): void {\n this.identityStore.updateFromAnalytics(update);\n }\n\n // ── Config accessors (for inline rendering) ──────────────────────────────────\n\n getTheme(): ProjectTheme | null {\n return this.configStore.theme;\n }\n\n getSurvey(surveyId: string): Survey | undefined {\n return this.configStore.surveys.find((s) => s.id === surveyId);\n }\n\n /** Subscribe to config refreshes (e.g. to render an inline survey that wasn't\n * cached yet). Returns an unsubscribe function. */\n onConfigChange(cb: ConfigListener): () => void {\n this.configListeners.add(cb);\n return () => this.configListeners.delete(cb);\n }\n\n // ── Presentation ─────────────────────────────────────────────────────────────\n\n /** Subscribe to auto-triggered surveys. Returns an unsubscribe function. If a\n * survey is already active, the new subscriber is notified immediately. */\n onPresent(cb: PresentListener): () => void {\n this.presentListeners.add(cb);\n if (this.active && !this.active.closed) cb(this.toActiveSurvey(this.active));\n return () => this.presentListeners.delete(cb);\n }\n\n private handlePresent(survey: Survey, trigger: Trigger, identity: Identity): void {\n // One survey on screen at a time — drop while one is active.\n if (this.active && !this.active.closed) {\n this.handleDecision({ surveyId: survey.id, triggerId: trigger.id, reason: \"another_survey_showing\" });\n return;\n }\n this.handleDecision({ surveyId: survey.id, triggerId: trigger.id, reason: \"shown\" });\n const p = this.newPresentation(survey, trigger, identity);\n this.active = p;\n const active = this.toActiveSurvey(p);\n this.presentListeners.forEach((l) => l(active));\n }\n\n private newPresentation(survey: Survey, trigger: Trigger | null, identity: Identity): Presentation {\n return { survey, trigger, identity, impressionId: uuid(), presentedAt: new Date(), impression: null, closed: false };\n }\n\n private toActiveSurvey(p: Presentation): ActiveSurvey {\n return {\n survey: p.survey,\n trigger: p.trigger,\n shown: () => this.markShown(p),\n close: (result?: SurveyResult | null) => {\n if (p.closed) return;\n p.closed = true;\n if (this.active === p) this.active = null;\n if (result) this.recordOutcome(p, result);\n },\n };\n }\n\n /** Queues the impression the moment the survey is on screen, so it counts even\n * if the app is killed before the survey closes. */\n private markShown(p: Presentation): void {\n if (p.impression || p.closed) return;\n p.impression = {\n clientId: p.impressionId,\n surveyId: p.survey.id,\n triggerId: p.trigger?.id ?? null,\n endUserId: endUserIdOf(p.identity),\n shownAt: new Date(),\n dismissed: false,\n context: this.deviceContext(),\n };\n this.api.recordImpression(p.impression);\n }\n\n /** An **inline** `<MicroSurvey>` (no trigger, no gate, not \"the\" active survey).\n * Call `shown` when it renders and `close` with its outcome. */\n presentInline(survey: Survey): ActiveSurvey {\n return this.toActiveSurvey(this.newPresentation(survey, null, this.identityStore.snapshot()));\n }\n\n /** Records the outcome of an inline survey in one go, at close. Prefer\n * `presentInline`, which sends the impression when the survey appears. */\n recordInline(survey: Survey, result: SurveyResult, shownAt: Date): void {\n const p = this.newPresentation(survey, null, this.identityStore.snapshot());\n p.presentedAt = shownAt;\n p.closed = true;\n this.recordOutcome(p, result);\n }\n\n private recordOutcome(p: Presentation, result: SurveyResult): void {\n let impression = p.impression;\n if (!impression) {\n // Never reported shown: send the impression now, with the final `dismissed`.\n impression = {\n clientId: p.impressionId,\n surveyId: p.survey.id,\n triggerId: p.trigger?.id ?? null,\n endUserId: endUserIdOf(p.identity),\n shownAt: p.presentedAt,\n dismissed: result.dismissed,\n context: this.deviceContext(),\n };\n this.api.recordImpression(impression);\n } else if (result.dismissed) {\n // Already sent as shown: the same impression again, now dismissed. The\n // server updates the one it has (same clientId).\n this.api.recordImpression({ ...impression, dismissed: true });\n }\n // A pure dismissal (no answers) is an impression, NOT a response — don't\n // inflate the response count. Partial multi-step answers still count.\n if (result.completed || result.answers.length > 0) {\n this.api.recordResponse({\n surveyId: p.survey.id,\n endUserId: impression.endUserId,\n completed: result.completed,\n submittedAt: new Date(),\n userProps: p.identity.userProperties,\n impressionId: p.impressionId,\n triggerId: p.trigger?.id ?? null,\n context: impression.context,\n answers: result.answers,\n });\n }\n }\n\n /** Where this showing happened. The language is read at record time: the user\n * can change it while the app runs. */\n private deviceContext(): DeviceContext {\n let locale: string | undefined;\n try {\n locale = Intl.DateTimeFormat().resolvedOptions().locale || undefined;\n } catch {\n // Runtimes built without Intl: leave the language out.\n }\n return { platform: this.platform, appVersion: this.appVersion, osVersion: this.osVersion, locale };\n }\n}\n\n/** Creates and returns a `MicroSurveysClient`. Call `start()` to begin. */\nexport function createClient(opts: CreateClientOptions): MicroSurveysClient {\n return new MicroSurveysClient(opts);\n}\n","//\n// amplitude.ts\n//\n// An Amplitude enrichment plugin for `@amplitude/analytics-react-native`: it\n// reads every tracked event (name + properties), keeps the identity fresh\n// (user id, device id, `$identify` user properties), and forwards both to the\n// SDK — then returns the event **unmodified** (pure pass-through, never drops or\n// rewrites events). Port of iOS `MicroSurveysAmplitudePlugin`.\n//\n// Typed structurally so this package doesn't depend on Amplitude.\n//\n\nimport type { AnalyticsIdentity } from \"./core\";\n\n/** The fields of an Amplitude event this plugin reads. */\nexport interface AmplitudeEvent {\n event_type: string;\n event_properties?: Record<string, unknown> | null;\n user_id?: string | null;\n device_id?: string | null;\n /** On `$identify` events: `{ $set, $setOnce, $unset, … }` operations. */\n user_properties?: Record<string, unknown> | null;\n}\n\n/** An Amplitude enrichment plugin (`amplitude.add(plugin)`). */\nexport interface MicroSurveysAmplitudePlugin {\n name: string;\n type: \"enrichment\";\n setup(config?: unknown, client?: unknown): Promise<void>;\n execute<E extends AmplitudeEvent>(event: E): Promise<E>;\n}\n\n/** What the plugin forwards into. Implemented by `MicroSurveys`. */\nexport interface AmplitudeForwarder {\n updateAnalyticsIdentity(update: AnalyticsIdentity): void;\n track(name: string, properties?: Record<string, unknown>): void;\n}\n\nexport function createAmplitudePlugin(forwarder: AmplitudeForwarder): MicroSurveysAmplitudePlugin {\n return {\n name: \"microsurveys\",\n type: \"enrichment\",\n async setup() {},\n async execute(event) {\n try {\n forwarder.updateAnalyticsIdentity(identityOf(event));\n // System events (`$identify`, `$groupidentify`, …) never match host\n // triggers; skip them rather than churn trigger state.\n if (!event.event_type.startsWith(\"$\")) {\n forwarder.track(event.event_type, event.event_properties ?? {});\n }\n } catch {\n // Never let survey logic break the host's analytics pipeline.\n }\n return event;\n },\n };\n}\n\n/** Maps an event's identity fields (and, for `$identify`, its property\n * operations) onto an identity update. */\nexport function identityOf(event: AmplitudeEvent): AnalyticsIdentity {\n const update: AnalyticsIdentity = { userId: event.user_id, deviceId: event.device_id };\n if (event.event_type !== \"$identify\" || !event.user_properties) return update;\n\n const ops = event.user_properties;\n const set = asRecord(ops.$set);\n const setOnce = asRecord(ops.$setOnce);\n if (set) update.userProperties = set;\n if (setOnce) update.setOnceProperties = setOnce;\n const unset = asRecord(ops.$unset);\n if (unset) update.unsetProperties = Object.keys(unset);\n return update;\n}\n\nfunction asRecord(v: unknown): Record<string, unknown> | null {\n return v && typeof v === \"object\" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;\n}\n","//\n// asyncStorage.ts\n//\n// The engine reads its stores synchronously (config cache, identity,\n// trigger state, outbox), but React Native's AsyncStorage is async. This adapter\n// preloads every MicroSurveys key into memory once, then serves reads from\n// memory and writes through to AsyncStorage in order. Writes are best-effort:\n// a failed write only loses persistence, never breaks the running SDK.\n//\n\nimport { STORAGE_KEY_PREFIX } from \"./core\";\nimport type { KeyValueStorage } from \"./core\";\n\n/** The subset of AsyncStorage this SDK needs. Matches\n * `@react-native-async-storage/async-storage` v1, v2 (`multiGet`) and v3\n * (`getMany`), or any store with the same shape. */\nexport interface AsyncKeyValueStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n getAllKeys(): Promise<readonly string[]>;\n /** v3 batch read. */\n getMany?(keys: string[]): Promise<Record<string, string | null>>;\n /** v1/v2 batch read. */\n multiGet?(keys: readonly string[]): Promise<readonly (readonly [string, string | null])[]>;\n}\n\n/** Loads every MicroSurveys key from `store` and returns a synchronous view of\n * it for the runtime. Never rejects: if the store can't be read, the SDK\n * starts with empty state. */\nexport async function hydrateAsyncStorage(store: AsyncKeyValueStorage): Promise<KeyValueStorage> {\n const cache = new Map<string, string>();\n try {\n const keys = (await store.getAllKeys()).filter((k) => k.startsWith(STORAGE_KEY_PREFIX));\n for (const [key, value] of await readMany(store, keys)) {\n if (value !== null) cache.set(key, value);\n }\n } catch {\n // Unreadable store: start empty rather than not at all.\n }\n\n // One write chain, so writes land in the order the runtime made them.\n let chain: Promise<void> = Promise.resolve();\n const enqueue = (write: () => Promise<void>) => {\n chain = chain.then(write).catch(() => {});\n };\n\n return {\n getItem: (key) => cache.get(key) ?? null,\n setItem(key, value) {\n cache.set(key, value);\n enqueue(() => store.setItem(key, value));\n },\n removeItem(key) {\n cache.delete(key);\n enqueue(() => store.removeItem(key));\n },\n };\n}\n\nasync function readMany(store: AsyncKeyValueStorage, keys: string[]): Promise<[string, string | null][]> {\n if (keys.length === 0) return [];\n if (store.getMany) return Object.entries(await store.getMany(keys));\n if (store.multiGet) return (await store.multiGet(keys)).map(([k, v]) => [k, v]);\n return Promise.all(keys.map(async (k): Promise<[string, string | null]> => [k, await store.getItem(k)]));\n}\n","//\n// provider.tsx\n//\n// `<MicroSurveysProvider>` exposes a `MicroSurveys` instance to the tree,\n// starts it, and mounts the overlay host that presents auto-triggered surveys\n// (port of iOS `Presenter`). Pass `apiKey` for the simple case, or `instance`\n// to share one created at module scope (e.g. for the Amplitude plugin).\n//\n\nimport { createContext, useContext, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { ActiveSurvey } from \"./core\";\nimport { MicroSurveys } from \"./MicroSurveys\";\nimport { SurveyModal } from \"./ui/SurveyModal\";\n\ninterface ContextValue {\n instance: MicroSurveys | null;\n fontFamily?: string;\n}\n\nexport const MicroSurveysContext = createContext<ContextValue>({ instance: null });\n\nexport interface MicroSurveysProviderProps {\n /** Project API key (`ms_live_…` / `ms_test_…`). Ignored when `instance` is passed. */\n apiKey?: string;\n /** Override the API base for self-hosted deployments. Ignored when `instance` is passed. */\n apiBaseURL?: string;\n /** Your app's version (e.g. \"3.2.0\"), sent with responses. Ignored when `instance` is passed. */\n appVersion?: string;\n /** A `MicroSurveys` you created yourself, e.g. to register its Amplitude plugin. */\n instance?: MicroSurveys;\n /** Start automatically on mount (load config, flush queued ingest). Default true. */\n autoStart?: boolean;\n /** A font family your app registered (e.g. with expo-font) to render surveys in.\n * Defaults to the system font. */\n fontFamily?: string;\n children?: ReactNode;\n}\n\nexport function MicroSurveysProvider({ apiKey, apiBaseURL, appVersion, instance, autoStart = true, fontFamily, children }: MicroSurveysProviderProps) {\n // Created once; later prop changes are ignored (remount the provider to switch keys).\n const [owned] = useState<MicroSurveys | null>(() => (!instance && apiKey ? new MicroSurveys({ apiKey, apiBaseURL, appVersion }) : null));\n const ms = instance ?? owned;\n\n useEffect(() => {\n if (!ms || !autoStart) return;\n ms.start();\n // Only stop an instance this provider created; a shared one outlives it.\n return () => owned?.stop();\n }, [ms, owned, autoStart]);\n\n const value = useMemo(() => ({ instance: ms, fontFamily }), [ms, fontFamily]);\n return (\n <MicroSurveysContext.Provider value={value}>\n {children}\n {ms && <OverlayHost instance={ms} fontFamily={fontFamily} />}\n </MicroSurveysContext.Provider>\n );\n}\n\n/** Presents auto-triggered surveys one at a time. A survey triggered while\n * another is still on screen (e.g. during its \"Thanks\") waits its turn. */\nfunction OverlayHost({ instance, fontFamily }: { instance: MicroSurveys; fontFamily?: string }) {\n const [current, setCurrent] = useState<{ active: ActiveSurvey; id: number } | null>(null);\n const queue = useRef<ActiveSurvey[]>([]);\n const showing = useRef(false);\n const nextId = useRef(0);\n\n useEffect(\n () =>\n instance.onPresent((active) => {\n if (showing.current) {\n queue.current.push(active);\n return;\n }\n showing.current = true;\n setCurrent({ active, id: nextId.current++ });\n }),\n [instance],\n );\n\n // On screen: send the impression now rather than when the survey closes.\n useEffect(() => {\n current?.active.shown();\n }, [current]);\n\n function showNext() {\n // Normally closed already by onResult; this only frees the slot if not.\n current?.active.close();\n const next = queue.current.shift();\n if (next) {\n setCurrent({ active: next, id: nextId.current++ });\n } else {\n showing.current = false;\n setCurrent(null);\n }\n }\n\n return (\n <SurveyModal\n // A fresh modal per presentation, even when the same survey shows twice.\n key={current?.id ?? \"none\"}\n survey={current?.active.survey ?? null}\n theme={instance.getTheme()}\n fontFamily={fontFamily}\n onResult={(result) => current?.active.close(result)}\n onClose={showNext}\n />\n );\n}\n\n/** The `MicroSurveys` instance from the nearest provider (or null outside one). */\nexport function useMicroSurveysInstance(): MicroSurveys | null {\n return useContext(MicroSurveysContext).instance;\n}\n\n/** Event + identity helpers bound to the provider's instance. Safe no-ops\n * outside a provider. */\nexport function useMicroSurveys() {\n const instance = useMicroSurveysInstance();\n return useMemo(\n () => ({\n instance,\n track: (name: string, properties?: Record<string, unknown>) => instance?.track(name, properties),\n identify: (userId: string | null | undefined, properties?: Record<string, unknown>) => instance?.identify(userId, properties),\n refresh: () => instance?.refreshConfig(),\n }),\n [instance],\n );\n}\n","//\n// SurveyModal.tsx\n//\n// Presents one survey over the app as a bottom sheet (grabber, swipe down to\n// dismiss) or a centered dialog, per the survey's `presentation` or the project\n// theme's `position`. Port of iOS `SurveyViewController`'s presentation: dims\n// the app, avoids the keyboard, respects safe areas, and blocks every dismissal\n// path for `dismissible: false` surveys.\n//\n// Exported so hosts can preview a survey without a backend (as the demo app\n// does); auto-triggered surveys are presented by <MicroSurveysProvider>.\n//\n\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport type { RefObject } from \"react\";\nimport {\n Animated,\n Easing,\n Keyboard,\n KeyboardAvoidingView,\n Modal,\n PanResponder,\n Platform,\n Pressable,\n StyleSheet,\n View,\n useColorScheme,\n useWindowDimensions,\n} from \"react-native\";\nimport type { LayoutChangeEvent, PanResponderGestureState } from \"react-native\";\nimport { SafeAreaProvider, initialWindowMetrics, useSafeAreaInsets } from \"react-native-safe-area-context\";\nimport type { ProjectTheme, Survey, SurveyResult } from \"../core\";\nimport { SurveyCard } from \"./SurveyCard\";\nimport type { SurveyCardHandle } from \"./SurveyCard\";\nimport { FLOATING_SHEET_INSET, FLOATING_SHEET_RADIUS, usesGlassChrome } from \"./platform\";\nimport { resolveTheme } from \"./theme\";\nimport type { SurveyTheme } from \"./theme\";\n\nexport interface SurveyModalProps {\n /** The survey to show; the modal is visible while this is non-null. */\n survey: Survey | null;\n /** The dashboard theme (`/api/sdk/config` → `theme`). Defaults apply when absent. */\n theme?: ProjectTheme | null;\n /** A font family your app registered (e.g. with expo-font). Defaults to the system font. */\n fontFamily?: string;\n /** Called once with the outcome, as soon as it is known. */\n onResult?: (result: SurveyResult) => void;\n /** Called after the survey has animated away. Clear `survey` here. */\n onClose?: () => void;\n}\n\nexport function SurveyModal({ survey, theme: projectTheme, fontFamily, onResult, onClose }: SurveyModalProps) {\n const scheme = useColorScheme() === \"dark\" ? \"dark\" : \"light\";\n const theme = useMemo(\n () => resolveTheme(projectTheme, { scheme, presentation: survey?.presentation, fontFamily }),\n [projectTheme, scheme, survey?.presentation, fontFamily],\n );\n\n const card = useRef<SurveyCardHandle>(null);\n\n if (!survey) return null;\n return (\n <Modal\n visible\n transparent\n animationType=\"none\"\n statusBarTranslucent\n navigationBarTranslucent\n // Android back button.\n onRequestClose={() => {\n if (survey.dismissible !== false) card.current?.dismiss();\n }}\n >\n {/* The modal is its own native window; give it its own safe-area context. */}\n <SafeAreaProvider initialMetrics={initialWindowMetrics}>\n <Presentation key={survey.id} card={card} survey={survey} theme={theme} onResult={onResult} onClose={onClose} />\n </SafeAreaProvider>\n </Modal>\n );\n}\n\ninterface PresentationProps {\n card: RefObject<SurveyCardHandle | null>;\n survey: Survey;\n theme: SurveyTheme;\n onResult?: (result: SurveyResult) => void;\n onClose?: () => void;\n}\n\nfunction Presentation({ card, survey, theme, onResult, onClose }: PresentationProps) {\n const insets = useSafeAreaInsets();\n const window = useWindowDimensions();\n const isSheet = theme.position === \"bottom\";\n const dismissible = survey.dismissible !== false;\n // iOS 26+ sheets float inset from the edges on Face ID iPhones (home-button\n // devices have no bottom inset and keep an edge-to-edge sheet). UIKit doesn't\n // lay a floating sheet out narrower: it lays out the full-width sheet and\n // scales it down to fit the inset, so everything inside renders at ~96%.\n // Do the same so text wraps and controls size exactly like the native SDK.\n const floating = isSheet && usesGlassChrome && insets.bottom > 0;\n const floatScale = floating ? (window.width - 2 * FLOATING_SHEET_INSET) / window.width : 1;\n // Radii are drawn before the scale, so pre-divide to land on the native value.\n const sheetRadius = floating && theme.nativeSheetCorners ? FLOATING_SHEET_RADIUS / floatScale : theme.sheetCornerRadius;\n // Dim behind the survey: a system sheet dims 20% black on iOS (32% scrim on\n // Android, per Material); the dialog uses the configured background at 40%,\n // as the iOS SDK's custom card does.\n const scrim = isSheet ? (Platform.OS === \"ios\" ? \"rgba(0, 0, 0, 0.2)\" : \"rgba(0, 0, 0, 0.32)\") : theme.scrim;\n\n // 0 = hidden, 1 = shown. `drag` follows a swipe-down on the sheet.\n const progress = useRef(new Animated.Value(0)).current;\n const drag = useRef(new Animated.Value(0)).current;\n const [sheetHeight, setSheetHeight] = useState(window.height);\n const sheetTop = useRef(window.height);\n // Height of the on-screen keyboard (0 when hidden).\n const [keyboard, setKeyboard] = useState(0);\n const keyboardUp = keyboard > 0;\n // On iOS the sheet stays pinned to the bottom and extends behind the keyboard,\n // insetting its content instead of lifting as a whole (as the native SDK does\n // via additionalSafeAreaInsets). Dialogs and Android sheets just move up.\n const insetForKeyboard = isSheet && Platform.OS === \"ios\";\n // That inset is a spacer under the card, animated alongside the keyboard. It's\n // local on purpose: LayoutAnimation is app-wide, and replaying committed props\n // made native-driven views (the dialog mid fade-in) snap back to opacity 0.\n const keyboardSpacer = useRef(new Animated.Value(0)).current;\n const keyboardDuration = useRef(250);\n\n // These run on the JS driver on purpose. A native-driven value never reaches\n // React, so when the keyboard re-lays out the modal, React re-commits the\n // starting value (opacity 0, off-screen) and the survey vanishes on screen.\n useEffect(() => {\n Animated.timing(progress, {\n toValue: 1,\n duration: isSheet ? 320 : 280,\n easing: Easing.out(Easing.cubic),\n useNativeDriver: false,\n }).start();\n }, [progress, isSheet]);\n\n useEffect(() => {\n const update = (height: number, duration?: number) => {\n // iOS reports the keyboard's animation duration; match it.\n if (duration) keyboardDuration.current = duration;\n setKeyboard(height);\n };\n const show = Keyboard.addListener(Platform.OS === \"ios\" ? \"keyboardWillShow\" : \"keyboardDidShow\", (e) =>\n update(e.endCoordinates.height, e.duration),\n );\n const hide = Keyboard.addListener(Platform.OS === \"ios\" ? \"keyboardWillHide\" : \"keyboardDidHide\", (e) => update(0, e.duration));\n return () => {\n show.remove();\n hide.remove();\n };\n }, []);\n\n // The card keeps `pad` above the keyboard; the spacer covers the rest. The\n // floating sheet's bottom edge sits FLOATING_SHEET_INSET up and its content is scaled.\n const spacerTarget = insetForKeyboard && keyboard > 0 ? (keyboard - (floating ? FLOATING_SHEET_INSET : 0)) / floatScale : 0;\n useEffect(() => {\n Animated.timing(keyboardSpacer, {\n toValue: spacerTarget,\n duration: keyboardDuration.current,\n easing: Easing.bezier(0.17, 0.59, 0.4, 0.77), // close to the iOS keyboard curve\n useNativeDriver: false,\n }).start();\n }, [keyboardSpacer, spacerTarget]);\n\n function animateOut() {\n Keyboard.dismiss();\n Animated.timing(progress, { toValue: 0, duration: 240, easing: Easing.in(Easing.cubic), useNativeDriver: false }).start(() => onClose?.());\n }\n\n function requestDismiss() {\n if (dismissible) card.current?.dismiss();\n }\n\n const pan = useMemo(\n () =>\n PanResponder.create({\n // Own touches that start in the sheet's header band (grabber, progress) from\n // the start: otherwise a responder higher up the tree (e.g. a draggable\n // dev overlay at the app root) claims them and the sheet never sees the\n // drag. Buttons in the band (close) are deeper and still win taps.\n onStartShouldSetPanResponder: (e) => isSheet && dismissible && e.nativeEvent.pageY - sheetTop.current < DRAG_HEADER_HEIGHT,\n // Elsewhere, take over a downward drag nothing inside wanted.\n onMoveShouldSetPanResponder: (_, g) => isSheet && dismissible && isDownwardDrag(g),\n onPanResponderTerminationRequest: () => false,\n onPanResponderMove: (_, g) => drag.setValue(Math.max(0, g.dy)),\n onPanResponderRelease: (_, g) => {\n if (isDownwardDrag(g) && (g.dy > 120 || g.vy > 1)) requestDismiss();\n else Animated.spring(drag, { toValue: 0, useNativeDriver: false, bounciness: 0 }).start();\n },\n onPanResponderTerminate: () => Animated.spring(drag, { toValue: 0, useNativeDriver: false, bounciness: 0 }).start(),\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [isSheet, dismissible],\n );\n\n const cardContent = (\n <SurveyCard\n ref={card}\n survey={survey}\n theme={theme}\n variant={isSheet ? \"sheet\" : \"dialog\"}\n // The sheet runs under the home indicator; keep the button above it\n // (unless the keyboard is up, which already lifts the sheet).\n bottomInset={isSheet && !keyboardUp ? insets.bottom : 0}\n onResult={(r) => onResult?.(r)}\n onClose={animateOut}\n />\n );\n\n return (\n <View style={StyleSheet.absoluteFill} accessibilityViewIsModal>\n <Animated.View style={[StyleSheet.absoluteFill, { backgroundColor: scrim, opacity: progress }]}>\n <Pressable\n style={StyleSheet.absoluteFill}\n onPress={requestDismiss}\n // Not a VoiceOver/TalkBack element (as on iOS): the close button and\n // the platform's escape gesture already dismiss.\n accessible={false}\n importantForAccessibility=\"no\"\n />\n </Animated.View>\n\n <KeyboardAvoidingView\n behavior={insetForKeyboard ? undefined : Platform.OS === \"ios\" ? \"padding\" : \"height\"}\n // The dialog centers in the safe area, like iOS. (Its bottom inset is a\n // margin on the dialog: this view's paddingBottom belongs to the keyboard.)\n style={[styles.fill, isSheet ? styles.bottom : [styles.center, { paddingTop: insets.top }]]}\n pointerEvents=\"box-none\"\n >\n {isSheet ? (\n <Animated.View\n {...pan.panHandlers}\n onLayout={(e: LayoutChangeEvent) => {\n setSheetHeight(e.nativeEvent.layout.height);\n sheetTop.current = e.nativeEvent.layout.y;\n }}\n style={[\n styles.sheet,\n shadow,\n floating\n ? {\n borderRadius: sheetRadius,\n borderCurve: \"continuous\",\n borderWidth: StyleSheet.hairlineWidth / floatScale,\n borderColor: theme.dark ? \"rgba(255, 255, 255, 0.14)\" : \"rgba(0, 0, 0, 0.18)\",\n }\n : { borderTopLeftRadius: sheetRadius, borderTopRightRadius: sheetRadius, borderCurve: \"continuous\" },\n {\n maxHeight: window.height - insets.top - 24,\n backgroundColor: theme.surface,\n transform: [\n {\n translateY: Animated.add(\n progress.interpolate({\n inputRange: [0, 1],\n // Shown: scaling about the center lifts the bottom edge by\n // h(1-s)/2; shift so it rests FLOATING_SHEET_INSET above the screen edge.\n outputRange: [sheetHeight, floating ? (sheetHeight * (1 - floatScale)) / 2 - FLOATING_SHEET_INSET : 0],\n }),\n drag,\n ),\n },\n { scale: floatScale },\n ],\n },\n ]}\n >\n <View style={[styles.grabber, { backgroundColor: theme.secondaryText }]} />\n {cardContent}\n {insetForKeyboard && <Animated.View style={{ height: keyboardSpacer }} />}\n </Animated.View>\n ) : (\n <Animated.View\n style={[\n styles.dialog,\n shadow,\n {\n maxHeight: window.height - insets.top - insets.bottom - 48,\n marginBottom: insets.bottom,\n backgroundColor: theme.surface,\n borderRadius: theme.cornerRadius,\n borderCurve: \"continuous\",\n opacity: progress,\n transform: [{ scale: progress.interpolate({ inputRange: [0, 1], outputRange: [0.94, 1] }) }],\n },\n ]}\n >\n {cardContent}\n </Animated.View>\n )}\n </KeyboardAvoidingView>\n </View>\n );\n}\n\n/** Height of the sheet's top band that always drags the sheet. */\nconst DRAG_HEADER_HEIGHT = 72;\n\nfunction isDownwardDrag(g: PanResponderGestureState): boolean {\n return g.dy > 6 && Math.abs(g.dy) > Math.abs(g.dx);\n}\n\nconst shadow = {\n shadowColor: \"#000\",\n shadowOpacity: 0.18,\n shadowRadius: 24,\n shadowOffset: { width: 0, height: -4 },\n elevation: 16,\n} as const;\n\nconst styles = StyleSheet.create({\n fill: { flex: 1 },\n bottom: { justifyContent: \"flex-end\" },\n center: { justifyContent: \"center\", paddingHorizontal: 20 },\n sheet: { width: \"100%\", maxWidth: 640, alignSelf: \"center\" },\n dialog: { width: \"100%\", maxWidth: 480, alignSelf: \"center\", overflow: \"hidden\" },\n grabber: { position: \"absolute\", top: 6, alignSelf: \"center\", width: 36, height: 5, borderRadius: 3, opacity: 0.35, zIndex: 1 },\n});\n","//\n// SurveyCard.tsx\n//\n// The content of a survey: progress (\"1 of 3\"), close button, the current\n// question's prompt + input, and a primary Next/Submit button. Handles\n// multi-step navigation, required-answer gating, the closing \"Thanks\" state and\n// reporting the result. Port of iOS `SurveyViewController`'s card; the caller\n// supplies the chrome (sheet, dialog, or inline container).\n//\n\nimport { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { Animated, Platform, Pressable, ScrollView, StyleSheet, Text, View } from \"react-native\";\nimport type { LayoutChangeEvent } from \"react-native\";\nimport type { AnswerValue, Survey, SurveyAnswer, SurveyResult } from \"../core\";\nimport { CloseButton } from \"./CloseButton\";\nimport { QuestionInput, font, isAnswerValid } from \"./questions\";\nimport type { SurveyTheme } from \"./theme\";\n\n/** Bottom padding inside the scroll area, taken back from the button's margin. */\nconst CLIP_ROOM = 4;\n\n/** How long the \"Thanks\" confirmation shows before the card closes. */\nconst THANKS_MS = 1300;\n\nexport interface SurveyCardHandle {\n /** Dismiss as the user closing the survey (scrim tap, swipe, back button). */\n dismiss(): void;\n}\n\nexport interface SurveyCardProps {\n survey: Survey;\n theme: SurveyTheme;\n /** \"sheet\" adds room for the drag grabber above the content. */\n variant: \"sheet\" | \"dialog\" | \"inline\";\n /** Space to keep below the primary button (e.g. the home-indicator inset). */\n bottomInset?: number;\n /** Called exactly once, as soon as the outcome is known (submit or dismiss). */\n onResult: (result: SurveyResult) => void;\n /** Called when the card is done: right after a dismissal, or after the\n * \"Thanks\" confirmation following a submit. */\n onClose: () => void;\n}\n\nexport const SurveyCard = forwardRef<SurveyCardHandle, SurveyCardProps>(function SurveyCard(\n { survey, theme, variant, bottomInset, onResult, onClose },\n ref,\n) {\n const questions = useMemo(() => [...survey.questions].sort((a, b) => a.order - b.order), [survey]);\n const dismissible = survey.dismissible !== false;\n\n const [index, setIndex] = useState(0);\n // Answers commit when the user advances (Next/Submit), as on iOS, so a\n // dismissal reports only questions the user moved past.\n const committed = useRef<Record<string, AnswerValue>>({});\n const [current, setCurrent] = useState<AnswerValue | undefined>(undefined);\n const [done, setDone] = useState(false);\n const [height, setHeight] = useState(0);\n const reported = useRef(false);\n const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => () => {\n if (closeTimer.current) clearTimeout(closeTimer.current);\n }, []);\n\n const question = questions[index];\n const isLast = index >= questions.length - 1;\n const valid = question ? isAnswerValid(question, current) : false;\n\n function collected(): SurveyAnswer[] {\n return questions.filter((q) => committed.current[q.id] !== undefined).map((q) => ({ questionId: q.id, value: committed.current[q.id]! }));\n }\n\n function report(completed: boolean) {\n if (reported.current) return false;\n reported.current = true;\n onResult({ answers: collected(), completed, dismissed: !completed });\n return true;\n }\n\n function dismiss() {\n if (report(false)) onClose();\n }\n\n useImperativeHandle(ref, () => ({ dismiss }));\n\n // A survey with no questions (misconfigured) has nothing to show.\n useEffect(() => {\n if (questions.length === 0) dismiss();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n function advance() {\n if (!question || !valid) return;\n if (current !== undefined) committed.current[question.id] = current;\n if (!isLast) {\n setIndex(index + 1);\n setCurrent(undefined);\n return;\n }\n if (report(true)) {\n setDone(true);\n closeTimer.current = setTimeout(onClose, THANKS_MS);\n }\n }\n\n const pad = theme.spacing + 4;\n // Extra top room on the sheet so the title and close button clear the grabber.\n const topInset = variant === \"sheet\" ? pad + 12 : pad;\n const hasProgress = questions.length > 1;\n\n if (!question) return null;\n\n if (done) {\n const custom = survey.successMessage?.trim();\n return (\n // Keep the card's height so the sheet doesn't jump when the content swaps.\n <View style={[styles.thanks, { minHeight: height, padding: pad }]} accessibilityLiveRegion=\"polite\">\n <FadeIn>\n <View style={styles.thanksStack}>\n <View style={[styles.check, { backgroundColor: theme.accent }]}>\n <Text allowFontScaling={false} style={[styles.checkGlyph, { color: theme.accentText }]}>\n ✓\n </Text>\n </View>\n <Text style={[promptStyle(theme), { color: theme.text, textAlign: \"center\", marginTop: theme.spacing }]}>{custom || \"Thanks!\"}</Text>\n </View>\n </FadeIn>\n </View>\n );\n }\n\n return (\n <View onLayout={(e: LayoutChangeEvent) => setHeight(e.nativeEvent.layout.height)} style={styles.card}>\n {hasProgress && (\n <Text style={[font(theme, 13), { color: theme.secondaryText, marginTop: topInset, marginHorizontal: pad }]}>\n {index + 1} of {questions.length}\n </Text>\n )}\n\n <ScrollView\n style={styles.scroll}\n // A little room under the last control, so its border never sits on the\n // scroll view's clipping edge (Android snaps that edge to whole pixels and\n // shaved the bottom of the text field). The button's margin gives it back.\n contentContainerStyle={{ paddingHorizontal: pad, paddingTop: hasProgress ? theme.spacing : topInset, paddingBottom: CLIP_ROOM, gap: theme.spacing + 8 }}\n keyboardShouldPersistTaps=\"handled\"\n showsVerticalScrollIndicator={false}\n bounces={false}\n >\n <FadeIn key={question.id}>\n <View style={{ gap: theme.spacing + 8 }}>\n <Text accessibilityRole=\"header\" style={[promptStyle(theme), { color: theme.text, paddingRight: dismissible ? 48 : 0 }]}>\n {question.prompt}\n </Text>\n <QuestionInput question={question} theme={theme} value={current} onChange={setCurrent} autoFocus={variant !== \"inline\"} />\n </View>\n </FadeIn>\n </ScrollView>\n\n <Pressable\n accessibilityRole=\"button\"\n accessibilityState={{ disabled: !valid }}\n disabled={!valid}\n onPress={advance}\n style={({ pressed }) => [\n styles.button,\n {\n height: theme.controlHeight,\n marginTop: theme.spacing - CLIP_ROOM,\n marginHorizontal: pad,\n marginBottom: Math.max(pad, bottomInset ?? 0),\n borderRadius: Math.min(theme.controlRadius, theme.controlHeight / 2),\n backgroundColor: theme.accent,\n opacity: !valid ? 0.45 : pressed ? 0.9 : 1,\n },\n ]}\n >\n <Text maxFontSizeMultiplier={1.6} style={[font(theme, 16, \"600\"), { color: theme.accentText }]}>\n {isLast ? \"Submit\" : \"Next\"}\n </Text>\n </Pressable>\n\n {dismissible && (\n <CloseButton\n theme={theme}\n onPress={dismiss}\n // iOS pins the 44pt button `pad` from the card's top-right corner.\n style={Platform.OS === \"ios\" ? { top: pad, right: pad } : { top: variant === \"sheet\" ? pad + 4 : pad - 6, right: pad - 6 }}\n />\n )}\n </View>\n );\n});\n\nfunction promptStyle(theme: SurveyTheme) {\n return {\n fontSize: theme.titleSize,\n fontWeight: theme.titleWeight,\n fontFamily: theme.fontFamily,\n // iOS applies `lineHeightMultiple` to the font's natural line height (~1.2em).\n lineHeight: Math.round(theme.titleSize * 1.2 * theme.titleLineHeight),\n letterSpacing: theme.titleLetterSpacing,\n textAlign: theme.align,\n } as const;\n}\n\n/** Fades its children in on mount (question changes, the thanks state). */\nfunction FadeIn({ children }: { children: ReactNode }) {\n const opacity = useRef(new Animated.Value(0)).current;\n useEffect(() => {\n // JS driver: a native-driven opacity is re-committed as 0 when the keyboard\n // re-lays out the card (see SurveyModal).\n Animated.timing(opacity, { toValue: 1, duration: 220, useNativeDriver: false }).start();\n }, [opacity]);\n return <Animated.View style={{ opacity }}>{children}</Animated.View>;\n}\n\nconst styles = StyleSheet.create({\n card: { flexShrink: 1 },\n scroll: { flexGrow: 0, flexShrink: 1 },\n button: { alignItems: \"center\", justifyContent: \"center\" },\n thanks: { alignItems: \"center\", justifyContent: \"center\" },\n thanksStack: { alignItems: \"center\" },\n check: { width: 48, height: 48, borderRadius: 24, alignItems: \"center\", justifyContent: \"center\" },\n checkGlyph: { fontSize: 26, fontWeight: \"700\", lineHeight: 30 },\n});\n","//\n// CloseButton.tsx\n//\n// The survey's close button, drawn to match the iOS SDK on the same device:\n// • iOS 26+: a glass circle (`UIButton.Configuration.glass()`, 44pt, bold xmark).\n// • iOS < 26: `xmark.circle.fill` tinted secondary label (the cross is cut out).\n// • Android: a neutral filled circle.\n// The cross is two rounded bars rather than a text glyph, so its weight matches\n// SF Symbols instead of depending on the font's \"✕\".\n//\n\nimport { Platform, Pressable, StyleSheet, View } from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { usesGlassChrome } from \"./platform\";\nimport type { SurveyTheme } from \"./theme\";\n\nexport function CloseButton({ theme, onPress, style }: { theme: SurveyTheme; onPress: () => void; style?: ViewStyle }) {\n let circle: ViewStyle;\n let cross: { color: string; length: number; thickness: number };\n if (usesGlassChrome) {\n circle = {\n width: 44,\n height: 44,\n borderRadius: 22,\n backgroundColor: theme.dark ? \"rgba(72, 72, 74, 0.92)\" : \"rgba(255, 255, 255, 0.94)\",\n borderWidth: StyleSheet.hairlineWidth,\n borderColor: theme.dark ? \"rgba(255, 255, 255, 0.16)\" : \"rgba(0, 0, 0, 0.14)\",\n shadowColor: \"#000\",\n shadowOpacity: theme.dark ? 0.3 : 0.08,\n shadowRadius: 8,\n shadowOffset: { width: 0, height: 2 },\n };\n cross = { color: theme.dark ? \"rgba(255, 255, 255, 0.92)\" : \"rgba(0, 0, 0, 0.88)\", length: 19, thickness: 2.6 };\n } else if (Platform.OS === \"ios\") {\n circle = { width: 31, height: 31, borderRadius: 15.5, backgroundColor: theme.dark ? \"rgba(235, 235, 245, 0.6)\" : \"rgba(60, 60, 67, 0.6)\" };\n cross = { color: theme.surface, length: 12, thickness: 2.4 };\n } else {\n circle = { width: 32, height: 32, borderRadius: 16, backgroundColor: theme.track };\n cross = { color: theme.secondaryText, length: 13, thickness: 2 };\n }\n\n return (\n <Pressable accessibilityRole=\"button\" accessibilityLabel=\"Close survey\" onPress={onPress} hitSlop={6} style={[styles.hit, style]}>\n {({ pressed }) => (\n <View style={[circle, styles.center, pressed && { opacity: 0.7 }]}>\n {[45, -45].map((deg) => (\n <View\n key={deg}\n style={{\n position: \"absolute\",\n width: cross.length,\n height: cross.thickness,\n borderRadius: cross.thickness / 2,\n backgroundColor: cross.color,\n transform: [{ rotate: `${deg}deg` }],\n }}\n />\n ))}\n </View>\n )}\n </Pressable>\n );\n}\n\nconst styles = StyleSheet.create({\n hit: { position: \"absolute\", width: 44, height: 44, alignItems: \"center\", justifyContent: \"center\" },\n center: { alignItems: \"center\", justifyContent: \"center\" },\n});\n","//\n// platform.ts\n//\n// iOS 26 redesigned system chrome (\"Liquid Glass\"): sheets float inset from the\n// screen edges with corners concentric to the display, and close buttons are\n// glass circles. The iOS SDK gets these from UIKit (`UISheetPresentationController`,\n// `UIButton.Configuration.glass()`); this SDK draws its own, so it mirrors them\n// here to look the same on the same device. Android keeps Material conventions.\n//\n\nimport { Platform } from \"react-native\";\n\n/** True on iOS 26+, where the native SDK's sheet floats and its close button is glass. */\nexport const usesGlassChrome = Platform.OS === \"ios\" && parseInt(String(Platform.Version), 10) >= 26;\n\n/** Inset of a floating iOS 26 sheet from the screen edges, measured from the native sheet. */\nexport const FLOATING_SHEET_INSET = 8;\n\n/** Corner radius of a floating iOS 26 sheet on Face ID iPhones (concentric with\n * the display corners), measured from the native sheet. */\nexport const FLOATING_SHEET_RADIUS = 52;\n","//\n// questions.tsx\n//\n// One renderer per question type, ported from the iOS UI/*View.swift files.\n// Each takes the question, the current answer, and an `onChange`, and emits the\n// exact `AnswerValue` JSON the backend expects (API-CONTRACT §Answer value\n// shapes). Every visual value comes from the resolved `SurveyTheme`.\n//\n\nimport { useState } from \"react\";\nimport { Pressable, StyleSheet, Text, TextInput, View } from \"react-native\";\nimport type { LayoutChangeEvent, TextStyle } from \"react-native\";\nimport type { AnswerValue, ChoiceOption, EmojiOption, Question } from \"../core\";\nimport { clampRadius } from \"./theme\";\nimport type { FontWeight, SurveyTheme } from \"./theme\";\n\nexport interface QuestionInputProps {\n question: Question;\n theme: SurveyTheme;\n value: AnswerValue | undefined;\n onChange: (value: AnswerValue | undefined) => void;\n /** Focus text inputs as soon as they show (overlays; not inline embeds). */\n autoFocus?: boolean;\n}\n\nexport function QuestionInput({ question, theme, value, onChange, autoFocus }: QuestionInputProps) {\n const cfg = question.config;\n switch (cfg.kind) {\n case \"scale\":\n return <ScaleInput min={cfg.min} max={cfg.max} minLabel={cfg.minLabel} maxLabel={cfg.maxLabel} theme={theme} value={numValue(value)} onPick={(n) => onChange({ value: n })} />;\n case \"stars\":\n return <StarsInput count={cfg.count} theme={theme} value={numValue(value)} onPick={(n) => onChange({ value: n })} />;\n case \"emoji\":\n return <EmojiInput options={cfg.options} theme={theme} value={strValue(value)} onPick={(v) => onChange({ value: v })} />;\n case \"thumbs\":\n return <ThumbsInput theme={theme} value={strValue(value)} onPick={(v) => onChange({ value: v })} />;\n case \"singleChoice\":\n return <ChoiceInput options={cfg.options} theme={theme} value={value && \"choice\" in value ? value.choice : undefined} onPick={(v) => onChange({ choice: v })} />;\n case \"openText\":\n return (\n <OpenTextInput\n placeholder={cfg.placeholder}\n maxLength={cfg.maxLength}\n theme={theme}\n autoFocus={autoFocus}\n // Like iOS: the answer is the trimmed text, and empty text is no answer.\n onText={(t) => onChange(t.trim().length > 0 ? { text: t.trim() } : undefined)}\n />\n );\n }\n}\n\n/** Whether `value` satisfies the question's `required` rule. */\nexport function isAnswerValid(question: Question, value: AnswerValue | undefined): boolean {\n return question.required ? value !== undefined : true;\n}\n\n// ── helpers ───────────────────────────────────────────────────────────────────\n\nfunction numValue(v: AnswerValue | undefined): number | undefined {\n return v && \"value\" in v && typeof v.value === \"number\" ? v.value : undefined;\n}\nfunction strValue(v: AnswerValue | undefined): string | undefined {\n return v && \"value\" in v && typeof v.value === \"string\" ? v.value : undefined;\n}\n\n/** A text style at `size` (scaled by the theme's text scale) in the theme font. */\nexport function font(theme: SurveyTheme, size: number, weight: FontWeight = \"400\"): TextStyle {\n return { fontSize: size * theme.textScale, fontWeight: weight, fontFamily: theme.fontFamily };\n}\n\n/** Large controls shouldn't grow without bound under accessibility text sizes. */\nconst MAX_FONT_SCALE = 1.6;\n\n// ── Scale (NPS / CES) ─────────────────────────────────────────────────────────\n\nconst CHIP_GAP = 8;\n/** Minimum chip side, as iOS `ChipButton(minSide: 44)`. */\nconst CHIP_MIN_SIDE = 44;\n\nfunction ScaleInput({ min, max, minLabel, maxLabel, theme, value, onPick }: { min: number; max: number; minLabel?: string; maxLabel?: string; theme: SurveyTheme; value: number | undefined; onPick: (n: number) => void }) {\n const [width, setWidth] = useState(0);\n // Defend against a malformed (reversed/equal) range from the backend.\n const lo = Math.min(min, max);\n const hi = Math.max(min, max);\n const points: number[] = [];\n for (let i = lo; i <= hi; i++) points.push(i);\n\n // Compact scales (≤7, e.g. CES 1–7) stretch to fill the row like a segmented\n // control, never taller than wide (so pills stay round). Wider scales (NPS\n // 0–10) wrap as centered rows of square chips.\n const compact = points.length <= 7;\n const chipWidth = compact && width > 0 ? (width - CHIP_GAP * (points.length - 1)) / points.length : CHIP_MIN_SIDE;\n const chipHeight = compact ? Math.min(theme.controlHeight, chipWidth) : CHIP_MIN_SIDE;\n const hasLabels = !!minLabel || !!maxLabel;\n\n return (\n <View onLayout={(e: LayoutChangeEvent) => setWidth(e.nativeEvent.layout.width)}>\n <View style={[styles.scaleRow, !compact && styles.wrap]}>\n {width > 0 &&\n points.map((n) => {\n const on = value === n;\n return (\n <Pressable\n key={n}\n accessibilityRole=\"button\"\n accessibilityLabel={String(n)}\n accessibilityState={{ selected: on }}\n onPress={() => onPick(n)}\n style={({ pressed }) => [\n styles.chip,\n {\n width: compact ? chipWidth : undefined,\n minWidth: compact ? undefined : CHIP_MIN_SIDE,\n height: chipHeight,\n borderRadius: clampRadius(theme.controlRadius, compact ? chipWidth : CHIP_MIN_SIDE, chipHeight),\n backgroundColor: on ? theme.accent : theme.surface,\n borderColor: on ? theme.accent : theme.border,\n opacity: pressed ? 0.85 : 1,\n },\n ]}\n >\n <Text maxFontSizeMultiplier={MAX_FONT_SCALE} style={[font(theme, 16, \"500\"), { color: on ? theme.accentText : theme.text }]}>\n {n}\n </Text>\n </Pressable>\n );\n })}\n </View>\n {hasLabels && (\n <View style={styles.endLabels}>\n <Text style={[font(theme, 13), styles.endLabel, { color: theme.secondaryText }]} numberOfLines={2}>\n {minLabel}\n </Text>\n <Text style={[font(theme, 13), styles.endLabel, { color: theme.secondaryText, textAlign: \"right\" }]} numberOfLines={2}>\n {maxLabel}\n </Text>\n </View>\n )}\n </View>\n );\n}\n\n// ── Stars (CSAT_STAR) ─────────────────────────────────────────────────────────\n\nfunction StarsInput({ count, theme, value, onPick }: { count: number; theme: SurveyTheme; value: number | undefined; onPick: (n: number) => void }) {\n const stars: number[] = [];\n for (let i = 1; i <= Math.max(1, count); i++) stars.push(i);\n return (\n <View style={styles.starsRow}>\n {stars.map((n) => {\n const on = value !== undefined && n <= value;\n return (\n <Pressable\n key={n}\n accessibilityRole=\"button\"\n accessibilityLabel={`${n} star${n === 1 ? \"\" : \"s\"}`}\n accessibilityState={{ selected: value === n }}\n onPress={() => onPick(n)}\n hitSlop={4}\n style={styles.star}\n >\n <Text allowFontScaling={false} style={{ fontSize: 38, lineHeight: 46, color: theme.accent }}>\n {on ? \"★\" : \"☆\"}\n </Text>\n </Pressable>\n );\n })}\n </View>\n );\n}\n\n// ── Emoji (CSAT_EMOJI) ────────────────────────────────────────────────────────\n\nfunction EmojiInput({ options, theme, value, onPick }: { options: EmojiOption[]; theme: SurveyTheme; value: string | undefined; onPick: (v: string) => void }) {\n return (\n <View style={styles.emojiRow}>\n {options.map((o) => {\n const on = value === o.value;\n return (\n <Pressable\n key={o.value}\n accessibilityRole=\"button\"\n accessibilityLabel={o.label || o.value}\n accessibilityState={{ selected: on }}\n onPress={() => onPick(o.value)}\n style={({ pressed }) => [\n styles.emojiCell,\n {\n borderRadius: theme.controlRadius,\n backgroundColor: on ? theme.accentTintStrong : theme.surface,\n borderColor: on ? theme.accent : theme.border,\n opacity: pressed ? 0.85 : 1,\n },\n ]}\n >\n <Text allowFontScaling={false} style={styles.emojiGlyph}>\n {o.emoji}\n </Text>\n {!!o.label && (\n <Text maxFontSizeMultiplier={MAX_FONT_SCALE} style={[font(theme, 13), { color: theme.secondaryText, textAlign: \"center\" }]}>\n {o.label}\n </Text>\n )}\n </Pressable>\n );\n })}\n </View>\n );\n}\n\n// ── Thumbs ────────────────────────────────────────────────────────────────────\n\nfunction ThumbsInput({ theme, value, onPick }: { theme: SurveyTheme; value: string | undefined; onPick: (v: \"up\" | \"down\") => void }) {\n const sides = [\n { value: \"up\" as const, emoji: \"👍\", label: \"Thumbs up\" },\n { value: \"down\" as const, emoji: \"👎\", label: \"Thumbs down\" },\n ];\n return (\n <View style={styles.thumbsRow}>\n {sides.map((s) => {\n const on = value === s.value;\n return (\n <Pressable\n key={s.value}\n accessibilityRole=\"button\"\n accessibilityLabel={s.label}\n accessibilityState={{ selected: on }}\n onPress={() => onPick(s.value)}\n style={({ pressed }) => [\n styles.thumb,\n {\n height: theme.controlHeight,\n borderRadius: clampRadius(theme.controlRadius, Infinity, theme.controlHeight),\n backgroundColor: on ? theme.accent : theme.surface,\n borderColor: on ? theme.accent : theme.border,\n opacity: pressed ? 0.85 : 1,\n },\n ]}\n >\n <Text allowFontScaling={false} style={styles.thumbGlyph}>\n {s.emoji}\n </Text>\n </Pressable>\n );\n })}\n </View>\n );\n}\n\n// ── Single choice ─────────────────────────────────────────────────────────────\n\nfunction ChoiceInput({ options, theme, value, onPick }: { options: ChoiceOption[]; theme: SurveyTheme; value: string | undefined; onPick: (v: string) => void }) {\n return (\n <View style={styles.choices}>\n {options.map((o) => {\n const on = value === o.value;\n return (\n <Pressable\n key={o.value}\n accessibilityRole=\"radio\"\n accessibilityLabel={o.label}\n accessibilityState={{ checked: on }}\n onPress={() => onPick(o.value)}\n style={({ pressed }) => [\n styles.choice,\n {\n minHeight: theme.controlHeight,\n borderRadius: clampRadius(theme.controlRadius, Infinity, theme.controlHeight),\n backgroundColor: on ? theme.accentTint : theme.surface,\n borderColor: on ? theme.accent : theme.border,\n opacity: pressed ? 0.85 : 1,\n },\n ]}\n >\n <Text style={[font(theme, 16), styles.choiceLabel, { color: theme.text }]}>{o.label}</Text>\n <View\n style={[\n styles.radio,\n on ? { backgroundColor: theme.accent, borderColor: theme.accent } : { borderColor: theme.border },\n ]}\n >\n {on && (\n <Text allowFontScaling={false} style={[styles.radioCheck, { color: theme.accentText }]}>\n ✓\n </Text>\n )}\n </View>\n </Pressable>\n );\n })}\n </View>\n );\n}\n\n// ── Open text ─────────────────────────────────────────────────────────────────\n\nfunction OpenTextInput({ placeholder, maxLength, theme, autoFocus, onText }: { placeholder?: string; maxLength?: number; theme: SurveyTheme; autoFocus?: boolean; onText: (t: string) => void }) {\n const [text, setText] = useState(\"\");\n const [focused, setFocused] = useState(false);\n return (\n <View>\n <TextInput\n multiline\n // Raise the keyboard as soon as the question shows, like iOS `activate()`.\n autoFocus={autoFocus}\n value={text}\n onChangeText={(t) => {\n setText(t);\n onText(t);\n }}\n onFocus={() => setFocused(true)}\n onBlur={() => setFocused(false)}\n placeholder={placeholder}\n placeholderTextColor={theme.secondaryText}\n maxLength={maxLength}\n textAlignVertical=\"top\"\n style={[\n font(theme, 16),\n styles.textArea,\n {\n minHeight: theme.controlHeight * 2,\n borderRadius: theme.controlRadius,\n borderColor: focused ? theme.accent : theme.border,\n backgroundColor: theme.surface,\n color: theme.text,\n },\n ]}\n />\n {maxLength !== undefined && (\n <Text style={[font(theme, 13), styles.counter, { color: theme.secondaryText }]}>\n {text.length}/{maxLength}\n </Text>\n )}\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n scaleRow: { flexDirection: \"row\", gap: CHIP_GAP },\n wrap: { flexWrap: \"wrap\", justifyContent: \"center\" },\n chip: { borderWidth: 1, alignItems: \"center\", justifyContent: \"center\", paddingHorizontal: 10 },\n endLabels: { flexDirection: \"row\", gap: 12, marginTop: 10, paddingHorizontal: 2 },\n endLabel: { flex: 1 },\n starsRow: { flexDirection: \"row\", justifyContent: \"center\", gap: 6, height: 48, alignItems: \"center\" },\n star: { paddingHorizontal: 2 },\n emojiRow: { flexDirection: \"row\", flexWrap: \"wrap\", justifyContent: \"center\", columnGap: 10, rowGap: 12 },\n emojiCell: { minWidth: 64, paddingVertical: 8, paddingHorizontal: 10, borderWidth: 1, alignItems: \"center\", gap: 2 },\n emojiGlyph: { fontSize: 32, lineHeight: 40 },\n thumbsRow: { flexDirection: \"row\", gap: 16 },\n thumb: { flex: 1, borderWidth: 1, alignItems: \"center\", justifyContent: \"center\" },\n thumbGlyph: { fontSize: 32, lineHeight: 40 },\n choices: { gap: 10 },\n choice: { flexDirection: \"row\", alignItems: \"center\", borderWidth: 1, paddingVertical: 14, paddingHorizontal: 16, gap: 12 },\n choiceLabel: { flex: 1 },\n radio: { width: 22, height: 22, borderRadius: 11, borderWidth: 1.5, alignItems: \"center\", justifyContent: \"center\" },\n radioCheck: { fontSize: 13, lineHeight: 16, fontWeight: \"700\" },\n textArea: { borderWidth: 1, paddingHorizontal: 16, paddingTop: 12, paddingBottom: 12 },\n counter: { marginTop: 6, textAlign: \"right\" },\n});\n","//\n// theme.ts\n//\n// Maps the dashboard's `ProjectTheme` onto concrete style values, starting from\n// the same light/dark defaults as iOS `SurveyTheme.default` and overriding only\n// the keys provided (port of iOS `Presenter.makeTheme`). Pure, so it's unit\n// tested without a device.\n//\n\nimport type { ProjectTheme } from \"../core\";\n\nexport type ColorScheme = \"light\" | \"dark\";\nexport type FontWeight = \"400\" | \"500\" | \"600\" | \"700\";\n\nexport interface SurveyTheme {\n /** Dim behind the sheet/dialog. */\n scrim: string;\n surface: string;\n text: string;\n secondaryText: string;\n accent: string;\n accentText: string;\n border: string;\n /** Neutral fill (close button, unselected tracks). */\n track: string;\n /** Selected-control tints (accent at low opacity). */\n accentTint: string;\n accentTintStrong: string;\n\n /** Dialog corner radius, and the sheet's when `cornerRadius` is configured. */\n cornerRadius: number;\n /** Sheet top-corner radius: device-like by default, `cornerRadius` if set. */\n sheetCornerRadius: number;\n /** No `cornerRadius` configured: sheets keep the platform's native corners. */\n nativeSheetCorners: boolean;\n /** Resolved for dark mode (drives chrome the dashboard theme doesn't cover). */\n dark: boolean;\n controlRadius: number;\n controlHeight: number;\n spacing: number;\n\n /** Body/option/button/caption text multiplier (not the title). */\n textScale: number;\n titleSize: number;\n titleWeight: FontWeight;\n titleLineHeight: number;\n titleLetterSpacing: number;\n\n position: \"bottom\" | \"center\";\n align: \"left\" | \"center\";\n /** A host-registered font family, or undefined for the system font. */\n fontFamily?: string;\n}\n\nconst PALETTES: Record<ColorScheme, Pick<SurveyTheme, \"surface\" | \"text\" | \"secondaryText\" | \"accent\" | \"accentText\" | \"border\" | \"track\"> & { background: string }> = {\n light: {\n background: \"#09090B\",\n surface: \"#FFFFFF\",\n text: \"#18181B\",\n secondaryText: \"#71717A\",\n accent: \"#2E7272\", // Slate Teal (brand primary)\n accentText: \"#FFFFFF\",\n border: \"#E4E4E7\",\n track: \"#F4F4F5\",\n },\n dark: {\n background: \"#000000\",\n surface: \"#1A1A1E\",\n text: \"#FAFAFA\",\n secondaryText: \"#A1A1AA\",\n accent: \"#41B2B2\",\n accentText: \"#FFFFFF\",\n border: \"#333338\",\n track: \"#27272A\",\n },\n};\n\nconst WEIGHTS: Record<string, FontWeight> = { regular: \"400\", medium: \"500\", semibold: \"600\", bold: \"700\" };\n\nexport interface ResolveThemeOptions {\n scheme?: ColorScheme;\n /** Per-survey `presentation` (\"sheet\" | \"dialog\"), overriding the theme position. */\n presentation?: string | null;\n /** Font family the host registered (e.g. via expo-font). */\n fontFamily?: string;\n}\n\nexport function resolveTheme(project: ProjectTheme | null | undefined, opts: ResolveThemeOptions = {}): SurveyTheme {\n const p = project ?? {};\n const base = PALETTES[opts.scheme ?? \"light\"];\n\n const accent = color(p.accent) ?? base.accent;\n const controlHeight = num(p.controlHeight) ?? 48;\n let cornerRadius = 16;\n let sheetCornerRadius = 28;\n let controlRadius = 12;\n // A configured cornerRadius overrides the device-like sheet corner too, and\n // seeds the control radius (iOS: radius - 2) unless controlRadius is set.\n const cr = num(p.cornerRadius);\n if (cr !== undefined) {\n cornerRadius = cr;\n sheetCornerRadius = cr;\n controlRadius = Math.max(0, cr - 2);\n }\n controlRadius = num(p.controlRadius) ?? controlRadius;\n if (p.controlPill === true) controlRadius = controlHeight / 2;\n\n let position: SurveyTheme[\"position\"] = p.position === \"center\" ? \"center\" : \"bottom\";\n switch (opts.presentation) {\n case \"dialog\":\n case \"center\":\n position = \"center\";\n break;\n case \"sheet\":\n case \"bottom\":\n position = \"bottom\";\n break;\n }\n\n return {\n // A fixed ~40% dim of the (opaque) configured background, like iOS.\n scrim: withAlpha(color(p.background) ?? base.background, 0.4),\n surface: color(p.surface) ?? base.surface,\n text: color(p.text) ?? base.text,\n secondaryText: color(p.secondaryText) ?? base.secondaryText,\n accent,\n accentText: color(p.accentText) ?? base.accentText,\n border: color(p.border) ?? base.border,\n track: base.track,\n accentTint: withAlpha(accent, 0.1),\n accentTintStrong: withAlpha(accent, 0.12),\n cornerRadius,\n sheetCornerRadius,\n nativeSheetCorners: cr === undefined,\n dark: opts.scheme === \"dark\",\n controlRadius,\n controlHeight,\n spacing: num(p.spacing) ?? 16,\n textScale: Math.max(0.5, num(p.textScale) ?? 1),\n titleSize: num(p.titleSize) ?? 20,\n titleWeight: WEIGHTS[(p.titleWeight ?? \"\").toLowerCase()] ?? \"600\",\n titleLineHeight: num(p.titleLineHeight) ?? 1.1,\n titleLetterSpacing: num(p.titleLetterSpacing) ?? 0,\n position,\n align: p.alignment === \"center\" ? \"center\" : \"left\",\n fontFamily: opts.fontFamily,\n };\n}\n\n/** Corner radius for a control of the given size: a pill radius past half the\n * shorter side would distort, so clamp it (as iOS `ChipButton` does). */\nexport function clampRadius(radius: number, width: number, height: number): number {\n return Math.min(radius, Math.min(width, height) / 2);\n}\n\nfunction num(v: unknown): number | undefined {\n return typeof v === \"number\" && Number.isFinite(v) ? v : undefined;\n}\n\n/** Normalizes `#RGB`, `#RRGGBB` or `#RRGGBBAA` (with or without `#`) to\n * `#RRGGBB[AA]`. Returns undefined for empty/invalid input so callers keep\n * their default. */\nexport function color(hex: string | null | undefined): string | undefined {\n if (typeof hex !== \"string\") return undefined;\n let h = hex.trim().replace(/^#/, \"\");\n if (h.length === 3) h = h.replace(/./g, (c) => c + c);\n if (!/^[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(h)) return undefined;\n return \"#\" + h.toUpperCase();\n}\n\n/** `#RRGGBB[AA]` → `rgba(r, g, b, alpha)` (replacing any existing alpha). */\nexport function withAlpha(hex: string, alpha: number): string {\n const h = (color(hex) ?? \"#000000\").slice(1);\n const r = parseInt(h.slice(0, 2), 16);\n const g = parseInt(h.slice(2, 4), 16);\n const b = parseInt(h.slice(4, 6), 16);\n return `rgba(${r}, ${g}, ${b}, ${alpha})`;\n}\n","//\n// MicroSurvey.tsx\n//\n// `<MicroSurvey surveyId>` — renders a specific survey **inline** in a screen\n// (no overlay), e.g. in a settings or feedback screen. Pulls the survey from\n// the cached config, sends an impression when it renders and a response when it\n// closes. It\n// ignores triggers and platform targeting: rendering it is an explicit choice.\n//\n\nimport { useContext, useEffect, useMemo, useRef, useState } from \"react\";\nimport { View, useColorScheme } from \"react-native\";\nimport type { StyleProp, ViewStyle } from \"react-native\";\nimport type { ActiveSurvey, Survey, SurveyResult } from \"./core\";\nimport { MicroSurveysContext } from \"./provider\";\nimport { SurveyCard } from \"./ui/SurveyCard\";\nimport { resolveTheme } from \"./ui/theme\";\n\nexport interface MicroSurveyProps {\n surveyId: string;\n /** Called with the outcome after the survey closes. */\n onComplete?: (result: SurveyResult) => void;\n /** Style for the card container (margins, width, …). */\n style?: StyleProp<ViewStyle>;\n}\n\nexport function MicroSurvey({ surveyId, onComplete, style }: MicroSurveyProps) {\n const { instance, fontFamily } = useContext(MicroSurveysContext);\n const scheme = useColorScheme() === \"dark\" ? \"dark\" : \"light\";\n const [survey, setSurvey] = useState<Survey | null>(null);\n const [closed, setClosed] = useState(false);\n // One showing per mounted survey: its impression is sent once, when it renders.\n const showing = useRef<ActiveSurvey | null>(null);\n const result = useRef<SurveyResult | null>(null);\n\n useEffect(() => {\n if (!instance) return;\n // Fires once config is loaded, then on every refresh (the survey may not be cached yet).\n return instance.onConfigChange(() => setSurvey(instance.getSurvey(surveyId) ?? null));\n }, [instance, surveyId]);\n\n const projectTheme = instance?.getTheme();\n const theme = useMemo(() => resolveTheme(projectTheme, { scheme, fontFamily }), [projectTheme, scheme, fontFamily]);\n\n const visible = !!instance && !!survey && !closed;\n if (visible && (!showing.current || showing.current.survey.id !== survey.id)) {\n showing.current = instance.presentInline(survey);\n }\n\n useEffect(() => {\n if (visible) showing.current?.shown();\n }, [visible, survey]);\n\n if (!instance || !survey || closed) return null;\n\n return (\n <View\n style={[\n { backgroundColor: theme.surface, borderRadius: theme.cornerRadius, borderWidth: 1, borderColor: theme.border, overflow: \"hidden\" },\n style,\n ]}\n >\n <SurveyCard\n survey={survey}\n theme={theme}\n variant=\"inline\"\n onResult={(r) => {\n result.current = r;\n showing.current?.close(r);\n }}\n onClose={() => {\n setClosed(true);\n if (result.current) onComplete?.(result.current);\n }}\n />\n </View>\n );\n}\n"],"mappings":";;;;;AAiBA,OAAO,kBAAkB;AACzB,SAAS,UAAU,gBAAgB;;;ACC5B,IAAM,qBAAqB;AAa3B,SAAS,OAAe;AAC7B,MAAI;AAEF,UAAM,SAAU,WAA0D;AAC1E,QAAI,UAAU,OAAO,OAAO,eAAe,YAAY;AACrD,aAAO,OAAO,WAAW;AAAA,IAC3B;AAAA,EACF,QAAQ;AAAA,EAER;AAEA,SAAO,uCAAuC,QAAQ,SAAS,CAAC,MAAM;AACpE,UAAM,IAAK,KAAK,OAAO,IAAI,KAAM;AACjC,UAAM,IAAI,MAAM,MAAM,IAAK,IAAI,I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ACjB,oBAAQ,SAAS,MAAM,CAAC;AAAA,UAC1B;AAAA,UACA,SAAS,MAAM;AACb,sBAAU,IAAI;AACd,gBAAI,OAAO,QAAS,cAAa,OAAO,OAAO;AAAA,UACjD;AAAA;AAAA,MACF;AAAA;AAAA,EACF;AAEJ;","names":["DEFAULT_BASE_URL","DEFAULT_CONFIG_TTL_MS","useEffect","useMemo","useRef","useState","useEffect","useMemo","useRef","useState","Animated","Platform","Pressable","StyleSheet","View","useState","Platform","Pressable","StyleSheet","Text","View","Platform","Platform","Platform","Pressable","StyleSheet","View","jsx","View","styles","Pressable","StyleSheet","jsx","jsxs","SurveyCard","useState","advance","View","styles","Text","Pressable","Platform","StyleSheet","jsx","jsxs","useMemo","useRef","Platform","Animated","useState","useEffect","View","StyleSheet","Pressable","styles","jsx","jsxs","useState","useEffect","useMemo","useRef","useContext","useEffect","useMemo","useRef","useState","View","useColorScheme","jsx","useContext","useColorScheme","useState","useRef","useEffect","useMemo","View"]}