@microsurveysai/react-native 0.1.0 → 0.1.2
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/README.md +1 -0
- package/dist/index.cjs +60 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +17 -1
- package/dist/index.d.ts +17 -1
- package/dist/index.js +60 -10
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../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/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// @microsurveysai/react-native\n//\n// React Native SDK for MicroSurveys. Surveys configured in the dashboard are\n// evaluated on-device against the events you track (or forward from Amplitude)\n// and presented natively as a bottom sheet or dialog.\n//\n// export const ms = new MicroSurveys({ apiKey: \"ms_live_…\" });\n// amplitude.add(ms.amplitudePlugin()); // optional\n//\n// <MicroSurveysProvider instance={ms}>\n// <App />\n// </MicroSurveysProvider>\n//\n// ms.track(\"checkout_completed\", { plan: \"pro\" });\n//\n\nexport { MicroSurveys } from \"./MicroSurveys\";\nexport type { MicroSurveysOptions } from \"./MicroSurveys\";\nexport { MicroSurveysProvider, useMicroSurveys, useMicroSurveysInstance } from \"./provider\";\nexport type { MicroSurveysProviderProps } from \"./provider\";\nexport { MicroSurvey } from \"./MicroSurvey\";\nexport type { MicroSurveyProps } from \"./MicroSurvey\";\nexport { SurveyModal } from \"./ui/SurveyModal\";\nexport type { SurveyModalProps } from \"./ui/SurveyModal\";\nexport { hydrateAsyncStorage } from \"./asyncStorage\";\nexport type { AsyncKeyValueStorage } from \"./asyncStorage\";\nexport type { AmplitudeEvent, MicroSurveysAmplitudePlugin } from \"./amplitude\";\n\n// Re-export the common wire types so consumers don't need a second import.\nexport { parseConfig } from \"./core\";\nexport type {\n Survey,\n Question,\n SurveyResult,\n SurveyAnswer,\n AnswerValue,\n ProjectTheme,\n KeyValueStorage,\n} from \"./core\";\n","//\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}\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\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 storage: kv,\n subscribeForeground: appStateForeground,\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}\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// ── 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\nfunction normalizeConfig(type: QuestionType, raw: Record<string, unknown>): QuestionConfig {\n switch (type) {\n case \"NPS\":\n return { kind: \"scale\", min: numOr(raw.min, 0), max: numOr(raw.max, 10), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };\n case \"CES\":\n return { kind: \"scale\", min: numOr(raw.min, 1), max: numOr(raw.max, 7), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };\n case \"CSAT_STAR\":\n return { kind: \"stars\", count: numOr(raw.count, 5) };\n case \"CSAT_EMOJI\": {\n const opts = Array.isArray(raw.options) ? 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 = Array.isArray(raw.options) ? 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 questions = (Array.isArray(raw.questions) ? raw.questions : [])\n .map((q) => normalizeQuestion(asObject(q)))\n .filter((q): q is Question => q !== null);\n const triggers = (Array.isArray(raw.triggers) ? raw.triggers : [])\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, surveys };\n}\n","//\n// apiClient.ts\n//\n// `fetch`-based client for the three 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 { parseConfig } from \"./types\";\nimport type { SDKConfig, SurveyAnswer, JsonObject } 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\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 // ── Impressions / responses ─────────────────────────────────────────────────\n\n recordImpression(input: {\n surveyId: string;\n triggerId: string | null;\n endUserId: string;\n shownAt: Date;\n dismissed: boolean;\n }): void {\n const payload = {\n clientId: uuid(),\n surveyId: input.surveyId,\n triggerId: input.triggerId ?? undefined,\n endUserId: input.endUserId,\n shownAt: input.shownAt.toISOString(),\n dismissed: input.dismissed,\n };\n this.enqueue(\"/api/sdk/impressions\", { impressions: [payload] });\n }\n\n recordResponse(input: {\n surveyId: string;\n endUserId: string;\n completed: boolean;\n submittedAt: Date;\n userProps: JsonObject;\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 answers: input.answers,\n };\n this.enqueue(\"/api/sdk/responses\", { responses: [payload] });\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. Idempotency keys make re-sends\n * safe. Never throws. */\n async flush(): Promise<void> {\n if (this.isFlushing) return;\n this.isFlushing = true;\n try {\n for (const entry of this.outbox.snapshot()) {\n try {\n await this.post(entry.path, entry.body);\n this.outbox.remove(entry.id);\n } catch {\n break; // network/server problem — retry on the next flush\n }\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 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). */\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 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 } from \"./sampling\";\nimport { newTriggerRecord, endUserIdOf } from \"./types\";\nimport type { TriggerStateStore } from \"./persistence\";\nimport type { Identity, Survey, Trigger, UserTriggerState } from \"./types\";\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}\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 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 }\n\n /** Feed an event into the engine. */\n process(name: string, properties: Record<string, unknown> = {}): void {\n const identity = this.identityProvider();\n const endUserId = endUserIdOf(identity);\n const state = this.store.load(endUserId);\n const nowT = this.now();\n\n for (const survey of this.surveysProvider()) {\n const triggers = survey.triggers;\n if (!triggers || triggers.length === 0) continue;\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)) continue;\n\n for (const trigger of triggers) {\n const satisfied = this.advanceTrigger(trigger, state, name, properties, nowT);\n if (!satisfied) continue;\n\n const occurrence = state.triggers[trigger.id]?.satisfiedCount ?? 0;\n\n // (1) window\n if (!this.isWithinWindow(survey, nowT)) continue;\n // (3) frequency\n if (!passesFrequency(trigger, occurrence)) continue;\n // (4) audience\n if (survey.audienceMatch && !audienceMatches(survey.audienceMatch, identity.userProperties)) continue;\n // (5) sampling (sticky)\n if (!this.passesSampling(survey, endUserId, state)) continue;\n // (6) cap\n if (!passesCap(survey, state, nowT)) continue;\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 isWithinWindow(survey: Survey, nowT: number): boolean {\n if (survey.startsAt) {\n const start = Date.parse(survey.startsAt);\n if (!Number.isNaN(start) && nowT < start / 1000) return false;\n }\n if (survey.endsAt) {\n const end = Date.parse(survey.endsAt);\n if (!Number.isNaN(end) && nowT > end / 1000) return false;\n }\n return true;\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)) return;\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// 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 } 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 { endUserIdOf } from \"./types\";\nimport type { 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\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 /** 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}\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 subscribeForeground: (onForeground: () => void) => () => void;\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.subscribeForeground = opts.subscribeForeground;\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 });\n }\n\n // ── Lifecycle ────────────────────────────────────────────────────────────────\n\n /** Flush any queued ingest, refresh config, and (optionally) wire the\n * foreground refresh. Safe to call once early. */\n start(): void {\n if (this.started) return;\n this.started = true;\n void this.api.flush();\n void this.refreshConfig();\n if (this.refreshOnForeground) {\n this.unsubscribeForeground = this.subscribeForeground(() => {\n // Retry ingest queued while offline/backgrounded, then refresh if stale.\n void this.api.flush();\n this.refreshConfigIfStale();\n });\n }\n }\n\n /** Tear down listeners + pending timers. */\n stop(): void {\n this.engine.stop();\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 this.engine.process(name, properties);\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) return;\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 // Impression is finalized at close, so `dismissed` is authoritative.\n this.api.recordImpression({ surveyId, triggerId, endUserId, shownAt, dismissed: result.dismissed });\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 answers: result.answers,\n });\n }\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 /** 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, 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 }) : 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiBA,2BAAyB;AACzB,0BAAmC;;;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;AAAA,EACF;AAAA,EAEQ,MAAM,SAA8B;AAC1C,SAAK,GAAG,QAAQ,KAAK,KAAK,UAAU,OAAO,CAAC;AAAA,EAC9C;AAAA,EAEA,QAAQ,MAAc,MAAoB;AACxC,UAAM,UAAU,KAAK,K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QAAI,wBAAS,KAAK;AAC1C,QAAM,cAAU,sBAAoB,IAAI;AACxC,QAAM,aAAS,sBAA4B,IAAI;AAE/C,+BAAU,MAAM;AACd,QAAI,CAAC,SAAU;AAEf,WAAO,SAAS,eAAe,MAAM,UAAU,SAAS,UAAU,QAAQ,KAAK,IAAI,CAAC;AAAA,EACtF,GAAG,CAAC,UAAU,QAAQ,CAAC;AAEvB,QAAM,eAAe,UAAU,SAAS;AACxC,QAAM,YAAQ,uBAAQ,MAAM,aAAa,cAAc,EAAE,QAAQ,WAAW,CAAC,GAAG,CAAC,cAAc,QAAQ,UAAU,CAAC;AAElH,MAAI,CAAC,YAAY,CAAC,UAAU,OAAQ,QAAO;AAC3C,MAAI,CAAC,QAAQ,QAAS,SAAQ,UAAU,oBAAI,KAAK;AAEjD,SACE;AAAA,IAAC;AAAA;AAAA,MACC,OAAO;AAAA,QACL,EAAE,iBAAiB,MAAM,SAAS,cAAc,MAAM,cAAc,aAAa,GAAG,aAAa,MAAM,QAAQ,UAAU,SAAS;AAAA,QAClI;AAAA,MACF;AAAA,MAEA;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","AsyncStorage","import_react","import_react","import_react_native","import_react","import_react_native","import_react_native","import_react_native","import_react_native","import_jsx_runtime","styles","import_jsx_runtime","SurveyCard","advance","styles","import_jsx_runtime","styles","import_jsx_runtime","import_react","import_react_native","import_jsx_runtime"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../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/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// @microsurveysai/react-native\n//\n// React Native SDK for MicroSurveys. Surveys configured in the dashboard are\n// evaluated on-device against the events you track (or forward from Amplitude)\n// and presented natively as a bottom sheet or dialog.\n//\n// export const ms = new MicroSurveys({ apiKey: \"ms_live_…\" });\n// amplitude.add(ms.amplitudePlugin()); // optional\n//\n// <MicroSurveysProvider instance={ms}>\n// <App />\n// </MicroSurveysProvider>\n//\n// ms.track(\"checkout_completed\", { plan: \"pro\" });\n//\n\nexport { MicroSurveys } from \"./MicroSurveys\";\nexport type { MicroSurveysOptions } from \"./MicroSurveys\";\nexport { MicroSurveysProvider, useMicroSurveys, useMicroSurveysInstance } from \"./provider\";\nexport type { MicroSurveysProviderProps } from \"./provider\";\nexport { MicroSurvey } from \"./MicroSurvey\";\nexport type { MicroSurveyProps } from \"./MicroSurvey\";\nexport { SurveyModal } from \"./ui/SurveyModal\";\nexport type { SurveyModalProps } from \"./ui/SurveyModal\";\nexport { hydrateAsyncStorage } from \"./asyncStorage\";\nexport type { AsyncKeyValueStorage } from \"./asyncStorage\";\nexport type { AmplitudeEvent, MicroSurveysAmplitudePlugin } from \"./amplitude\";\n\n// Re-export the common wire types so consumers don't need a second import.\nexport { parseConfig } from \"./core\";\nexport type {\n Survey,\n Question,\n SurveyResult,\n SurveyAnswer,\n AnswerValue,\n ProjectTheme,\n KeyValueStorage,\n} from \"./core\";\n","//\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\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 });\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}\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\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 questions = (Array.isArray(raw.questions) ? raw.questions : [])\n .map((q) => normalizeQuestion(asObject(q)))\n .filter((q): q is Question => q !== null);\n const triggers = (Array.isArray(raw.triggers) ? raw.triggers : [])\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, surveys };\n}\n","//\n// apiClient.ts\n//\n// `fetch`-based client for the three 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 { 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\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 // ── 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 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. Idempotency keys make re-sends\n * safe. Never throws. */\n async flush(): Promise<void> {\n if (this.isFlushing) return;\n this.isFlushing = true;\n try {\n for (const entry of this.outbox.snapshot()) {\n try {\n await this.post(entry.path, entry.body);\n this.outbox.remove(entry.id);\n } catch {\n break; // network/server problem — retry on the next flush\n }\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 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). */\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 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 } from \"./sampling\";\nimport { newTriggerRecord, endUserIdOf } from \"./types\";\nimport type { TriggerStateStore } from \"./persistence\";\nimport type { Identity, Survey, Trigger, UserTriggerState } from \"./types\";\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}\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 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 }\n\n /** Feed an event into the engine. */\n process(name: string, properties: Record<string, unknown> = {}): void {\n const identity = this.identityProvider();\n const endUserId = endUserIdOf(identity);\n const state = this.store.load(endUserId);\n const nowT = this.now();\n\n for (const survey of this.surveysProvider()) {\n const triggers = survey.triggers;\n if (!triggers || triggers.length === 0) continue;\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)) continue;\n\n for (const trigger of triggers) {\n const satisfied = this.advanceTrigger(trigger, state, name, properties, nowT);\n if (!satisfied) continue;\n\n const occurrence = state.triggers[trigger.id]?.satisfiedCount ?? 0;\n\n // (1) window\n if (!this.isWithinWindow(survey, nowT)) continue;\n // (3) frequency\n if (!passesFrequency(trigger, occurrence)) continue;\n // (4) audience\n if (survey.audienceMatch && !audienceMatches(survey.audienceMatch, identity.userProperties)) continue;\n // (5) sampling (sticky)\n if (!this.passesSampling(survey, endUserId, state)) continue;\n // (6) cap\n if (!passesCap(survey, state, nowT)) continue;\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 isWithinWindow(survey: Survey, nowT: number): boolean {\n if (survey.startsAt) {\n const start = Date.parse(survey.startsAt);\n if (!Number.isNaN(start) && nowT < start / 1000) return false;\n }\n if (survey.endsAt) {\n const end = Date.parse(survey.endsAt);\n if (!Number.isNaN(end) && nowT > end / 1000) return false;\n }\n return true;\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)) return;\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// 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 } 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 { 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\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}\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\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.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 });\n }\n\n // ── Lifecycle ────────────────────────────────────────────────────────────────\n\n /** Flush any queued ingest, refresh config, and (optionally) wire the\n * foreground refresh. Safe to call once early. */\n start(): void {\n if (this.started) return;\n this.started = true;\n void this.api.flush();\n void this.refreshConfig();\n if (this.refreshOnForeground) {\n this.unsubscribeForeground = this.subscribeForeground(() => {\n // Retry ingest queued while offline/backgrounded, then refresh if stale.\n void this.api.flush();\n this.refreshConfigIfStale();\n });\n }\n }\n\n /** Tear down listeners + pending timers. */\n stop(): void {\n this.engine.stop();\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 this.engine.process(name, properties);\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) return;\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiBA,2BAAyB;AACzB,0BAAmC;;;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;AAAA,EACF;AAAA,EAEQ,MAAM,SAA8B;AAC1C,SAAK,GAAG,QAAQ,KAAK,KAAK,UAAU,OAAO,CAAC;AAAA,EAC9C;AAAA,EAEA,QAAQ,MAAc,MAAoB;AACxC,UAAM,UAAU,KAAK,KAAK;AAC1B,YAAQ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U;AAEf,WAAO,SAAS,eAAe,MAAM,UAAU,SAAS,UAAU,QAAQ,KAAK,IAAI,CAAC;AAAA,EACtF,GAAG,CAAC,UAAU,QAAQ,CAAC;AAEvB,QAAM,eAAe,UAAU,SAAS;AACxC,QAAM,YAAQ,uBAAQ,MAAM,aAAa,cAAc,EAAE,QAAQ,WAAW,CAAC,GAAG,CAAC,cAAc,QAAQ,UAAU,CAAC;AAElH,MAAI,CAAC,YAAY,CAAC,UAAU,OAAQ,QAAO;AAC3C,MAAI,CAAC,QAAQ,QAAS,SAAQ,UAAU,oBAAI,KAAK;AAEjD,SACE;AAAA,IAAC;AAAA;AAAA,MACC,OAAO;AAAA,QACL,EAAE,iBAAiB,MAAM,SAAS,cAAc,MAAM,cAAc,aAAa,GAAG,aAAa,MAAM,QAAQ,UAAU,SAAS;AAAA,QAClI;AAAA,MACF;AAAA,MAEA;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","AsyncStorage","import_react","import_react","import_react_native","import_react","import_react_native","import_react_native","import_react_native","import_react_native","import_jsx_runtime","styles","import_jsx_runtime","SurveyCard","advance","styles","import_jsx_runtime","styles","import_jsx_runtime","import_react","import_react_native","import_jsx_runtime"]}
|