@splithub/core 0.6.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-73Y4OWKF.js +929 -0
- package/dist/chunk-73Y4OWKF.js.map +1 -0
- package/dist/index.cjs +253 -136
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +52 -4
- package/dist/index.d.ts +52 -4
- package/dist/index.js +1339 -40
- package/dist/index.js.map +1 -1
- package/dist/{types-0c_5qhVX.d.cts → types-DEEyqr9C.d.cts} +5 -1
- package/dist/{types-0c_5qhVX.d.ts → types-DEEyqr9C.d.ts} +5 -1
- package/dist/vite.cjs +77 -14
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +4 -7
- package/dist/vite.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-BBUR5ZJ4.js +0 -2173
- package/dist/chunk-BBUR5ZJ4.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/redirect.ts"],"sourcesContent":["import { assign, isActive } from './assignment';\nimport { normalizePath, matchPath } from './paths';\nimport type { Assignment, Experiment, SplitHubConfig, TargetingContext } from './types';\n\nexport interface RedirectDecision {\n experiment: string;\n variant: string;\n /** Destination (`to` of the variant) when the visitor must be moved; null when they stay. */\n to: string | null;\n /** Why this variant: `assigned`, `dev` (a draft in development) or `override` (`?sh_force`). */\n reason: Assignment['reason'];\n}\n\n/**\n * Which redirect experiment applies to `pathname`, and where the visitor goes.\n * The first active experiment that matches and assigns a variant wins. Pure:\n * sh.js and the Next.js middleware ask the same question and get the same answer.\n * `explain` hears every assignment it made for a matching experiment (the\n * middleware prints the surprising ones in development).\n */\nexport function decideRedirect(\n config: SplitHubConfig,\n pathname: string,\n visitorId: string,\n context: TargetingContext = {},\n overrides: Record<string, string> = {},\n explain?: (experiment: Experiment, assignment: Assignment) => void\n): RedirectDecision | null {\n for (const exp of config.experiments) {\n if (exp.kind !== 'redirect' || !exp.match || !matchPath(exp.match, pathname)) continue;\n if (!isActive(config, exp, context.now)) {\n explain?.(exp, { experiment: exp.key, variant: null, reason: 'not_running' });\n continue;\n }\n const a = assign(config, exp.key, visitorId, { overrides, context });\n explain?.(exp, a);\n if (!a.variant) continue;\n const to = a.variant.to || null;\n const stays = !to || normalizePath(to.split(/[?#]/)[0] ?? '') === normalizePath(pathname);\n return { experiment: exp.key, variant: a.variant.key, to: stays ? null : to, reason: a.reason };\n }\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBO,SAAS,eACd,QACA,UACA,WACA,UAA4B,CAAC,GAC7B,YAAoC,CAAC,GACrC,SACyB;AACzB,aAAW,OAAO,OAAO,aAAa;AACpC,QAAI,IAAI,SAAS,cAAc,CAAC,IAAI,SAAS,CAAC,UAAU,IAAI,OAAO,QAAQ,EAAG;AAC9E,QAAI,CAAC,SAAS,QAAQ,KAAK,QAAQ,GAAG,GAAG;AACvC,gBAAU,KAAK,EAAE,YAAY,IAAI,KAAK,SAAS,MAAM,QAAQ,cAAc,CAAC;AAC5E;AAAA,IACF;AACA,UAAM,IAAI,OAAO,QAAQ,IAAI,KAAK,WAAW,EAAE,WAAW,QAAQ,CAAC;AACnE,cAAU,KAAK,CAAC;AAChB,QAAI,CAAC,EAAE,QAAS;AAChB,UAAM,KAAK,EAAE,QAAQ,MAAM;AAC3B,UAAM,QAAQ,CAAC,MAAM,cAAc,GAAG,MAAM,MAAM,EAAE,CAAC,KAAK,EAAE,MAAM,cAAc,QAAQ;AACxF,WAAO,EAAE,YAAY,IAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,IAAI,QAAQ,OAAO,IAAI,QAAQ,EAAE,OAAO;AAAA,EAChG;AACA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/assignment.ts","../src/dev.ts","../src/shared.ts","../src/ids.ts","../src/paths.ts","../src/visitor.ts","../src/redirect.ts","../src/events.ts","../src/debug.ts","../src/client.ts"],"sourcesContent":["import { HOLDOUT_KEY, LAYER_BUCKETS } from './config';\nimport { hashToUnit } from './hash';\nimport { runFlow } from './targeting';\nimport type { Assignment, Experiment, SplitHubConfig, TargetingContext, Variant } from './types';\n\n// Module-scoped so it compiles without node types and still shadows nothing at runtime.\ndeclare const process: { env: Record<string, string | undefined> };\n\n/**\n * True in `next dev` / `vite` and on the server of a dev build. Bundlers\n * replace `process.env.NODE_ENV` with a literal, so the expression is kept\n * verbatim; where nothing replaces it and no `process` exists, it is false.\n */\nexport function isDevEnvironment(): boolean {\n try {\n return process.env.NODE_ENV === 'development';\n } catch {\n return false;\n }\n}\n\n/** A draft shown in development because the config says `runDraftsInDev: true`. */\nexport function isDevDraft(config: Pick<SplitHubConfig, 'runDraftsInDev'>, experiment: Pick<Experiment, 'status'>): boolean {\n return experiment.status === 'draft' && config.runDraftsInDev && isDevEnvironment();\n}\n\n/** Running now, or a draft served in development. What the middleware and the drop-in script check before assigning. */\nexport function isActive(config: Pick<SplitHubConfig, 'runDraftsInDev'>, experiment: Pick<Experiment, 'status' | 'schedule'>, now?: number): boolean {\n return (experiment.status === 'running' && inSchedule(experiment, now)) || isDevDraft(config, experiment);\n}\n\n/**\n * Deterministic bucketing. Same visitor + same experiment + same seed always\n * yields the same variant, on any runtime, with no network call.\n *\n * Two independent hashes are used so that changing `traffic` does not\n * reshuffle variants of visitors already inside the experiment.\n */\nexport function pickVariant(experiment: Experiment, visitorId: string): Variant | null {\n const trafficUnit = hashToUnit(`${experiment.seed}:${experiment.key}:traffic:${visitorId}`);\n if (trafficUnit >= experiment.traffic) return null;\n\n const unit = hashToUnit(`${experiment.seed}:${experiment.key}:variant:${visitorId}`);\n let cumulative = 0;\n for (const variant of experiment.variants) {\n cumulative += variant.weight;\n if (unit < cumulative) return variant;\n }\n // Floating point rounding: fall back to the last variant.\n return experiment.variants[experiment.variants.length - 1] ?? null;\n}\n\n/**\n * Holdout group of a visitor: `holdout` (sees the control everywhere, sends no\n * exposures but the `__holdout` marker) or `enrolled`. Null without a holdout.\n * One hash per visitor and project, independent of every experiment's seed.\n */\nexport function holdoutGroup(config: Pick<SplitHubConfig, 'holdout'>, visitorId: string): 'holdout' | 'enrolled' | null {\n const h = config.holdout;\n if (!h || !(h.percent > 0)) return null;\n return hashToUnit(`${h.seed}:${HOLDOUT_KEY}:${visitorId}`) < h.percent / 100 ? 'holdout' : 'enrolled';\n}\n\n/** The visitor's bucket 0..99 in a layer: the same in every experiment of the layer. */\nexport function layerBucket(config: Pick<SplitHubConfig, 'layers'>, layerKey: string, visitorId: string): number {\n const seed = config.layers?.[layerKey]?.seed ?? layerKey;\n return Math.min(LAYER_BUCKETS - 1, Math.floor(hashToUnit(`${seed}:layer:${layerKey}:${visitorId}`) * LAYER_BUCKETS));\n}\n\n/** True when the experiment has no layer or the visitor's bucket is inside its range. */\nexport function inLayer(config: Pick<SplitHubConfig, 'layers'>, experiment: Pick<Experiment, 'layer'>, visitorId: string): boolean {\n const l = experiment.layer;\n if (!l) return true;\n const b = layerBucket(config, l.key, visitorId);\n return b >= l.range[0] && b < l.range[1];\n}\n\n/**\n * Whether an assignment puts the visitor in the holdout comparison: they reached a\n * running experiment (in or out of its traffic, layer or targeting), so holdout and\n * enrolled visitors are counted by the same rule. Overrides, bots and tests that are\n * not running do not count.\n */\nexport function countsForHoldout(a: Pick<Assignment, 'reason'>): boolean {\n return a.reason === 'assigned' || a.reason === 'holdout' || a.reason === 'outside_traffic' || a.reason === 'targeting' || a.reason === 'layer';\n}\n\nexport interface AssignOptions {\n /** Force a variant (QA, `?sh_force=hero-cta:bold`). */\n overrides?: Record<string, string>;\n /** Visitor context for targeting flows (country, device, UTM ...). */\n context?: TargetingContext;\n}\n\nexport function assign(\n config: SplitHubConfig,\n experimentKey: string,\n visitorId: string,\n options: AssignOptions = {}\n): Assignment {\n const experiment = config.experiments.find((e) => e.key === experimentKey);\n if (!experiment) return { experiment: experimentKey, variant: null, reason: 'unknown_experiment' };\n\n const forced = options.overrides?.[experimentKey];\n if (forced) {\n // A typo in a preview link (`?sh_force=hero:a` with no variant `a`) is still a preview:\n // it shows the control and is never counted as a visit.\n const variant = experiment.variants.find((v) => v.key === forced) ?? controlVariant(experiment);\n return { experiment: experimentKey, variant, reason: 'override' };\n }\n\n // Crawlers and headless browsers see the control and are never counted: the SDK, sh.js and\n // the middleware all pass the user agent's device, so they agree.\n if (options.context?.device === 'bot') return { experiment: experimentKey, variant: null, reason: 'bot' };\n\n const devDraft = isDevDraft(config, experiment);\n if (!devDraft && (experiment.status !== 'running' || !inSchedule(experiment, options.context?.now))) {\n return { experiment: experimentKey, variant: null, reason: 'not_running' };\n }\n // Holdout and layers come before traffic and targeting: they decide who may enter at all.\n if (holdoutGroup(config, visitorId) === 'holdout') return { experiment: experimentKey, variant: null, reason: 'holdout' };\n if (!inLayer(config, experiment, visitorId)) return { experiment: experimentKey, variant: null, reason: 'layer' };\n // A draft in development is served exactly like a running test; only the reason differs, so the debug panel can say why.\n const reason = devDraft ? 'dev' : 'assigned';\n if (experiment.flow) {\n const trafficUnit = hashToUnit(`${experiment.seed}:${experiment.key}:traffic:${visitorId}`);\n if (trafficUnit >= experiment.traffic) return { experiment: experimentKey, variant: null, reason: 'outside_traffic' };\n const outcome = runFlow(experiment, experiment.flow, visitorId, options.context ?? {});\n return outcome.variant ? { experiment: experimentKey, variant: outcome.variant, reason } : { experiment: experimentKey, variant: null, reason: 'targeting' };\n }\n const variant = pickVariant(experiment, visitorId);\n if (!variant) return { experiment: experimentKey, variant: null, reason: 'outside_traffic' };\n return { experiment: experimentKey, variant, reason };\n}\n\n/** True when the experiment has no run window or `now` is inside it. */\nexport function inSchedule(experiment: Pick<Experiment, 'schedule'>, now = Date.now()): boolean {\n const s = experiment.schedule;\n if (!s) return true;\n if (s.startAt && now < Date.parse(s.startAt)) return false;\n if (s.endAt && now > Date.parse(s.endAt)) return false;\n return true;\n}\n\n/** Control is always the first declared variant. */\nexport function controlVariant(experiment: Experiment): Variant {\n return experiment.variants[0]!;\n}\n\n/** Parse `?sh_force=hero-cta:bold,pricing-title:urgency` into overrides. */\nexport function parseForceParam(search: string): Record<string, string> {\n const out: Record<string, string> = {};\n const match = /[?&]sh_force=([^&]+)/.exec(search);\n if (!match || !match[1]) return out;\n let raw: string;\n try {\n raw = decodeURIComponent(match[1]);\n } catch {\n // A malformed escape (`%E0%A4`) must not break rendering: ignore the parameter.\n return out;\n }\n for (const pair of raw.split(',')) {\n const [exp, variant] = pair.split(':');\n if (exp && variant) out[exp] = variant;\n }\n return out;\n}\n","// Plain-language notes for the developer, printed only in development\n// (NODE_ENV=development): in the browser console for Vite apps, in the terminal\n// for server code (Next.js middleware and Server Components). One line per\n// experiment and situation, so a draft that \"does nothing\" explains itself\n// without ?sh_debug. Production builds never print them.\n\nimport { isDevEnvironment } from './assignment';\nimport type { Assignment, Experiment } from './types';\n\nconst said = new Set<string>();\n\n/** Print `message` once per `key` for this page or server process, in development only. */\nexport function devNote(key: string, message: string): void {\n if (!isDevEnvironment() || said.has(key)) return;\n said.add(key);\n // With the Vite plugin (@splithub/core/vite) the note goes to the dev server's terminal instead of the browser console.\n const w = typeof window !== 'undefined' ? (window as unknown as { __splithubTerminal?: boolean }) : null;\n if (w && typeof CustomEvent === 'function') window.dispatchEvent(new CustomEvent('splithub:dev', { detail: message }));\n if (w?.__splithubTerminal) return;\n if (typeof console !== 'undefined') console.info(`[splithub] ${message}`);\n}\n\n/** Forget what was printed (tests). */\nexport function resetDevNotes(): void {\n said.clear();\n}\n\nfunction others(experiment: Experiment, shown: string | undefined): string {\n return experiment.variants.map((v) => v.key).filter((k) => k !== shown).join('|');\n}\n\n/** Explain an assignment that may surprise a developer: a draft, a paused test, a test outside its dates. */\nexport function explainAssignment(experiment: Experiment | undefined, a: Assignment): void {\n if (!experiment || !isDevEnvironment()) return;\n const key = experiment.key;\n if (a.reason === 'dev') {\n const shown = a.variant?.key;\n devNote(`${key}:dev`, `\"${key}\" is a draft. You see it here because runDraftsInDev is on; this visitor gets \"${shown}\", try ?sh_force=${key}:${others(experiment, shown)} for the others. Visitors see it only after you start it: npx splithub start ${key}`);\n return;\n }\n if (a.reason === 'holdout') {\n devNote('holdout', `This visitor is in the holdout, so every experiment shows its control. Open ?sh_force=${key}:${experiment.variants[1]?.key ?? 'variant'} to see a variant.`);\n return;\n }\n if (a.reason === 'layer') {\n devNote(`${key}:layer`, `\"${key}\" shares layer \"${experiment.layer?.key}\" with other experiments and this visitor's bucket belongs to another one, so they see the control.`);\n return;\n }\n if (a.reason !== 'not_running') return;\n const second = experiment.variants[1]?.key ?? 'variant';\n if (experiment.status === 'draft') {\n devNote(`${key}:draft`, `\"${key}\" is a draft, so everyone sees the control. To see it while you develop, add runDraftsInDev: true to splithub.config.ts, or open ?sh_force=${key}:${second}.`);\n } else if (experiment.status === 'running') {\n devNote(`${key}:schedule`, `\"${key}\" is outside its schedule, so everyone sees the control. Open ?sh_force=${key}:${second} to see a variant.`);\n } else {\n devNote(`${key}:${experiment.status}`, `\"${key}\" is ${experiment.status}, so everyone sees the control.`);\n }\n}\n","// One page may run two SplitHub clients: sh.js and the SDK, or two providers. Both may name\n// the same analytics property, and both would send every pageview, time on page and identify.\n// The first client to collect a property for an endpoint owns it; the other skips page\n// collection (its track() calls still go out, one row each). The registry sits on a global\n// symbol so separate bundles (sh.js and the app's SDK) see the same one.\n\nconst REGISTRY = Symbol.for('splithub.analytics');\n\ntype Registry = Map<string, object>;\n\nfunction registry(): Registry | null {\n if (typeof window === 'undefined') return null;\n const g = globalThis as unknown as Record<symbol, Registry | undefined>;\n return (g[REGISTRY] ??= new Map());\n}\n\n/** True when `owner` collects `key` (endpoint + property) on this page: the first to ask, or the one that already does. */\nexport function claimAnalytics(key: string, owner: object): boolean {\n const r = registry();\n if (!r) return true;\n const held = r.get(key);\n if (held && held !== owner) return false;\n r.set(key, owner);\n return true;\n}\n\n/** Lets another client collect `key` (the owner was destroyed). */\nexport function releaseAnalytics(key: string, owner: object): void {\n const r = registry();\n if (r?.get(key) === owner) r.delete(key);\n}\n\n/** Forget every claim (tests). */\nexport function resetAnalyticsClaims(): void {\n registry()?.clear();\n}\n","const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';\n\nfunction randomBytes(n: number): Uint8Array {\n const out = new Uint8Array(n);\n const c = typeof globalThis.crypto !== 'undefined' ? globalThis.crypto : undefined;\n if (c && typeof c.getRandomValues === 'function') {\n c.getRandomValues(out);\n } else {\n for (let i = 0; i < n; i++) out[i] = Math.floor(Math.random() * 256);\n }\n return out;\n}\n\n/** Short, URL-safe, time-prefixed id: sortable like a ULID, 20 chars. */\nexport function newId(prefix = ''): string {\n const time = Date.now().toString(36).padStart(9, '0');\n const bytes = randomBytes(11);\n let rand = '';\n for (let i = 0; i < bytes.length; i++) rand += ALPHABET[bytes[i]! % 36];\n return `${prefix}${time}${rand}`;\n}\n\nexport function newVisitorId(): string {\n return newId('v_');\n}\n\nexport function newSessionId(): string {\n return newId('s_');\n}\n","// One path rule for pageview goals, redirect experiments in sh.js and the Next.js middleware,\n// so a test that matches in one place matches in all of them.\n\n/** `/pricing/` → `/pricing`; the root stays `/`. */\nexport function normalizePath(path: string): string {\n return path.length > 1 && path.endsWith('/') ? path.replace(/\\/+$/, '') || '/' : path;\n}\n\n/**\n * `pattern` is an exact path (a trailing slash on either side is ignored) or a\n * prefix ending with `*` (`/blog/*` matches `/blog/a/b`).\n */\nexport function matchPath(pattern: string, pathname: string): boolean {\n if (pattern.endsWith('*')) return pathname.startsWith(pattern.slice(0, -1));\n return normalizePath(pattern) === normalizePath(pathname);\n}\n\n/**\n * Where a redirect variant sends the visitor: `to` resolved against the current\n * URL, with the current query merged in (the variant's own parameters win, so\n * `?utm_source` survives) and the current hash kept unless `to` has one.\n */\nexport function redirectTarget(to: string, currentHref: string): URL {\n const current = new URL(currentHref);\n const target = new URL(to, current);\n const own = new Set(target.searchParams.keys());\n current.searchParams.forEach((value, key) => {\n if (!own.has(key)) target.searchParams.append(key, value);\n });\n if (!target.hash) target.hash = current.hash;\n return target;\n}\n\n/**\n * Where a visit came from, as an exposure carries it: the referrer's origin only (never its path\n * or query), `''` for a visit with no referrer (direct), and `undefined` when it says nothing\n * about the source: a link from the same site, or a value that is not a URL.\n */\nexport function referrerOrigin(referrer: string | null | undefined, siteHost: string | null | undefined): string | undefined {\n if (!referrer) return '';\n let url: URL;\n try {\n url = new URL(referrer);\n } catch {\n return undefined;\n }\n const host = url.hostname.toLowerCase().replace(/^www\\./, '');\n const site = (siteHost ?? '').toLowerCase().replace(/:\\d+$/, '').replace(/^www\\./, '');\n if (!host || host === site) return undefined;\n // `android-app://com.google.android.gm` has no web origin; protocol + host keeps the app's name.\n return `${url.protocol}//${url.host}`.slice(0, 300);\n}\n","import { newSessionId, newVisitorId } from './ids';\nimport { referrerOrigin } from './paths';\nimport { safeGet, safeSet, type KeyValueStorage } from './platform';\n\nconst ONE_YEAR = 60 * 60 * 24 * 365;\n\n/** A web page. React Native has a `window` but no page (and `navigator.product` says so). */\nexport const isBrowser = (): boolean => typeof window !== 'undefined' && typeof document !== 'undefined' && !isReactNative();\n\n/** React Native (Hermes or JSC): a `window` and a `navigator`, but no page. */\nexport const isReactNative = (): boolean => typeof navigator !== 'undefined' && navigator.product === 'ReactNative';\n\n/** An id kept in an app's storage, made on first use. */\nexport function getOrCreateStoredId(storage: KeyValueStorage | null | undefined, key: string, make: () => string): string {\n const existing = safeGet(storage, key);\n if (existing) return existing;\n const id = make();\n safeSet(storage, key, id);\n return id;\n}\n\nfunction readCookie(name: string): string | null {\n if (!isBrowser()) return null;\n const match = document.cookie.split('; ').find((c) => c.startsWith(`${name}=`));\n return match ? decodeURIComponent(match.slice(name.length + 1)) : null;\n}\n\nfunction writeCookie(name: string, value: string): void {\n if (!isBrowser()) return;\n const secure = location.protocol === 'https:' ? '; Secure' : '';\n document.cookie = `${name}=${encodeURIComponent(value)}; Max-Age=${ONE_YEAR}; Path=/; SameSite=Lax${secure}`;\n}\n\nfunction safeStorage(kind: 'localStorage' | 'sessionStorage'): Storage | null {\n try {\n if (!isBrowser()) return null;\n const s = window[kind];\n const probe = '__sh_probe__';\n s.setItem(probe, '1');\n s.removeItem(probe);\n return s;\n } catch {\n return null;\n }\n}\n\n/**\n * Visitor id lookup order: cookie → localStorage → new. The value is written\n * to both so that SSR (cookie) and SPA (localStorage) agree.\n */\n/** True when a visitor id already exists (cookie or localStorage). */\nexport function hasVisitorId(key: string): boolean {\n return Boolean(readCookie(key) ?? safeStorage('localStorage')?.getItem(key));\n}\n\nexport function getOrCreateVisitorId(key: string): string {\n const fromCookie = readCookie(key);\n const ls = safeStorage('localStorage');\n const fromStorage = ls?.getItem(key) ?? null;\n const id = fromCookie ?? fromStorage ?? newVisitorId();\n if (fromCookie !== id) writeCookie(key, id);\n if (fromStorage !== id) ls?.setItem(key, id);\n return id;\n}\n\nexport function getOrCreateSessionId(key = 'sh_sid'): string {\n const ss = safeStorage('sessionStorage');\n const existing = ss?.getItem(key);\n if (existing) return existing;\n const id = newSessionId();\n ss?.setItem(key, id);\n return id;\n}\n\n/** Session-scoped exposure dedup so a reload does not re-send exposures. */\nexport function sessionExposureSet(key = 'sh_exposed'): Set<string> {\n const ss = safeStorage('sessionStorage');\n try {\n const raw = ss?.getItem(key);\n return new Set(raw ? (JSON.parse(raw) as string[]) : []);\n } catch {\n return new Set();\n }\n}\n\nexport function persistExposureSet(set: Set<string>, key = 'sh_exposed'): void {\n safeStorage('sessionStorage')?.setItem(key, JSON.stringify([...set]));\n}\n\n/** Reads a value from browser storage; null when absent or storage is blocked. */\nexport function readStored(kind: 'localStorage' | 'sessionStorage', key: string): string | null {\n try {\n return safeStorage(kind)?.getItem(key) ?? null;\n } catch {\n return null;\n }\n}\n\n/** Writes (or, with null, removes) a value in browser storage; silent when storage is blocked. */\nexport function writeStored(kind: 'localStorage' | 'sessionStorage', key: string, value: string | null): void {\n try {\n const s = safeStorage(kind);\n if (value === null) s?.removeItem(key);\n else s?.setItem(key, value);\n } catch {\n // storage blocked\n }\n}\n\n/**\n * The referrer the visit (this tab's session) began with, as `referrerOrigin` reads it, kept in\n * sessionStorage so a later page of the same visit still knows it. `undefined` when the first page\n * we saw was reached from the same site (the SDK is not on the landing page) or storage is blocked\n * and this page came from the site itself.\n */\nexport function sessionReferrer(key = 'sh_ref'): string | undefined {\n if (!isBrowser()) return undefined;\n const stored = readStored('sessionStorage', key);\n if (stored !== null) return stored;\n const ref = referrerOrigin(document.referrer, location.host);\n if (ref !== undefined) writeStored('sessionStorage', key, ref);\n return ref;\n}\n","import { assign, isActive } from './assignment';\nimport { normalizePath, matchPath } from './paths';\nimport type { Assignment, Experiment, SplitHubConfig, TargetingContext } from './types';\n\nexport interface RedirectDecision {\n experiment: string;\n variant: string;\n /** Destination (`to` of the variant) when the visitor must be moved; null when they stay. */\n to: string | null;\n /** Why this variant: `assigned`, `dev` (a draft in development) or `override` (`?sh_force`). */\n reason: Assignment['reason'];\n}\n\n/**\n * Which redirect experiment applies to `pathname`, and where the visitor goes.\n * The first active experiment that matches and assigns a variant wins. Pure:\n * sh.js and the Next.js middleware ask the same question and get the same answer.\n * `explain` hears every assignment it made for a matching experiment (the\n * middleware prints the surprising ones in development).\n */\nexport function decideRedirect(\n config: SplitHubConfig,\n pathname: string,\n visitorId: string,\n context: TargetingContext = {},\n overrides: Record<string, string> = {},\n explain?: (experiment: Experiment, assignment: Assignment) => void\n): RedirectDecision | null {\n for (const exp of config.experiments) {\n if (exp.kind !== 'redirect' || !exp.match || !matchPath(exp.match, pathname)) continue;\n if (!isActive(config, exp, context.now)) {\n explain?.(exp, { experiment: exp.key, variant: null, reason: 'not_running' });\n continue;\n }\n const a = assign(config, exp.key, visitorId, { overrides, context });\n explain?.(exp, a);\n if (!a.variant) continue;\n const to = a.variant.to || null;\n const stays = !to || normalizePath(to.split(/[?#]/)[0] ?? '') === normalizePath(pathname);\n return { experiment: exp.key, variant: a.variant.key, to: stays ? null : to, reason: a.reason };\n }\n return null;\n}\n","import { safeGet, safeSet, type KeyValueStorage } from './platform';\nimport type { AppInfo, EventBatch, SplitHubEvent } from './types';\nimport { isBrowser } from './visitor';\n\n/** What a transport throws when the ingest answers with an error status. */\nexport interface IngestError extends Error {\n status?: number;\n /** Seconds, from the `Retry-After` header. */\n retryAfter?: number;\n /** The body's `code` on a 429 (`quota_exceeded`, `deleted`, …). */\n code?: string;\n}\n\nexport interface Transport {\n send(batch: EventBatch, options: { beacon: boolean }): Promise<void> | void;\n}\n\nexport interface TransportOptions {\n endpoint: string;\n /** Sent as `Authorization: Bearer` (cloud public key). */\n key?: string;\n /**\n * Send the key as `?key=` so page-hide batches can use `navigator.sendBeacon`, which\n * cannot set headers. Only for endpoints that accept it; otherwise keyed batches use\n * `fetch(..., { keepalive: true })` on page hide, which also outlives the page.\n */\n keyInQuery?: boolean;\n /** `fetch(..., { keepalive })`; default true. Apps pass false: there is no page to outlive. */\n keepalive?: boolean;\n /** Tried in order when `endpoint` cannot be reached (a network error, not an error status). */\n fallbacks?: string[];\n /** Called once a fallback answers; later batches go there first. */\n onEndpoint?: (endpoint: string) => void;\n}\n\nfunction beaconUrl(options: TransportOptions, endpoint: string): string | null {\n if (!options.key) return endpoint;\n if (!options.keyInQuery) return null;\n return `${endpoint}${endpoint.includes('?') ? '&' : '?'}key=${encodeURIComponent(options.key)}`;\n}\n\n/** Default transport: fetch with keepalive; sendBeacon on page hide when the endpoint allows it. */\nexport function createFetchTransport(options: TransportOptions): Transport {\n const endpoints = [options.endpoint, ...(options.fallbacks ?? []).filter((e) => e !== options.endpoint)];\n let active = 0;\n return {\n async send(batch, { beacon }) {\n const body = JSON.stringify(batch);\n const url = beacon && isBrowser() && typeof navigator.sendBeacon === 'function' ? beaconUrl(options, endpoints[active]!) : null;\n if (url) {\n // A JSON content type is not CORS-safelisted, so a cross-origin beacon goes as text;\n // both ingest handlers parse the body whatever its type.\n let sameOrigin = false;\n try {\n sameOrigin = new URL(url, location.href).origin === location.origin;\n } catch {\n // relative or malformed: let fetch decide below\n }\n const blob = new Blob([body], { type: sameOrigin ? 'application/json' : 'text/plain;charset=UTF-8' });\n try {\n if (navigator.sendBeacon(url, blob)) return;\n } catch {\n // fall through to fetch\n }\n }\n const headers: Record<string, string> = { 'content-type': 'application/json' };\n if (options.key) headers.authorization = `Bearer ${options.key}`;\n // Only a network failure moves on: an error status means the address works.\n let res: Response | null = null;\n let failure: unknown;\n for (let i = 0; i < endpoints.length && !res; i++) {\n const at = (active + i) % endpoints.length;\n try {\n res = await fetch(endpoints[at]!, { method: 'POST', headers, body, ...(options.keepalive === false ? {} : { keepalive: true }) });\n } catch (e) {\n failure = e;\n continue;\n }\n if (at !== active) {\n active = at;\n options.onEndpoint?.(endpoints[at]!);\n }\n }\n if (!res) throw failure;\n if (!res.ok) {\n const error = new Error(`[splithub] ingest responded ${res.status}`) as IngestError;\n error.status = res.status;\n const retryAfter = Number(res.headers?.get?.('retry-after'));\n if (Number.isFinite(retryAfter) && retryAfter > 0) error.retryAfter = retryAfter;\n if (res.status === 429) {\n try {\n const code = ((await res.json()) as { code?: unknown } | null)?.code;\n if (typeof code === 'string') error.code = code;\n } catch {\n // no JSON body\n }\n }\n throw error;\n }\n },\n };\n}\n\nexport interface EventQueueOptions {\n project: string;\n sdk: string;\n transport: Transport;\n /** Flush when this many events are pending. Default 20. */\n maxBatch?: number;\n /** Flush at least this often (ms). Default 2000. */\n flushInterval?: number;\n /** Events kept while the endpoint is unreachable; the oldest go first. Default 200, 1000 with `storage`. */\n maxQueue?: number;\n /**\n * Attempts per event before it is dropped. Default 5. With `storage`, network failures and\n * 5xx / 408 never use up attempts; a 429 always does (the project is throttled, over quota or gone).\n */\n maxAttempts?: number;\n /**\n * Apps: unsent events are kept here (key `sh_queue`), so they survive a restart and an offline\n * stretch; network failures and 5xx / 408 back off up to 60 s. Queues sharing one storage share\n * `sh_queue`: only the first restores it, and each write carries every live queue's events.\n */\n storage?: KeyValueStorage;\n /** Sent with every batch (apps). */\n app?: AppInfo;\n onError?: (error: unknown) => void;\n}\n\n// sh.js (LITE) never has app storage: the offline queue's code drops out of it (see client.ts).\ndeclare const __SPLITHUB_LITE__: true | undefined;\n\nconst MAX_BACKOFF_MS = 30_000;\nconst MAX_OFFLINE_BACKOFF_MS = 60_000;\n/** The ingest takes at most 500 events per batch; a restored offline queue goes out in slices. */\nconst MAX_SEND = 500;\nexport const QUEUE_STORAGE_KEY = 'sh_queue';\n\n/** A 429 for a project over quota or deleted: nothing will change soon, so wait an hour. */\nconst LONG_BACKOFF_MS = 3_600_000;\nconst LONG_BACKOFF_CODES = new Set(['quota_exceeded', 'quota', 'deleted']);\n/** Upper bound for a server's Retry-After. */\nconst MAX_RETRY_AFTER_MS = 86_400_000;\n\n/**\n * Queues per storage, across copies of this module (Symbol.for), so two clients on one storage\n * (React StrictMode, two providers) neither send the saved events twice nor overwrite each other's.\n */\nfunction queuesOf(storage: KeyValueStorage): Set<EventQueue> {\n const g = globalThis as { [k: symbol]: WeakMap<KeyValueStorage, Set<EventQueue>> | undefined };\n const key = Symbol.for('splithub.queues');\n const map = (g[key] ??= new WeakMap());\n let set = map.get(storage);\n if (!set) map.set(storage, (set = new Set()));\n return set;\n}\n\n/** Events a previous launch could not send, newest `max` of them. */\nfunction restoreQueue(storage: KeyValueStorage, max: number): SplitHubEvent[] {\n try {\n const raw = safeGet(storage, QUEUE_STORAGE_KEY);\n const saved = raw ? (JSON.parse(raw) as unknown) : null;\n return Array.isArray(saved) ? saved.filter((e): e is SplitHubEvent => Boolean(e) && typeof e === 'object' && typeof (e as SplitHubEvent).type === 'string').slice(-max) : [];\n } catch {\n return [];\n }\n}\n\n/**\n * Batches events and sends them on a timer, when a batch is full, and when the page is\n * hidden (sendBeacon / keepalive). A failed batch is retried with exponential backoff and\n * jitter, up to `maxAttempts`; a 4xx other than 408/429 is a refusal and is not retried.\n * At most `maxQueue` events wait in memory. Page listeners are bound on the first event\n * and removed by `destroy()`, so a client created and thrown away (React StrictMode) leaks nothing.\n */\nexport class EventQueue {\n private pending: SplitHubEvent[] = [];\n private retry: SplitHubEvent[] = [];\n /** Batches on their way: still persisted until the transport says they arrived. */\n private readonly inflight = new Set<SplitHubEvent[]>();\n private attempts = 0;\n /** 429s in a row: they drop the batch after `maxAttempts`, storage or not. */\n private throttled = 0;\n private destroyed = false;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private backoffUntil = 0;\n private readonly maxBatch: number;\n private readonly flushInterval: number;\n private readonly maxQueue: number;\n private readonly maxAttempts: number;\n private unbind: (() => void) | null = null;\n\n constructor(private readonly options: EventQueueOptions) {\n this.maxBatch = options.maxBatch ?? 20;\n this.flushInterval = options.flushInterval ?? 2000;\n this.maxQueue = options.maxQueue ?? (options.storage ? 1000 : 200);\n this.maxAttempts = options.maxAttempts ?? 5;\n // Events a previous launch could not send go out first. Only the first queue on a storage\n // claims them; a later one adopts what destroyed queues left (StrictMode's thrown-away client).\n if (typeof __SPLITHUB_LITE__ === 'undefined' && options.storage) {\n const peers = queuesOf(options.storage);\n if (peers.size === 0) {\n this.pending = restoreQueue(options.storage, this.maxQueue);\n } else {\n for (const peer of peers) {\n if (!peer.destroyed) continue;\n this.pending.push(...peer.release());\n if (peer.inflight.size === 0) peers.delete(peer);\n }\n this.pending = this.pending.slice(-this.maxQueue);\n }\n peers.add(this);\n this.persist();\n if (this.pending.length) this.schedule(0);\n }\n }\n\n /** Hands over the events waiting here (not those on their way) to a queue that adopts them. */\n private release(): SplitHubEvent[] {\n const out = [...this.retry, ...this.pending];\n this.retry = [];\n this.pending = [];\n return out;\n }\n\n private persist(): void {\n if (!(typeof __SPLITHUB_LITE__ === 'undefined') || !this.options.storage) return;\n const queues = new Set(queuesOf(this.options.storage)).add(this);\n const all = [...queues].flatMap((q) => [...[...q.inflight].flat(), ...q.retry, ...q.pending]).slice(-this.maxQueue);\n safeSet(this.options.storage, QUEUE_STORAGE_KEY, all.length ? JSON.stringify(all) : null);\n }\n\n private bind(): void {\n if (this.unbind || !isBrowser()) return;\n const onHidden = () => {\n if (document.visibilityState === 'hidden') void this.flush(true);\n };\n const onPageHide = () => void this.flush(true);\n document.addEventListener('visibilitychange', onHidden);\n window.addEventListener('pagehide', onPageHide);\n this.unbind = () => {\n document.removeEventListener('visibilitychange', onHidden);\n window.removeEventListener('pagehide', onPageHide);\n };\n }\n\n private schedule(delay: number): void {\n if (this.timer) return;\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.flush(false);\n }, delay);\n }\n\n push(event: SplitHubEvent): void {\n this.bind();\n if (this.destroyed) {\n this.destroyed = false;\n if (typeof __SPLITHUB_LITE__ === 'undefined' && this.options.storage) queuesOf(this.options.storage).add(this);\n }\n this.pending.push(event);\n const overflow = this.size - this.maxQueue;\n if (overflow > 0) {\n const fromRetry = Math.min(overflow, this.retry.length);\n this.retry.splice(0, fromRetry);\n this.pending.splice(0, overflow - fromRetry);\n }\n this.persist();\n const waiting = Date.now() < this.backoffUntil;\n if (!waiting && this.pending.length >= this.maxBatch) {\n void this.flush(false);\n return;\n }\n this.schedule(waiting ? this.backoffUntil - Date.now() : this.flushInterval);\n }\n\n get size(): number {\n return this.pending.length + this.retry.length;\n }\n\n /** Send everything now. `beacon` is for page hide: it ignores the backoff, since the page is going away. */\n async flush(beacon = false): Promise<void> {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n const all = [...this.retry, ...this.pending];\n const events = all.slice(0, MAX_SEND);\n this.retry = all.slice(MAX_SEND);\n this.pending = [];\n if (events.length === 0) return;\n const offline = typeof __SPLITHUB_LITE__ === 'undefined' && Boolean(this.options.storage);\n const batch: EventBatch = { project: this.options.project, sdk: this.options.sdk, events, ...(this.options.app ? { app: this.options.app } : {}) };\n this.inflight.add(events);\n try {\n await this.options.transport.send(batch, { beacon });\n this.inflight.delete(events);\n this.attempts = 0;\n this.throttled = 0;\n this.backoffUntil = 0;\n this.persist();\n if (this.retry.length) this.schedule(0);\n } catch (error) {\n this.inflight.delete(events);\n const { status, retryAfter, code } = error as IngestError;\n // 4xx is a refusal (bad key, origin not allowed, invalid batch): retrying cannot help.\n const refused = status !== undefined && status >= 400 && status < 500 && status !== 408 && status !== 429;\n // 429: throttled, over quota or deleted. It may pass later, but never forever, even with storage.\n const throttled = status === 429;\n this.attempts += 1;\n if (throttled) this.throttled += 1;\n // An app offline for a day keeps its events: with storage a network failure or 5xx never drops them.\n const keep = !refused && (throttled ? this.throttled < this.maxAttempts : true) && (offline || this.attempts < this.maxAttempts);\n if (keep) {\n this.retry = [...events, ...this.retry, ...this.pending].slice(-this.maxQueue);\n this.pending = [];\n const base = Math.min(offline ? MAX_OFFLINE_BACKOFF_MS : MAX_BACKOFF_MS, 1000 * 2 ** (Math.min(this.attempts, 20) - 1));\n let delay = Math.round(base / 2 + Math.random() * (base / 2));\n if (retryAfter) delay = Math.max(delay, Math.min(MAX_RETRY_AFTER_MS, retryAfter * 1000));\n if (throttled && code && LONG_BACKOFF_CODES.has(code)) delay = Math.max(delay, LONG_BACKOFF_MS);\n this.backoffUntil = Date.now() + delay;\n this.schedule(delay);\n } else {\n this.attempts = 0;\n this.throttled = 0;\n this.backoffUntil = 0;\n }\n this.persist();\n this.options.onError?.(error);\n }\n }\n\n /** Stop the timer and the page listeners. Pending events stay; a later `push` binds again. */\n destroy(): void {\n this.unbind?.();\n this.unbind = null;\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.destroyed = true;\n // Nothing left to hand over: leave the storage to the other queues.\n if (typeof __SPLITHUB_LITE__ === 'undefined' && this.options.storage && this.size === 0 && this.inflight.size === 0) queuesOf(this.options.storage).delete(this);\n }\n}\n","// Debug mode: `?sh_debug=1` on any page (remembered for the session) makes the\n// SDK, the Next.js client and the drop-in script explain what they do: every\n// assignment with its reason, every exposure and goal with the payload, the\n// remote overrides they applied. Messages go to the console and to a\n// `splithub:debug` window event, which the React devtools panel listens to.\n//\n// ?sh_debug=1 log + panel\n// ?sh_debug=hold the same, and redirect experiments log the target instead of navigating\n// ?sh_debug=0 off\n\nconst KEY = 'sh_debug';\n\nexport type DebugKind = 'assign' | 'exposure' | 'goal' | 'pageview' | 'remote' | 'redirect' | 'info';\n\nexport interface DebugEntry {\n kind: DebugKind;\n message: string;\n data?: Record<string, unknown>;\n at: number;\n}\n\nfunction storage(): Storage | null {\n try {\n return typeof sessionStorage !== 'undefined' ? sessionStorage : null;\n } catch {\n return null;\n }\n}\n\n/** 'on' | 'hold' | null, reading the URL first (and remembering it), then the session. */\nexport function debugMode(): 'on' | 'hold' | null {\n if (typeof location === 'undefined') return null;\n const m = /[?&]sh_debug=([^&#]*)/.exec(location.search);\n const s = storage();\n if (m) {\n const v = decodeURIComponent(m[1] ?? '');\n const mode = v === '0' || v === 'off' || v === 'false' ? null : v === 'hold' ? 'hold' : 'on';\n try {\n if (mode) s?.setItem(KEY, mode);\n else s?.removeItem(KEY);\n } catch {\n // storage blocked\n }\n return mode;\n }\n const saved = s?.getItem(KEY);\n return saved === 'hold' ? 'hold' : saved ? 'on' : null;\n}\n\nexport const isDebug = (): boolean => debugMode() !== null;\n\nconst STYLE: Record<DebugKind, string> = {\n assign: 'color:#34d399',\n exposure: 'color:#60a5fa',\n goal: 'color:#fbbf24',\n pageview: 'color:#a78bfa',\n remote: 'color:#f472b6',\n redirect: 'color:#fb923c',\n info: 'color:#a1a1aa',\n};\n\nexport function debugLog(kind: DebugKind, message: string, data?: Record<string, unknown>): void {\n if (!isDebug()) return;\n const entry: DebugEntry = { kind, message, data, at: Date.now() };\n if (typeof console !== 'undefined') {\n if (data) console.log(`%c[splithub] ${kind}%c ${message}`, STYLE[kind], 'color:inherit', data);\n else console.log(`%c[splithub] ${kind}%c ${message}`, STYLE[kind], 'color:inherit');\n }\n if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof CustomEvent === 'function') window.dispatchEvent(new CustomEvent('splithub:debug', { detail: entry }));\n}\n\n/** Subscribe to debug entries (the devtools panel). Returns an unsubscribe function. */\nexport function onDebug(listener: (e: DebugEntry) => void): () => void {\n // React Native has a `window` without events.\n if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return () => undefined;\n const handler = (ev: Event) => listener((ev as CustomEvent<DebugEntry>).detail);\n window.addEventListener('splithub:debug', handler);\n return () => window.removeEventListener('splithub:debug', handler);\n}\n","import { assign, countsForHoldout, holdoutGroup, isDevEnvironment, parseForceParam } from './assignment';\nimport { debugLog, isDebug } from './debug';\nimport { devNote, explainAssignment } from './dev';\nimport { goalKeyFor, EVENT_NAME_PATTERN, getExperiment, HOLDOUT_KEY, isSplitHubConfig, pickProperty } from './config';\nimport { CLOUD_ENDPOINT, cloudEndpoints, isCloudEndpoint, isEndpointUrl, rememberEndpoint } from './endpoint';\nimport { EventQueue, createFetchTransport, type Transport } from './events';\nimport { murmur3 } from './hash';\nimport { newId, newSessionId, newVisitorId } from './ids';\nimport { memoryStorage, safeGet, safeSet, type KeyValueStorage, type PlatformAdapter } from './platform';\nimport {\n applyRemoteOverrides,\n fetchRemoteOverridesFrom,\n readRemoteCache,\n REMOTE_TTL_MS,\n resolveOverridesUrl,\n writeRemoteCache,\n type RemoteOverrides,\n} from './remote';\nimport { matchPath } from './paths';\nimport { claimAnalytics, releaseAnalytics } from './shared';\nimport { browserContext } from './targeting';\nimport type { Assignment, Experiment, SplitHubConfig, TargetingContext, Variant } from './types';\nimport {\n getOrCreateSessionId,\n getOrCreateStoredId,\n getOrCreateVisitorId,\n hasVisitorId,\n isBrowser,\n persistExposureSet,\n readStored,\n sessionExposureSet,\n sessionReferrer,\n writeStored,\n} from './visitor';\n\n// The drop-in script's build defines this as true, so `typeof` folds and the development\n// notes (strings included) drop out of sh.js. It has to be written inline at each use:\n// a constant imported from another module is inlined too late to remove the dead branch.\ndeclare const __SPLITHUB_LITE__: true | undefined;\n\nexport const SDK_VERSION = '0.1.0';\n/**\n * First visit (or first app launch) without cached overrides: the longest the client waits for\n * them. The fetch usually takes ~150 ms. Apps wait the same: later launches read the cache.\n */\nexport const REMOTE_WAIT_MS = 400;\nconst DEV_NOTE = 'Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.';\nexport { CLOUD_ENDPOINT };\n/** How long analytics events wait for overrides that may declare their property (a property made in the dashboard). */\nexport const PROPERTY_WAIT_MS = 5000;\n/** Goal and event props larger than this (as JSON) are trimmed: the ingest refuses them. */\nexport const MAX_PROPS_BYTES = 4096;\nconst MAX_ENGAGE_MS = 3_600_000;\n/** The app's user id (identify), kept across sessions; re-sent once per session. */\nconst UID_KEY = 'sh_uid';\nconst UID_SENT_KEY = 'sh_uid_sent';\nconst SESSION_KEY = 'sh_sid';\nconst EXPOSED_KEY = 'sh_exposed';\n/** An app away this long starts a new session when it comes back. */\nexport const SESSION_GAP_MS = 30 * 60 * 1000;\n\nexport interface ClientOptions {\n /** Provide on the server (from the cookie) so SSR and client agree. */\n visitorId?: string;\n sessionId?: string;\n /** Custom transport, e.g. a no-op for tests or SSR. */\n transport?: Transport;\n /**\n * Apps (React Native, desktop): storage, app info and lifecycle instead of a browser page.\n * The client then keeps the visitor in `storage`, persists unsent events (`sh_queue`), sends\n * no pageviews of its own (call `screen()`), and starts a new session after 30 minutes in the background.\n */\n platform?: PlatformAdapter;\n /** `sdk` of every batch. Default `core/<version>`; wrappers name themselves (`react-native/1.0.0`). */\n sdk?: string;\n /**\n * Send the cloud key as `?key=` so page-hide batches can use `navigator.sendBeacon`.\n * On by default for SplitHub Cloud (the key is public); off for a custom endpoint,\n * which may not read the key from the query.\n */\n keyInQuery?: boolean;\n /** Force variants, merged with `?sh_force=` in the browser. */\n overrides?: Record<string, string>;\n /** Disable all network activity (SSR, tests, `status: draft` previews). */\n disabled?: boolean;\n /**\n * Remote overrides (cloud mode): pause, traffic, weights and values changed\n * from the dashboard/CLI without a deploy. Cached in localStorage and\n * applied synchronously on later page loads. A first visit has no cache, so\n * the client waits up to `waitMs` for them, serving control meanwhile, then\n * decides once; a decided variant never changes mid-page.\n */\n remote?: {\n /** Apply these overrides now (SSR: pass what the server fetched). */\n overrides?: RemoteOverrides | null;\n /** Skip fetching. Default: fetch in cloud mode in the browser. */\n disabled?: boolean;\n url?: string;\n ttlMs?: number;\n /** First visit (nothing cached): how long to wait for the overrides before deciding from the file. Default 400 ms; 0 decides at once. */\n waitMs?: number;\n /**\n * Overrides still on their way (the drop-in script stops waiting for experiments before they arrive).\n * Analytics events for a property they may declare wait for them, up to 5 s.\n */\n arriving?: Promise<RemoteOverrides | null>;\n };\n /**\n * Visitor context for targeting (country, device, UTM ...). In the browser it\n * is collected automatically and merged with the cloud's geo (`ctx` in the\n * overrides JSON); on the server pass what you know from the request.\n */\n context?: TargetingContext;\n /**\n * Analytics property that receives pageviews and events: its id (`sh-x1h78w`), from\n * `properties` in the config or from the dashboard. Without it no analytics events are sent.\n */\n property?: string | false;\n /**\n * Single-page apps: after the first pageview(), report every client-side navigation\n * (history.pushState / replaceState / back) as a pageview too. Default true in the browser.\n */\n trackNavigation?: boolean;\n /**\n * Hash routers (`/#/pricing`): report the route after `#` as the page. Default: only when the\n * path is `/` and the hash starts with `#/`; `false` never, `true` on any path.\n */\n trackHash?: boolean;\n onError?: (error: unknown) => void;\n}\n\nexport interface SplitHubClient {\n readonly config: SplitHubConfig;\n readonly visitorId: string;\n /** May change during the client's life (an app back after 30 minutes away): read it each time, do not keep a copy. */\n readonly sessionId: string;\n /** Targeting context used for assignments. */\n readonly context: TargetingContext;\n /**\n * True on a first visit in cloud mode while the dashboard's overrides are on\n * their way (at most `remote.waitMs`). Every experiment serves control and\n * events wait; then the client decides once and notifies subscribers.\n */\n readonly pending: boolean;\n /** Resolves once experiments are decided (at once unless `pending`). */\n readonly ready: Promise<void>;\n /** Called once when a pending client decides. Returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Assignment without side effects. */\n assignment(experimentKey: string): Assignment;\n /** Variant key (control when not in experiment). Records an exposure. */\n variant(experimentKey: string): string;\n /** Payload of a `value` experiment (control value when not in experiment). Records an exposure. */\n value<T = unknown>(experimentKey: string): T;\n /** Record an exposure explicitly (the React components call this on mount). */\n exposure(experimentKey: string): void;\n /**\n * An event, any name (`track('signup')`, `track('Video Played', { id })`): one row that reaches the\n * analytics property and converts the experiments whose goal it is (the goal keyed by its slug).\n * Without a property it goes out as a goal row.\n */\n track(name: string, props?: Record<string, unknown>): void;\n /**\n * A page view: a `page` event for the analytics property, which also converts the pageview goals\n * of the URL. Without a property, the goal rows of the URL go out instead.\n */\n pageview(path?: string): void;\n /**\n * A screen of an app (or a virtual page on the web): a `page` event with url `/${name}` (or\n * `name` itself when it starts with `/`) and the name as title. `props` are accepted for\n * later; page rows carry none on the wire yet.\n */\n screen(name: string, props?: Record<string, unknown>): void;\n /**\n * Ties this visitor to your user id (1..128 characters) with optional flat traits\n * (`{ plan: 'pro' }`). Remembered in the browser and re-sent once per session; `null` forgets it.\n */\n identify(uid: string | null, traits?: Record<string, unknown>): void;\n /** Bind click goals (`type: 'click'`, CSS selector) to the document. Returns an unbind function. No-op outside the browser. */\n autoGoals(root?: Document | HTMLElement): () => void;\n flush(): Promise<void>;\n destroy(): void;\n /**\n * Binds the app lifecycle (background / foreground) again after `destroy()`, as a provider does when\n * StrictMode mounts it a second time. Idempotent; a no-op on the web, where the next event binds.\n */\n resume(): void;\n}\n\nfunction resolveEndpoint(config: SplitHubConfig): { endpoint: string; key?: string } {\n if (config.storage.mode === 'self') return { endpoint: config.storage.endpoint };\n return { endpoint: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\nexport function createClient(config: SplitHubConfig, options: ClientOptions = {}): SplitHubClient {\n if (!isSplitHubConfig(config)) {\n throw new Error('[splithub] pass the object returned by defineConfig() from splithub.config.ts');\n }\n\n // sh.js (LITE) never runs in an app: every `typeof __SPLITHUB_LITE__ === 'undefined' && adapter` below drops the app code from it.\n const adapter: PlatformAdapter | null = typeof __SPLITHUB_LITE__ === 'undefined' ? options.platform ?? null : null;\n const app = typeof __SPLITHUB_LITE__ === 'undefined' && adapter !== null;\n const browser = !app && isBrowser();\n // Remembers the visitor between pages or launches: a browser page or an app. The rest is a server.\n const persistent = browser || app;\n const sessionStore: KeyValueStorage | null = typeof __SPLITHUB_LITE__ === 'undefined' && adapter ? adapter.session ?? memoryStorage() : null;\n const kv = (kind: 'local' | 'session'): KeyValueStorage | null => (typeof __SPLITHUB_LITE__ === 'undefined' && adapter ? (kind === 'local' ? adapter.storage : sessionStore) : browser ? browserStorage(kind) : null);\n\n // Remote overrides: apply the cached copy synchronously, refresh in the background.\n // A first visit has no cache: wait briefly for the fresh copy instead, so a test\n // paused or started in the dashboard is right from the first page.\n const base = config;\n const publicKey = config.storage.mode === 'cloud' ? config.storage.key : undefined;\n // On the cloud the address can move after this build shipped: try the one the cloud last\n // announced first, then the default and a backup (see endpoint.ts). A custom endpoint stays as written.\n const local = kv('local');\n const cloudList = config.storage.mode === 'cloud' && isCloudEndpoint(config.storage.endpoint) && !options.remote?.url ? cloudEndpoints(local, config.storage.endpoint) : null;\n const adopt = (fresh: RemoteOverrides | null): void => {\n if (cloudList && fresh && isEndpointUrl(fresh.endpoint)) rememberEndpoint(local, fresh.endpoint);\n };\n let effective = config;\n let geo: RemoteOverrides['ctx'] | undefined;\n let waitFor: Promise<RemoteOverrides | null> | null = null;\n // The fresh overrides however late they come: they may declare the analytics property.\n let arriving: Promise<RemoteOverrides | null> | null = options.remote?.arriving ?? null;\n if (options.remote?.overrides) {\n effective = applyRemoteOverrides(config, options.remote.overrides);\n geo = options.remote.overrides.ctx;\n } else if (persistent && publicKey && !options.remote?.disabled) {\n // Apps have no file declaring the pushed experiments: they ask for those too (`all`), cached apart.\n // Websites keep the plain answer, the one sh.js and every other web client shares.\n const all = app;\n const cached = readRemoteCache(publicKey, adapter?.storage, all);\n if (cached) {\n effective = applyRemoteOverrides(config, cached.overrides);\n geo = cached.overrides.ctx;\n debugLog('remote', `overrides v${cached.overrides.version} from cache (${Math.round((Date.now() - cached.fetchedAt) / 1000)} s old)`, { experiments: cached.overrides.experiments });\n }\n const stale = !cached || Date.now() - cached.fetchedAt > (options.remote?.ttlMs ?? REMOTE_TTL_MS);\n if (stale) {\n const urls = cloudList ? cloudList.map((e) => resolveOverridesUrl(e, publicKey, all)) : [options.remote?.url ?? resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, publicKey, all)];\n const fetched = fetchRemoteOverridesFrom(urls).then(({ overrides: fresh, answered }) => {\n if (cloudList && answered > 0) rememberEndpoint(local, cloudList[answered]!);\n adopt(fresh);\n if (fresh) writeRemoteCache(publicKey, fresh, adapter?.storage, all);\n return fresh;\n });\n arriving = fetched;\n // `overrides: null` from the server (Next.js) means the HTML already follows the\n // file: waiting would make the first client render disagree with it.\n const waitMs = options.remote?.waitMs ?? REMOTE_WAIT_MS;\n if (!cached && waitMs > 0 && options.remote?.overrides === undefined) waitFor = withTimeout(fetched, waitMs);\n else {\n void fetched.then((fresh) => {\n if (fresh) debugLog('remote', `fresh overrides v${fresh.version} fetched; applied on the next page load`, { experiments: fresh.experiments });\n });\n }\n }\n }\n config = effective;\n\n const hadVisitor = persistent && !options.visitorId ? (typeof __SPLITHUB_LITE__ === 'undefined' && adapter ? safeGet(adapter.storage, config.visitorKey) !== null : hasVisitorId(config.visitorKey)) : undefined;\n const visitorId = options.visitorId ?? (typeof __SPLITHUB_LITE__ === 'undefined' && adapter ? getOrCreateStoredId(adapter.storage, config.visitorKey, newVisitorId) : browser ? getOrCreateVisitorId(config.visitorKey) : 'server');\n // On the server without the visitor's id, any variant would be a guess the browser then\n // contradicts; the control is the stable answer until the id is passed in.\n const noVisitor = !persistent && !options.visitorId;\n // On the server each visitor gets a session id of their own, so the cloud never merges\n // the visits of different visitors that share one server.\n let sessionId = options.sessionId ?? (typeof __SPLITHUB_LITE__ === 'undefined' && adapter ? getOrCreateStoredId(sessionStore, SESSION_KEY, newSessionId) : browser ? getOrCreateSessionId() : options.visitorId ? `srv_${murmur3(options.visitorId).toString(36)}` : 'server');\n // In the browser the device's own time zone beats the one guessed from the IP.\n const contextFor = (g: RemoteOverrides['ctx'] | undefined): TargetingContext => {\n if (typeof __SPLITHUB_LITE__ === 'undefined' && adapter) return { ...stripUndefined(g ?? {}), ...appContext(adapter), ...(hadVisitor === undefined ? {} : { visitor: hadVisitor ? 'returning' : 'new' }), ...(options.context ?? {}) };\n if (!browser) return { ...(g ?? {}), ...(options.context ?? {}) };\n const forPage = g?.timezone ? { ...g, timezone: undefined } : g;\n return browserContext({ ...stripUndefined(forPage ?? {}), ...(hadVisitor === undefined ? {} : { visitor: hadVisitor ? 'returning' : 'new' }), ...(options.context ?? {}) });\n };\n let context = contextFor(geo);\n // Crawlers and headless browsers get the control (see assign) and send nothing.\n const isBot = (): boolean => context.device === 'bot';\n const overrides = {\n ...(browser ? parseForceParam(location.search) : {}),\n ...(options.overrides ?? {}),\n };\n for (const [key, forced] of Object.entries(overrides)) {\n const experiment = config.experiments.find((e) => e.key === key);\n if (experiment && !experiment.variants.some((v) => v.key === forced)) {\n warn(`sh_force asks for variant \"${forced}\" of \"${key}\", which has ${experiment.variants.map((v) => `\"${v.key}\"`).join(', ')}; showing the control, not counted.`);\n }\n }\n const disabled = options.disabled ?? (!persistent && !options.transport);\n // The cloud refuses a project with nothing running (429) and drops exposures of drafts.\n // Sending them anyway only fills the console with errors, so they stay local (and visible in debug mode).\n const cloud = config.storage.mode === 'cloud';\n const cloudIdle = (): boolean => cloud && !config.experiments.some((e) => e.status === 'running') && !(config.properties ?? []).some((p) => p.status === 'running');\n // The analytics property events go to, resolved against the live config (the dashboard may add or pause one).\n // Property ids are lowercase; a pasted id with spaces or capitals still works.\n const wanted = typeof options.property === 'string' ? options.property.trim().toLowerCase() || null : null;\n // Analytics follow the freshest overrides, even ones that arrive after the experiments were decided:\n // events are not variants, so a property made in the dashboard counts from the first page.\n let propConfig = config;\n const known = (): boolean => wanted !== null && pickProperty(propConfig, wanted) !== null;\n const property = (): string | null => {\n if (!wanted) return null;\n const p = pickProperty(propConfig, wanted);\n return p && p.status === 'running' ? p.key : null;\n };\n // Tests are running in the config from the start, so `next dev` / `vite` would count the\n // developer as a visitor. Development never sends to the cloud; `vite preview` or a deploy does.\n const devLocal = cloud && isDevEnvironment();\n const held = new Set<string>();\n const hold = (key: string, kind: 'exposure' | 'goal' | 'pageview', message: string): void => {\n if (held.has(key)) return;\n held.add(key);\n debugLog(kind, message);\n };\n\n const transport = options.transport ?? createFetchTransport({\n ...resolveEndpoint(config),\n ...(cloudList ? { endpoint: cloudList[0], fallbacks: cloudList.slice(1) } : {}),\n keyInQuery: options.keyInQuery ?? (config.storage.mode === 'cloud' && isCloudEndpoint(config.storage.endpoint)),\n keepalive: !app,\n });\n const queue = new EventQueue({\n project: config.project,\n sdk: options.sdk ?? `core/${SDK_VERSION}`,\n transport,\n onError: options.onError,\n ...(typeof __SPLITHUB_LITE__ === 'undefined' && adapter ? { storage: adapter.storage, ...(adapter.app ? { app: adapter.app } : {}) } : {}),\n });\n const exposed = browser ? sessionExposureSet() : typeof __SPLITHUB_LITE__ === 'undefined' && adapter ? storedSet(sessionStore, EXPOSED_KEY) : new Set<string>();\n const saveExposed = (): void => {\n if (browser) persistExposureSet(exposed);\n else if (typeof __SPLITHUB_LITE__ === 'undefined' && adapter) safeSet(sessionStore, EXPOSED_KEY, JSON.stringify([...exposed]));\n };\n\n // Apps: the screen on show, set by screen(); it is the `url` of goals and events.\n let screenUrl: string | null = null;\n let screenTitle = '';\n const currentUrl = (): string | undefined =>\n browser ? location.pathname + location.search : screenUrl ?? undefined;\n // Read once, on the first page this client sees: a redirect variant or a later route change\n // would otherwise report the site itself as the referrer.\n const entryRef = browser ? sessionReferrer() : undefined;\n const refField = entryRef === undefined ? {} : { ref: entryRef };\n\n // Holdout marker: one `__holdout` exposure per visitor (holdout or enrolled) the first time they reach a running test.\n const markHoldout = (ts: number): void => {\n const group = holdoutGroup(config, visitorId);\n if (!group || noVisitor) return;\n const dedupKey = `${HOLDOUT_KEY}:${group}`;\n if (exposed.has(dedupKey)) return;\n if (devLocal) {\n hold(`x:${HOLDOUT_KEY}`, 'exposure', `${HOLDOUT_KEY} / ${group} not sent: development never sends to the cloud`);\n return;\n }\n exposed.add(dedupKey);\n saveExposed();\n const event = { id: newId('e_'), type: 'exposure' as const, exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...refField };\n debugLog('exposure', `${HOLDOUT_KEY} / ${group} recorded`, event);\n queue.push(event);\n };\n\n // While pending, exposures wait here with the time they happened (events wait on `ready`), so a\n // goal on the first page still counts (the cloud needs exposure time <= goal time).\n let pending = waitFor !== null;\n const waiting: Array<{ exp: string; ts: number }> = [];\n const listeners = new Set<() => void>();\n\n const sendExposure = (experimentKey: string, ts: number): void => {\n const a = client.assignment(experimentKey);\n if (config.holdout && countsForHoldout(a)) markHoldout(ts);\n if (!a.variant || a.reason === 'override') return;\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n devNote('dev-events', DEV_NOTE);\n hold(`x:${experimentKey}`, 'exposure', `${experimentKey} / ${a.variant.key} not sent: development never sends to the cloud`);\n return;\n }\n const dedupKey = `${experimentKey}:${a.variant.key}`;\n if (exposed.has(dedupKey)) return;\n exposed.add(dedupKey);\n saveExposed();\n const event = { id: newId('e_'), type: 'exposure' as const, exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...refField };\n debugLog('exposure', `${experimentKey} / ${a.variant.key} recorded`, event);\n queue.push(event);\n };\n\n const sendGoal = (name: string, props: Record<string, unknown> | undefined, ts: number): void => {\n // The overrides' geo may only now say this is a crawler.\n if (isBot()) return;\n // Resolved now, not when tracked: the overrides may have brought goals from the dashboard.\n // A name without a usable key goes out as an event only (an invalid key would cost the whole batch).\n const goal = goalKeyFor(config.goals, name);\n if (!goal) return;\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n devNote('dev-events', DEV_NOTE);\n hold(`g:${goal}`, 'goal', `${goal} not sent: development never sends to the cloud`);\n return;\n }\n if (cloudIdle()) {\n hold(`g:${goal}`, 'goal', `${goal} not sent: no experiment is running in this project yet`);\n return;\n }\n const event = { id: newId('g_'), type: 'goal' as const, goal, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...(props ? { props } : {}) };\n debugLog('goal', `${goal}${props ? ' ' + JSON.stringify(props) : ''}`, event);\n queue.push(event);\n };\n\n // Analytics wait while overrides that may declare the property are on their way; without\n // that, a first visit to a property made in the dashboard would lose its landing page.\n let propertyFetch: Promise<void> | null = null;\n const propertyWaiting: Array<() => void> = [];\n const warnUnknownProperty = (): void => {\n if (wanted && !known() && (isDevEnvironment() || isDebug())) {\n warn(`property \"${wanted}\" is not in splithub.config.ts or the dashboard, so no pageviews or events are sent. Check the id (it looks like sh-x1h78w).`);\n }\n };\n const withProperty = (send: () => void): void => {\n if (!wanted) return;\n if (!known() && propertyFetch) {\n propertyWaiting.push(send);\n return;\n }\n send();\n };\n\n // Hash routers keep the route after `#/`; that route is the page.\n const hashRoute = (): string | null => {\n if (!browser || options.trackHash === false) return null;\n const hash = location.hash;\n const route = hash.startsWith('#/') ? hash.slice(1) : hash.startsWith('#!/') ? hash.slice(2) : null;\n if (route === null || (options.trackHash !== true && location.pathname !== '/')) return null;\n return route.includes('?') || !location.search ? route : route + location.search;\n };\n const pageUrl = (): string => hashRoute() ?? location.pathname + location.search;\n const pagePath = (): string => hashRoute()?.split('?')[0] ?? location.pathname;\n\n // Engagement: visible time and deepest scroll of the current page, sent as `engage` when the\n // visitor moves on (route change) or leaves (page hidden, by beacon).\n let engage: { prop: string; url: string; ms: number; since: number | null; scroll: number } | null = null;\n // Apps: in the foreground. Engagement on an app is time on screen.\n let appVisible = true;\n const pageVisible = (): boolean => (app ? appVisible : typeof document === 'undefined' || document.visibilityState !== 'hidden');\n const scrollDepth = (): number => {\n if (!browser) return 0;\n const doc = document.documentElement;\n const height = Math.max(doc.scrollHeight, document.body?.scrollHeight ?? 0);\n const seen = (window.scrollY || doc.scrollTop || 0) + window.innerHeight;\n if (!height || seen >= height) return 100;\n return Math.max(0, Math.min(100, Math.round((seen / height) * 100)));\n };\n /** Queues the engaged time so far; `final` ends the page. True when something was queued. */\n const emitEngage = (final: boolean): boolean => {\n const e = engage;\n if (!e) return false;\n const now = Date.now();\n const ms = Math.min(MAX_ENGAGE_MS, Math.round(e.ms + (e.since !== null ? now - e.since : 0)));\n e.ms = 0;\n e.since = !final && pageVisible() ? now : null;\n if (final) engage = null;\n if (ms <= 0 || isBot()) return false;\n const event = { id: newId('n_'), type: 'engage' as const, prop: e.prop, vid: visitorId, sid: sessionId, ts: now, url: e.url, ms, scroll: e.scroll };\n debugLog('pageview', `${e.prop}: ${e.url} engaged ${Math.round(ms / 1000)} s, scrolled ${e.scroll}%`, event);\n queue.push(event);\n return true;\n };\n\n // Identify: the app's user id, sent once per session for each id and traits.\n let sentIdentity: string | null = safeGet(kv('session'), UID_SENT_KEY);\n const sendIdentify = (uid: string, traits: Record<string, string | number | boolean> | undefined, ts: number): void => {\n if (!wanted || isBot() || noVisitor) return;\n const mark = `${uid}\\n${traits ? JSON.stringify(traits) : ''}`;\n withProperty(() => {\n const prop = property();\n // Another client on the page shares the session mark: the same identity goes out once.\n if (!prop || isBot() || sentIdentity === mark || safeGet(kv('session'), UID_SENT_KEY) === mark) return;\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n hold(`i:${prop}`, 'pageview', `${prop}: identify not sent: development never sends to the cloud`);\n return;\n }\n sentIdentity = mark;\n safeSet(kv('session'), UID_SENT_KEY, mark);\n const event = { id: newId('i_'), type: 'identify' as const, prop, vid: visitorId, sid: sessionId, ts, uid, ...(traits ? { traits } : {}) };\n debugLog('info', `${prop}: identify ${uid}`, event);\n queue.push(event);\n });\n };\n // A returning user's id goes out once in each new session, with its first page.\n const resendIdentity = (ts: number): void => {\n const uid = safeGet(kv('local'), UID_KEY);\n if (uid && !(sentIdentity ?? '').startsWith(`${uid}\\n`)) sendIdentify(uid, undefined, ts);\n };\n\n // Pageview goals of a path, as goal rows: only when no `page` row carries them (the ingest\n // turns a page row into the conversions of the pageview goals it matches).\n const sendPageGoals = (path: string, ts: number): void => {\n if (isBot()) return;\n for (const goal of config.goals) {\n if (goal.type === 'pageview' && goal.path && matchPath(goal.path, path)) {\n debugLog('pageview', `${path} matches goal ${goal.key}`);\n sendGoal(goal.key, undefined, ts);\n }\n }\n };\n\n // Another client on this page (sh.js, a second provider) may already collect this property:\n // then this one sends no pageviews, time on page or identify of its own.\n const endpointKey = resolveEndpoint(config).endpoint;\n const owner = {};\n const claimed = new Set<string>();\n const collects = (prop: string): boolean => {\n if (claimAnalytics(`${endpointKey}|${prop}`, owner)) {\n claimed.add(prop);\n return true;\n }\n if (typeof __SPLITHUB_LITE__ === 'undefined') devNote(`shared:${prop}`, `Another SplitHub script on this page already collects pageviews for \"${prop}\", so this one leaves them to it. Keep one install per property: the SDK or sh.js.`);\n hold(`s:${prop}`, 'pageview', `${prop}: pageviews left to the other SplitHub script on this page`);\n return false;\n };\n\n // Analytics: pageviews and events for the property. The provider and a route hook may report\n // the same page twice in a row (StrictMode mounts twice); one view per URL per second is kept.\n let lastPage: { url: string; ts: number } | null = null;\n const sendPage = (path: string, ts: number, screen?: string): void => {\n if (isBot()) return;\n if (!wanted || noVisitor) {\n sendPageGoals(path, ts);\n return;\n }\n // Read the page now: by the time the property is known the visitor may be elsewhere.\n const url = browser && path === pagePath() ? pageUrl() : path;\n const title = screen !== undefined ? screen.slice(0, 200) : browser && typeof document !== 'undefined' ? document.title.slice(0, 200) : '';\n const ref = browser && typeof document !== 'undefined' ? document.referrer.slice(0, 512) : '';\n withProperty(() => {\n const prop = property();\n if (isBot()) return;\n if (!prop) {\n sendPageGoals(path, ts);\n return;\n }\n if (lastPage && lastPage.url === url && ts - lastPage.ts < 1000) return;\n lastPage = { url, ts };\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n devNote('dev-events', DEV_NOTE);\n hold(`p:${prop}`, 'pageview', `${prop}: pageviews not sent: development never sends to the cloud`);\n return;\n }\n if (!collects(prop)) return;\n emitEngage(true);\n const event = { id: newId('p_'), type: 'page' as const, prop, vid: visitorId, sid: sessionId, ts, url, ...(title ? { title } : {}), ...(ref ? { ref } : {}) };\n debugLog('pageview', `${prop}: ${url}`, event);\n queue.push(event);\n if (persistent) engage = { prop, url, ms: 0, since: pageVisible() ? ts : null, scroll: scrollDepth() };\n resendIdentity(ts);\n });\n };\n // track(): one row. With a running property the `event` row, which the ingest also turns into the\n // conversion of the experiments whose goal it is; without one, the goal row.\n const sendTracked = (name: string, props: Record<string, unknown> | undefined, ts: number): void => {\n if (isBot()) return;\n if (!wanted || noVisitor) {\n sendGoal(name, props, ts);\n return;\n }\n if (!EVENT_NAME_PATTERN.test(name)) {\n warn(`event name \"${name}\" is invalid: letters, digits, spaces and \"_ . : / -\", up to 64 characters.`);\n sendGoal(name, props, ts);\n return;\n }\n const url = currentUrl();\n withProperty(() => {\n const prop = property();\n if (isBot()) return;\n if (!prop) {\n sendGoal(name, props, ts);\n return;\n }\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n hold(`v:${prop}:${name}`, 'goal', `${prop}: event ${name} not sent: development never sends to the cloud`);\n return;\n }\n const event = { id: newId('v_'), type: 'event' as const, prop, name, vid: visitorId, sid: sessionId, ts, url, ...(props ? { props } : {}) };\n debugLog('goal', `${prop}: event ${name}${props ? ' ' + JSON.stringify(props) : ''}`, event);\n queue.push(event);\n });\n };\n\n const emit = (name: string, props: Record<string, unknown> | undefined): void => {\n if (disabled || isBot()) return;\n bindApp();\n const ts = Date.now();\n props = fitProps(props, `event \"${name}\"`);\n // After the ready handler has sent the waiting exposures: a goal only converts a visitor already in the experiment.\n if (pending) void ready.then(() => sendTracked(name, props, ts));\n else sendTracked(name, props, ts);\n };\n\n // Client-side navigations as pageviews, bound on the first pageview() and released by destroy().\n // A new path, query or hash route is a new page.\n let unwatch: (() => void) | null = null;\n const watch = (): void => {\n if (unwatch || !browser || options.trackNavigation === false) return;\n let last = pageUrl();\n unwatch = onNavigation(() => {\n const now = pageUrl();\n if (now === last) return;\n last = now;\n client.pageview();\n });\n };\n\n // Page listeners of a property: engagement (scroll, hide) and the automatic link events.\n let unbindPage: (() => void) | null = null;\n const bindPage = (): void => {\n if (unbindPage || !browser || !wanted || disabled) return;\n const onScroll = (): void => {\n if (engage) engage.scroll = Math.max(engage.scroll, scrollDepth());\n };\n const leave = (): void => {\n if (emitEngage(false)) void queue.flush(true);\n if (engage) engage.since = null;\n };\n const onVisibility = (): void => {\n if (document.visibilityState === 'hidden') leave();\n else if (engage && engage.since === null) engage.since = Date.now();\n };\n const onShow = (): void => {\n if (engage && engage.since === null && pageVisible()) engage.since = Date.now();\n };\n addEventListener('scroll', onScroll, { passive: true });\n document.addEventListener('visibilitychange', onVisibility);\n addEventListener('pagehide', leave);\n addEventListener('pageshow', onShow);\n unbindPage = () => {\n removeEventListener('scroll', onScroll);\n document.removeEventListener('visibilitychange', onVisibility);\n removeEventListener('pagehide', leave);\n removeEventListener('pageshow', onShow);\n };\n };\n\n // Apps: background closes the screen's engagement and sends the queue; coming back after\n // 30 minutes starts a new session, which opens with the screen on show.\n let unbindApp: (() => void) | null = null;\n let backgroundAt: number | null = null;\n const rotateSession = (now: number): void => {\n if (!(typeof __SPLITHUB_LITE__ === 'undefined')) return;\n sessionId = newSessionId();\n safeSet(sessionStore, SESSION_KEY, sessionId);\n sentIdentity = null;\n safeSet(sessionStore, UID_SENT_KEY, null);\n lastPage = null;\n debugLog('info', `new session ${sessionId} after the app was away`);\n if (screenUrl && !pending) sendPage(screenUrl, now, screenTitle);\n };\n const bindApp = (): void => {\n if (!(typeof __SPLITHUB_LITE__ === 'undefined') || !adapter || unbindApp || disabled) return;\n const offBackground = adapter.onBackground?.(() => {\n if (backgroundAt !== null) return;\n backgroundAt = Date.now();\n appVisible = false;\n emitEngage(false);\n void queue.flush(false);\n });\n const offForeground = adapter.onForeground?.(() => {\n const now = Date.now();\n const away = backgroundAt === null ? 0 : now - backgroundAt;\n backgroundAt = null;\n appVisible = true;\n if (away >= SESSION_GAP_MS && !options.sessionId) rotateSession(now);\n if (engage && engage.since === null) engage.since = now;\n });\n unbindApp = () => {\n offBackground?.();\n offForeground?.();\n };\n };\n\n const ready: Promise<void> = waitFor\n ? waitFor.then((fresh) => {\n if (fresh) {\n config = applyRemoteOverrides(base, fresh);\n propConfig = config;\n context = contextFor(fresh.ctx);\n debugLog('remote', `first visit: overrides v${fresh.version} arrived, experiments decided`, { experiments: fresh.experiments });\n } else {\n debugLog('remote', 'first visit: overrides did not arrive in time; experiments follow splithub.config.ts');\n }\n pending = false;\n // Exposures first: a goal only converts a visitor already in the test.\n for (const w of waiting) sendExposure(w.exp, w.ts);\n waiting.length = 0;\n for (const listener of [...listeners]) listener();\n listeners.clear();\n })\n : Promise.resolve();\n\n if (wanted && !known()) {\n if (arriving) {\n propertyFetch = withTimeout(arriving, PROPERTY_WAIT_MS).then((fresh) => {\n if (fresh) propConfig = applyRemoteOverrides(base, fresh);\n propertyFetch = null;\n warnUnknownProperty();\n for (const send of propertyWaiting.splice(0)) send();\n });\n } else warnUnknownProperty();\n }\n\n const decided = new Set<string>();\n const client: SplitHubClient = {\n get config() {\n return config;\n },\n visitorId,\n get sessionId() {\n return sessionId;\n },\n get context() {\n return context;\n },\n get pending() {\n return pending;\n },\n ready,\n subscribe(listener) {\n if (!pending) return () => undefined;\n listeners.add(listener);\n return () => void listeners.delete(listener);\n },\n\n assignment(experimentKey) {\n if (pending) return { experiment: experimentKey, variant: null, reason: 'pending' };\n let a = assign(config, experimentKey, visitorId, { overrides, context });\n if (noVisitor && a.variant && a.reason !== 'override') a = { experiment: experimentKey, variant: null, reason: 'no_visitor' };\n if (typeof __SPLITHUB_LITE__ === 'undefined') explainAssignment(getExperiment(config, experimentKey), a);\n if (isDebug() && !decided.has(experimentKey)) {\n decided.add(experimentKey);\n const exp = getExperiment(config, experimentKey);\n debugLog('assign', `${experimentKey} → ${a.variant?.key ?? 'control (no variant)'} · ${a.reason}`, { kind: exp?.kind, status: exp?.status, traffic: exp?.traffic, flow: Boolean(exp?.flow), ...(a.variant?.value !== undefined && a.variant?.value !== null ? { value: a.variant.value } : {}), ...(a.variant?.to ? { to: a.variant.to } : {}) });\n }\n return a;\n },\n\n exposure(experimentKey) {\n if (disabled) return;\n if (pending) {\n if (!waiting.some((w) => w.exp === experimentKey)) waiting.push({ exp: experimentKey, ts: Date.now() });\n return;\n }\n sendExposure(experimentKey, Date.now());\n },\n\n variant(experimentKey) {\n const experiment = getExperiment(config, experimentKey);\n if (!experiment) {\n warnUnknown(experimentKey);\n return 'control';\n }\n const a = client.assignment(experimentKey);\n client.exposure(experimentKey);\n return (a.variant ?? experiment.variants[0]!).key;\n },\n\n value<T>(experimentKey: string): T {\n const experiment = getExperiment(config, experimentKey);\n if (!experiment) {\n warnUnknown(experimentKey);\n return undefined as T;\n }\n const a = client.assignment(experimentKey);\n client.exposure(experimentKey);\n return (a.variant ?? experiment.variants[0]!).value as T;\n },\n\n track(name, props) {\n emit(name, props);\n },\n\n pageview(path) {\n const current = path ?? (browser ? pagePath() : undefined);\n if (!current) return;\n if (path === undefined) watch();\n bindPage();\n if (disabled) return;\n // Pageview goals may be declared in the dashboard: match them once the overrides are in.\n if (pending) {\n const ts = Date.now();\n void ready.then(() => sendPage(current, ts));\n return;\n }\n sendPage(current, Date.now());\n },\n\n screen(name) {\n // sh.js does not expose screen(): its pageviews follow the page.\n if (!(typeof __SPLITHUB_LITE__ === 'undefined')) return;\n const label = typeof name === 'string' ? name.trim() : '';\n if (!label) {\n warn('screen() needs the name of the screen.');\n return;\n }\n const url = label.startsWith('/') ? label : `/${label}`;\n if (app) {\n screenUrl = url;\n screenTitle = label;\n }\n bindApp();\n if (disabled) return;\n const ts = Date.now();\n if (pending) {\n void ready.then(() => sendPage(url, ts, label));\n return;\n }\n sendPage(url, ts, label);\n },\n\n identify(uid, traits) {\n if (uid === null) {\n safeSet(kv('local'), UID_KEY, null);\n safeSet(kv('session'), UID_SENT_KEY, null);\n sentIdentity = null;\n return;\n }\n const id = typeof uid === 'string' ? uid.trim() : '';\n if (!id || id.length > 128) {\n warn('identify() needs a user id of 1 to 128 characters.');\n return;\n }\n safeSet(kv('local'), UID_KEY, id);\n if (disabled || isBot()) return;\n sendIdentify(id, cleanTraits(traits), Date.now());\n },\n\n autoGoals(root) {\n if (!browser) return () => undefined;\n const clickGoals = config.goals.filter((g) => g.type === 'click' && g.selector);\n if (clickGoals.length === 0) return () => undefined;\n const target: Document | HTMLElement = root ?? document;\n const onClick = (ev: Event) => {\n const el = ev.target as Element | null;\n if (!el || typeof el.closest !== 'function') return;\n for (const g of clickGoals) {\n try {\n if (el.closest(g.selector!)) client.track(g.key);\n } catch {\n // invalid selector: ignore\n }\n }\n };\n target.addEventListener('click', onClick, true);\n return () => target.removeEventListener('click', onClick, true);\n },\n\n flush: () => queue.flush(false),\n resume: () => bindApp(),\n // Unbinds the page listeners; pending events are kept and a later event binds again,\n // so a provider may destroy on unmount even under StrictMode's double mount.\n destroy: () => {\n queue.destroy();\n unwatch?.();\n unwatch = null;\n unbindPage?.();\n unbindPage = null;\n unbindApp?.();\n unbindApp = null;\n for (const prop of claimed) releaseAnalytics(`${endpointKey}|${prop}`, owner);\n claimed.clear();\n },\n };\n\n bindApp();\n if (browser && isDebug()) {\n (window as unknown as { __splithub?: SplitHubClient }).__splithub = client;\n debugLog('info', `client ready · ${config.experiments.length} experiments · visitor ${visitorId} · ${config.storage.mode} mode`, { context });\n }\n return client;\n}\n\n// One wrap of history for every client on the page; each client listens while it lives.\nconst navListeners = new Set<() => void>();\nlet historyWrapped = false;\nfunction onNavigation(listener: () => void): () => void {\n if (!historyWrapped && typeof history !== 'undefined') {\n historyWrapped = true;\n for (const method of ['pushState', 'replaceState'] as const) {\n const original = history[method];\n history[method] = function (this: History, ...args: Parameters<History['pushState']>) {\n const out = original.apply(this, args);\n // After the router has rendered the new page, so its title is current.\n setTimeout(() => navListeners.forEach((l) => l()), 0);\n return out;\n };\n }\n addEventListener('popstate', () => navListeners.forEach((l) => l()));\n addEventListener('hashchange', () => navListeners.forEach((l) => l()));\n }\n navListeners.add(listener);\n return () => void navListeners.delete(listener);\n}\n\n/** Browser storage as a KeyValueStorage, silent when blocked. */\nfunction browserStorage(kind: 'local' | 'session'): KeyValueStorage {\n const area = kind === 'local' ? 'localStorage' : 'sessionStorage';\n return {\n getItem: (k) => readStored(area, k),\n setItem: (k, v) => writeStored(area, k, v),\n removeItem: (k) => writeStored(area, k, null),\n };\n}\n\nfunction storedSet(storage: KeyValueStorage | null, key: string): Set<string> {\n try {\n const raw = safeGet(storage, key);\n const list = raw ? (JSON.parse(raw) as unknown) : null;\n return new Set(Array.isArray(list) ? list.filter((x): x is string => typeof x === 'string') : []);\n } catch {\n return new Set();\n }\n}\n\n/** An app's targeting context: what the adapter says, with platform, version and OS filled from `app`. */\nfunction appContext(adapter: PlatformAdapter): TargetingContext {\n const info = adapter.app;\n return {\n ...(info ? { platform: info.platform, os: info.platform } : {}),\n ...(info?.version ? { appVersion: info.version } : {}),\n ...(info?.device ? { device: info.device } : {}),\n ...stripUndefined(adapter.context ?? {}),\n };\n}\n\nfunction stripUndefined<T extends object>(o: T): Partial<T> {\n return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) as Partial<T>;\n}\n\nfunction withTimeout<T>(p: Promise<T | null>, ms: number): Promise<T | null> {\n return new Promise((resolve) => {\n const t = setTimeout(() => resolve(null), ms);\n p.then(\n (v) => {\n clearTimeout(t);\n resolve(v);\n },\n () => {\n clearTimeout(t);\n resolve(null);\n }\n );\n });\n}\n\n/** Props as the ingest takes them: at most 4 KB of JSON. Larger ones keep `revenue` and the plain values that fit, with a warning. */\nfunction fitProps(props: Record<string, unknown> | undefined, what: string): Record<string, unknown> | undefined {\n if (!props || typeof props !== 'object') return undefined;\n let json: string;\n try {\n json = JSON.stringify(props);\n } catch {\n warn(`${what}: props cannot be sent as JSON, so they were left out.`);\n return undefined;\n }\n if (json.length <= MAX_PROPS_BYTES) return props;\n const out: Record<string, unknown> = {};\n let size = 2;\n const entries = Object.entries(props).sort(([a], [b]) => (a === 'revenue' ? -1 : b === 'revenue' ? 1 : 0));\n for (const [key, value] of entries) {\n if (value !== null && typeof value === 'object') continue;\n const part = JSON.stringify({ [key]: value }).length - 1;\n if (size + part > MAX_PROPS_BYTES) continue;\n out[key] = value;\n size += part;\n }\n const kept = Object.keys(out);\n warn(`${what}: props are larger than 4 KB, so ${kept.length ? `only ${kept.join(', ')} went out` : 'none went out'}.`);\n return kept.length ? out : undefined;\n}\n\n/** Flat traits (text, numbers, true/false) up to 4 KB; anything else is left out. */\nfunction cleanTraits(traits: Record<string, unknown> | undefined): Record<string, string | number | boolean> | undefined {\n if (!traits || typeof traits !== 'object') return undefined;\n const out: Record<string, string | number | boolean> = {};\n let size = 2;\n let skipped = false;\n for (const [key, value] of Object.entries(traits)) {\n const plain = typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value));\n if (!plain || key.length > 64) {\n if (value !== undefined) skipped = true;\n continue;\n }\n const v = typeof value === 'string' ? value.slice(0, 256) : value;\n const part = JSON.stringify({ [key]: v }).length - 1;\n if (size + part > MAX_PROPS_BYTES) {\n skipped = true;\n continue;\n }\n out[key] = v;\n size += part;\n }\n if (skipped) warn('identify(): traits keep text, numbers and true/false up to 4 KB; the rest was left out.');\n return Object.keys(out).length ? out : undefined;\n}\n\nconst warned = new Set<string>();\nfunction warn(message: string): void {\n if (warned.has(message)) return;\n warned.add(message);\n if (typeof console !== 'undefined') console.warn(`[splithub] ${message}`);\n}\nfunction warnUnknown(key: string): void {\n warn(`experiment \"${key}\" is not in splithub.config.ts; rendering control.`);\n}\n\nexport type { Experiment, Variant };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaO,SAAS,mBAA4B;AAC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age"]}
|
|
@@ -203,7 +203,11 @@ type StorageInput = {
|
|
|
203
203
|
mode: 'cloud';
|
|
204
204
|
/** Public project key (`pk_...`). Safe to ship to the browser. */
|
|
205
205
|
key?: string;
|
|
206
|
-
/**
|
|
206
|
+
/**
|
|
207
|
+
* Where events go, if not the default: a domain (`go.sh2.uk`) or a full URL
|
|
208
|
+
* (`https://go-staging.sh2.uk/v1/events`, a proxy on your own domain). Unset, the SDK
|
|
209
|
+
* uses the address the cloud announces, so a move of the cloud needs no new build.
|
|
210
|
+
*/
|
|
207
211
|
endpoint?: string;
|
|
208
212
|
} | {
|
|
209
213
|
mode: 'self';
|
|
@@ -203,7 +203,11 @@ type StorageInput = {
|
|
|
203
203
|
mode: 'cloud';
|
|
204
204
|
/** Public project key (`pk_...`). Safe to ship to the browser. */
|
|
205
205
|
key?: string;
|
|
206
|
-
/**
|
|
206
|
+
/**
|
|
207
|
+
* Where events go, if not the default: a domain (`go.sh2.uk`) or a full URL
|
|
208
|
+
* (`https://go-staging.sh2.uk/v1/events`, a proxy on your own domain). Unset, the SDK
|
|
209
|
+
* uses the address the cloud announces, so a move of the cloud needs no new build.
|
|
210
|
+
*/
|
|
207
211
|
endpoint?: string;
|
|
208
212
|
} | {
|
|
209
213
|
mode: 'self';
|
package/dist/vite.cjs
CHANGED
|
@@ -25,9 +25,20 @@ __export(vite_exports, {
|
|
|
25
25
|
});
|
|
26
26
|
module.exports = __toCommonJS(vite_exports);
|
|
27
27
|
|
|
28
|
-
// src/
|
|
29
|
-
function
|
|
30
|
-
|
|
28
|
+
// src/platform.ts
|
|
29
|
+
function safeGet(storage, key) {
|
|
30
|
+
try {
|
|
31
|
+
return storage?.getItem(key) ?? null;
|
|
32
|
+
} catch {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function safeSet(storage, key, value) {
|
|
37
|
+
try {
|
|
38
|
+
if (value === null) storage?.removeItem(key);
|
|
39
|
+
else storage?.setItem(key, value);
|
|
40
|
+
} catch {
|
|
41
|
+
}
|
|
31
42
|
}
|
|
32
43
|
|
|
33
44
|
// src/remote.ts
|
|
@@ -90,20 +101,73 @@ function resolveOverridesUrl(eventsEndpoint, publicKey, all = false) {
|
|
|
90
101
|
const base = eventsEndpoint.replace(/\/events\/?$/, "");
|
|
91
102
|
return `${base}/overrides/${encodeURIComponent(publicKey)}.json${all ? "?all=1" : ""}`;
|
|
92
103
|
}
|
|
93
|
-
async function
|
|
104
|
+
async function fetchRemoteOverridesFrom(urls, fetchImpl = fetch) {
|
|
105
|
+
for (let i = 0; i < urls.length; i++) {
|
|
106
|
+
let res;
|
|
107
|
+
try {
|
|
108
|
+
res = await fetchImpl(urls[i], { cache: "no-cache" });
|
|
109
|
+
} catch {
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
const body = res.ok ? await res.json() : null;
|
|
114
|
+
return { overrides: isRemoteOverrides(body) ? body : null, answered: i };
|
|
115
|
+
} catch {
|
|
116
|
+
return { overrides: null, answered: i };
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return { overrides: null, answered: -1 };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// src/endpoint.ts
|
|
123
|
+
var CLOUD_ENDPOINT = "https://go.sh2.uk/v1/events";
|
|
124
|
+
var CLOUD_FALLBACK_ENDPOINTS = ["https://splithub-go.adbro.workers.dev/v1/events"];
|
|
125
|
+
var PAST_CLOUD_ENDPOINTS = ["https://go.splithub.io/v1/events"];
|
|
126
|
+
var ENDPOINT_KEY = "sh_endpoint";
|
|
127
|
+
var trim = (url) => url.replace(/\/+$/, "");
|
|
128
|
+
function isEndpointUrl(value) {
|
|
129
|
+
if (typeof value !== "string" || value.length > 200) return false;
|
|
94
130
|
try {
|
|
95
|
-
const
|
|
96
|
-
|
|
97
|
-
const body = await res.json();
|
|
98
|
-
return isRemoteOverrides(body) ? body : null;
|
|
131
|
+
const u = new URL(value);
|
|
132
|
+
return u.protocol === "https:" && /\/v1\/events\/?$/.test(u.pathname) && !u.search && !u.hash;
|
|
99
133
|
} catch {
|
|
100
|
-
return
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
function isCloudEndpoint(endpoint) {
|
|
138
|
+
if (endpoint === void 0) return true;
|
|
139
|
+
const e = trim(endpoint);
|
|
140
|
+
return [CLOUD_ENDPOINT, ...CLOUD_FALLBACK_ENDPOINTS, ...PAST_CLOUD_ENDPOINTS].some((c) => c === e);
|
|
141
|
+
}
|
|
142
|
+
function rememberedEndpoint(store) {
|
|
143
|
+
const v = safeGet(store ?? null, ENDPOINT_KEY);
|
|
144
|
+
return isEndpointUrl(v) ? v : null;
|
|
145
|
+
}
|
|
146
|
+
function rememberEndpoint(store, endpoint) {
|
|
147
|
+
if (!isEndpointUrl(endpoint) || rememberedEndpoint(store) === endpoint) return;
|
|
148
|
+
safeSet(store ?? null, ENDPOINT_KEY, endpoint);
|
|
149
|
+
}
|
|
150
|
+
function cloudEndpoints(store, configured) {
|
|
151
|
+
const own = configured && !PAST_CLOUD_ENDPOINTS.includes(trim(configured)) ? configured : null;
|
|
152
|
+
const list = [rememberedEndpoint(store), own, CLOUD_ENDPOINT, ...CLOUD_FALLBACK_ENDPOINTS];
|
|
153
|
+
const out = [];
|
|
154
|
+
for (const e of list) if (e && !out.includes(trim(e))) out.push(trim(e));
|
|
155
|
+
return out;
|
|
156
|
+
}
|
|
157
|
+
async function fetchCloudOverrides(endpoint, key, options = {}) {
|
|
158
|
+
const list = isCloudEndpoint(endpoint) ? cloudEndpoints(options.store, endpoint) : [endpoint];
|
|
159
|
+
const { overrides, answered } = await fetchRemoteOverridesFrom(list.map((e) => resolveOverridesUrl(e, key, options.all)), options.fetchImpl);
|
|
160
|
+
if (isCloudEndpoint(endpoint)) {
|
|
161
|
+
if (answered > 0) rememberEndpoint(options.store, list[answered]);
|
|
162
|
+
if (overrides && isEndpointUrl(overrides.endpoint)) rememberEndpoint(options.store, overrides.endpoint);
|
|
101
163
|
}
|
|
164
|
+
return overrides;
|
|
102
165
|
}
|
|
103
166
|
|
|
104
|
-
// src/
|
|
105
|
-
|
|
106
|
-
|
|
167
|
+
// src/config.ts
|
|
168
|
+
function isSplitHubConfig(value) {
|
|
169
|
+
return Boolean(value) && typeof value === "object" && value.__splithub === 2;
|
|
170
|
+
}
|
|
107
171
|
|
|
108
172
|
// src/vite.ts
|
|
109
173
|
var VIRTUAL = "virtual:splithub-dev";
|
|
@@ -127,9 +191,8 @@ function describeExperiment(config, e, live) {
|
|
|
127
191
|
}
|
|
128
192
|
async function liveConfig(config) {
|
|
129
193
|
if (config.storage.mode !== "cloud" || !config.storage.key) return null;
|
|
130
|
-
const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);
|
|
131
194
|
const timeout = new Promise((resolve) => setTimeout(() => resolve(null), 3e3));
|
|
132
|
-
const overrides = await Promise.race([
|
|
195
|
+
const overrides = await Promise.race([fetchCloudOverrides(config.storage.endpoint, config.storage.key), timeout]);
|
|
133
196
|
return overrides ? applyRemoteOverrides(config, overrides) : null;
|
|
134
197
|
}
|
|
135
198
|
function splithub(options = {}) {
|