@splithub/next 0.3.0 → 0.4.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.
@@ -37,6 +37,7 @@ import {
37
37
  parseForceParam,
38
38
  parseUserAgent,
39
39
  redirectTarget,
40
+ referrerOrigin,
40
41
  SDK_VERSION
41
42
  } from "@splithub/core";
42
43
  import { NextResponse } from "next/server";
@@ -94,6 +95,8 @@ function splithubMiddleware(baseConfig, options = {}) {
94
95
  });
95
96
  const cloudDev = config.storage.mode === "cloud" && isDevEnvironment();
96
97
  const events = [];
98
+ const ref = referrerOrigin(request.headers.get("referer"), request.nextUrl.host);
99
+ const refField = ref === void 0 ? {} : { ref };
97
100
  if (decision) {
98
101
  if (decision.to) {
99
102
  const target = redirectTarget(decision.to, request.nextUrl.href);
@@ -110,13 +113,13 @@ function splithubMiddleware(baseConfig, options = {}) {
110
113
  const record = !cloudDev && (decision.reason === "assigned" || decision.reason === "dev" && config.storage.mode === "self");
111
114
  if (trackRedirects && record && request.cookies.get(exposureCookie)?.value !== decision.variant) {
112
115
  cookiesToSet.push({ name: exposureCookie, value: decision.variant });
113
- events.push({ id: newId("e_"), type: "exposure", exp: decision.experiment, var: decision.variant, vid: visitorId, sid: "edge", ts: Date.now(), url: pathname });
116
+ events.push({ id: newId("e_"), type: "exposure", exp: decision.experiment, var: decision.variant, vid: visitorId, sid: "edge", ts: Date.now(), url: pathname, ...refField });
114
117
  }
115
118
  }
116
119
  const group = reachedTest ? holdoutGroup(config, visitorId) : null;
117
120
  if (group && trackRedirects && !cloudDev && request.cookies.get(`sh_x_${HOLDOUT_KEY}`)?.value !== group) {
118
121
  cookiesToSet.push({ name: `sh_x_${HOLDOUT_KEY}`, value: group });
119
- events.push({ id: newId("e_"), type: "exposure", exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: "edge", ts: Date.now(), url: pathname });
122
+ events.push({ id: newId("e_"), type: "exposure", exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: "edge", ts: Date.now(), url: pathname, ...refField });
120
123
  }
121
124
  if (events.length) {
122
125
  const target = ingestTarget(config, request.nextUrl.origin);
@@ -148,4 +151,4 @@ export {
148
151
  requestContext,
149
152
  splithubMiddleware
150
153
  };
151
- //# sourceMappingURL=chunk-BH4ACCFH.js.map
154
+ //# sourceMappingURL=chunk-S5V4VC56.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/remote.ts","../src/middleware.ts"],"sourcesContent":["import { CLOUD_ENDPOINT, fetchRemoteOverrides, resolveOverridesUrl, REMOTE_TTL_MS, type RemoteOverrides, type SplitHubConfig } from '@splithub/core';\n\ninterface MemoEntry {\n at: number;\n value: RemoteOverrides | null;\n pending: Promise<RemoteOverrides | null> | null;\n}\n\n// Module-level memo: edge isolates and Node servers keep it across requests,\n// so at most one fetch per TTL per public key.\nconst memo = new Map<string, MemoEntry>();\n\nexport interface RemoteOptions {\n ttlMs?: number;\n /** Override the fetch implementation (tests). */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Live overrides for a cloud-mode config, cached in memory for `ttlMs`\n * (default 60s). Returns null in self mode or when the cloud is unreachable\n * (the config file then applies as-is).\n */\nexport async function getRemoteOverrides(config: SplitHubConfig, options: RemoteOptions = {}): Promise<RemoteOverrides | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const ttl = options.ttlMs ?? REMOTE_TTL_MS;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const entry = memo.get(url);\n const now = Date.now();\n if (entry && now - entry.at < ttl) return entry.value;\n if (entry?.pending) return entry.value ?? entry.pending;\n\n const pending = fetchRemoteOverrides(url, options.fetchImpl).then((value) => {\n memo.set(url, { at: Date.now(), value: value ?? entry?.value ?? null, pending: null });\n return value ?? entry?.value ?? null;\n });\n memo.set(url, { at: entry?.at ?? 0, value: entry?.value ?? null, pending });\n // Serve stale while revalidating; first call waits.\n return entry ? entry.value : pending;\n}\n\n/** Tests only. */\nexport function clearRemoteMemo(): void {\n memo.clear();\n}\n","import {\n applyRemoteOverrides,\n CLOUD_ENDPOINT,\n countsForHoldout,\n decideRedirect,\n explainAssignment,\n HOLDOUT_KEY,\n holdoutGroup,\n isDevEnvironment,\n matchPath,\n newId,\n newVisitorId,\n parseCookies,\n parseForceParam,\n parseUserAgent,\n redirectTarget,\n referrerOrigin,\n SDK_VERSION,\n type EventBatch,\n type ExposureEvent,\n type SplitHubConfig,\n type TargetingContext,\n} from '@splithub/core';\nimport { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';\nimport { getRemoteOverrides } from './remote';\n\nexport const VISITOR_HEADER = 'x-splithub-vid';\nconst ONE_YEAR = 60 * 60 * 24 * 365;\n\nexport interface MiddlewareOptions {\n /** Return true to skip a path entirely. Defaults to `_next`, `api` and files with an extension. */\n exclude?: (pathname: string) => boolean;\n /** Send exposures for redirect experiments from the edge. Default true. */\n trackRedirects?: boolean;\n /** Apply live overrides from the cloud (cloud mode only). Default true. */\n remote?: boolean;\n}\n\nfunction defaultExclude(pathname: string): boolean {\n return pathname.startsWith('/_next') || pathname.startsWith('/api/') || /\\.[a-z0-9]+$/i.test(pathname);\n}\n\n/** Same rule as sh.js and pageview goals (from `@splithub/core`). */\nexport { matchPath };\n\n/**\n * Targeting context from request headers: Cloudflare / Vercel geo, user agent, language,\n * referrer, cookies. `timezone` (for `hour` / `weekday`) comes from Vercel's\n * `x-vercel-ip-timezone` or a `cf-timezone` / `x-timezone` header you set; without one\n * the flow uses UTC.\n */\nexport function requestContext(headers: Headers, url: string, visitor?: 'new' | 'returning'): TargetingContext {\n const ua = parseUserAgent(headers.get('user-agent'));\n const country = headers.get('cf-ipcountry') ?? headers.get('x-vercel-ip-country') ?? headers.get('x-country') ?? undefined;\n const region = headers.get('x-vercel-ip-country-region') ?? headers.get('cf-region') ?? undefined;\n const city = headers.get('x-vercel-ip-city') ?? headers.get('cf-ipcity') ?? undefined;\n const timezone = headers.get('x-vercel-ip-timezone') ?? headers.get('cf-timezone') ?? headers.get('x-timezone') ?? undefined;\n return {\n country: country ?? undefined,\n region: region ? decodeURIComponent(region) : undefined,\n city: city ? decodeURIComponent(city) : undefined,\n device: ua.device,\n browser: ua.browser,\n os: ua.os,\n language: headers.get('accept-language') ?? undefined,\n referrer: headers.get('referer') ?? undefined,\n url,\n cookies: parseCookies(headers.get('cookie')),\n ...(timezone ? { timezone } : {}),\n ...(visitor ? { visitor } : {}),\n };\n}\n\nfunction ingestTarget(config: SplitHubConfig, origin: string): { url: string; key?: string } {\n if (config.storage.mode === 'self') return { url: new URL(config.storage.endpoint, origin).toString() };\n return { url: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\n/**\n * Next.js middleware:\n * 1. ensures the `sh_vid` visitor cookie, so SSR and the client agree on variants;\n * 2. forwards the visitor id to Server Components via the `x-splithub-vid` header;\n * 3. serves redirect experiments with an invisible rewrite (URL unchanged, no flash);\n * 4. records the redirect exposure from the edge, deduplicated with a cookie.\n *\n * ```ts\n * // middleware.ts\n * import { splithubMiddleware } from '@splithub/next';\n * import config from './splithub.config';\n * export default splithubMiddleware(config);\n * export const config = { matcher: ['/((?!_next|api|.*\\\\..*).*)'] };\n * ```\n */\nexport function splithubMiddleware(baseConfig: SplitHubConfig, options: MiddlewareOptions = {}) {\n const exclude = options.exclude ?? defaultExclude;\n const trackRedirects = options.trackRedirects ?? true;\n const useRemote = options.remote ?? true;\n\n return async function middleware(request: NextRequest, event?: NextFetchEvent): Promise<NextResponse> {\n const pathname = request.nextUrl.pathname;\n if (exclude(pathname)) return NextResponse.next();\n\n const config = useRemote ? applyRemoteOverrides(baseConfig, await getRemoteOverrides(baseConfig)) : baseConfig;\n\n let visitorId = request.cookies.get(config.visitorKey)?.value ?? null;\n const isNewVisitor = !visitorId;\n if (!visitorId) visitorId = newVisitorId();\n\n const overrides = parseForceParam(request.nextUrl.search);\n const context = requestContext(request.headers, request.nextUrl.href, isNewVisitor ? 'new' : 'returning');\n const requestHeaders = new Headers(request.headers);\n requestHeaders.set(VISITOR_HEADER, visitorId);\n\n let response: NextResponse | null = null;\n const cookiesToSet: Array<{ name: string; value: string }> = [];\n\n // The same decision as sh.js; in development, say why a matching test did nothing.\n // A visitor who reaches a running redirect test also joins the holdout comparison (same rule as the SDK).\n let reachedTest = false as boolean;\n const decision = decideRedirect(config, pathname, visitorId, context, overrides, (exp, a) => {\n if (countsForHoldout(a)) reachedTest = true;\n explainAssignment(exp, a);\n });\n // Development never sends to the cloud (the developer is not a visitor); a self-hosted store records it, dev drafts included.\n // Bots never reach here with a variant: assign gives them the control without one.\n const cloudDev = config.storage.mode === 'cloud' && isDevEnvironment();\n const events: ExposureEvent[] = [];\n // This request is the page load, so its Referer is where the visitor came from (the ingest\n // only sees this server). Same-site navigation says nothing about the source: left out.\n const ref = referrerOrigin(request.headers.get('referer'), request.nextUrl.host);\n const refField = ref === undefined ? {} : { ref };\n if (decision) {\n if (decision.to) {\n const target = redirectTarget(decision.to, request.nextUrl.href);\n let url: URL = target;\n if (target.origin === request.nextUrl.origin) {\n // Keep Next's own URL (basePath, locale) and change only what the variant says.\n const next = request.nextUrl.clone();\n next.pathname = target.pathname;\n next.search = target.search;\n url = next;\n }\n response = NextResponse.rewrite(url, { request: { headers: requestHeaders } });\n }\n\n const exposureCookie = `sh_x_${decision.experiment}`;\n const record = !cloudDev && (decision.reason === 'assigned' || (decision.reason === 'dev' && config.storage.mode === 'self'));\n if (trackRedirects && record && request.cookies.get(exposureCookie)?.value !== decision.variant) {\n cookiesToSet.push({ name: exposureCookie, value: decision.variant });\n events.push({ id: newId('e_'), type: 'exposure', exp: decision.experiment, var: decision.variant, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname, ...refField });\n }\n }\n const group = reachedTest ? holdoutGroup(config, visitorId) : null;\n if (group && trackRedirects && !cloudDev && request.cookies.get(`sh_x_${HOLDOUT_KEY}`)?.value !== group) {\n cookiesToSet.push({ name: `sh_x_${HOLDOUT_KEY}`, value: group });\n events.push({ id: newId('e_'), type: 'exposure', exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname, ...refField });\n }\n if (events.length) {\n const target = ingestTarget(config, request.nextUrl.origin);\n const batch: EventBatch = { project: config.project, sdk: `next/${SDK_VERSION}`, events };\n const headers: Record<string, string> = { 'content-type': 'application/json' };\n if (target.key) headers.authorization = `Bearer ${target.key}`;\n // The visitor's user agent, so the ingest's bot filter judges the visitor, not this server.\n // `x-splithub-ua` too, for runtimes that replace a user-agent set on fetch.\n const ua = request.headers.get('user-agent');\n if (ua) {\n headers['user-agent'] = ua;\n headers['x-splithub-ua'] = ua;\n }\n const send = fetch(target.url, { method: 'POST', headers, body: JSON.stringify(batch) }).catch(() => undefined);\n if (event?.waitUntil) event.waitUntil(send);\n }\n\n response ??= NextResponse.next({ request: { headers: requestHeaders } });\n\n if (isNewVisitor) {\n response.cookies.set(config.visitorKey, visitorId, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n }\n for (const c of cookiesToSet) response.cookies.set(c.name, c.value, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n return response;\n };\n}\n"],"mappings":";AAAA,SAAS,gBAAgB,sBAAsB,qBAAqB,qBAAgE;AAUpI,IAAM,OAAO,oBAAI,IAAuB;AAaxC,eAAsB,mBAAmB,QAAwB,UAAyB,CAAC,GAAoC;AAC7H,MAAI,OAAO,QAAQ,SAAS,WAAW,CAAC,OAAO,QAAQ,IAAK,QAAO;AACnE,QAAM,MAAM,QAAQ,SAAS;AAC7B,QAAM,MAAM,oBAAoB,OAAO,QAAQ,YAAY,gBAAgB,OAAO,QAAQ,GAAG;AAC7F,QAAM,QAAQ,KAAK,IAAI,GAAG;AAC1B,QAAM,MAAM,KAAK,IAAI;AACrB,MAAI,SAAS,MAAM,MAAM,KAAK,IAAK,QAAO,MAAM;AAChD,MAAI,OAAO,QAAS,QAAO,MAAM,SAAS,MAAM;AAEhD,QAAM,UAAU,qBAAqB,KA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,UAAU,MAAM,KAAK,UAAU,MAAM,CAAC;AAAA,IACrG;AACA,eAAW,KAAK,aAAc,UAAS,QAAQ,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,UAAU,MAAM,KAAK,UAAU,MAAM,CAAC;AACpH,WAAO;AAAA,EACT;AACF;","names":["CLOUD_ENDPOINT","CLOUD_ENDPOINT"]}
package/dist/client.cjs CHANGED
@@ -27,6 +27,7 @@ __export(client_exports, {
27
27
  SplitHubNextProvider: () => SplitHubNextProvider,
28
28
  SplitHubProvider: () => import_react3.SplitHubProvider,
29
29
  Variant: () => import_react3.Variant,
30
+ useIdentify: () => import_react3.useIdentify,
30
31
  usePageview: () => import_react3.usePageview,
31
32
  useSplitHub: () => import_react3.useSplitHub,
32
33
  useTrack: () => import_react3.useTrack,
@@ -56,6 +57,7 @@ function Exposure({ id }) {
56
57
  SplitHubNextProvider,
57
58
  SplitHubProvider,
58
59
  Variant,
60
+ useIdentify,
59
61
  usePageview,
60
62
  useSplitHub,
61
63
  useTrack,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.tsx"],"sourcesContent":["'use client';\n\nimport type { RemoteOverrides } from '@splithub/core';\nimport { SplitHubProvider, useSplitHub, type SplitHubProviderProps } from '@splithub/react';\nimport { useEffect } from 'react';\n\nexport { SplitHubProvider, useSplitHub, Experiment, Variant, useVariant, useValue, useTrack, usePageview } from '@splithub/react';\n\nexport interface SplitHubNextProviderProps extends SplitHubProviderProps {\n /** Overrides the server applied (`(await getSplitHub(config)).overrides`), so client and server agree. */\n remoteOverrides?: RemoteOverrides | null;\n}\n\n/**\n * Same as SplitHubProvider; pass `visitorId` from the server layout so SSR\n * and hydration agree:\n *\n * ```tsx\n * // app/layout.tsx (server component)\n * const sh = await getSplitHub(config);\n * <SplitHubNextProvider config={config} visitorId={sh.visitorId ?? undefined} remoteOverrides={sh.overrides}>{children}</SplitHubNextProvider>\n * ```\n */\nexport function SplitHubNextProvider({ remoteOverrides, remote, ...props }: SplitHubNextProviderProps) {\n // The HTML is already decided on the server: never wait for overrides here, or the\n // first client render (control) would disagree with it.\n const remoteOptions = { waitMs: 0, ...(remote ?? {}), ...(remoteOverrides !== undefined ? { overrides: remoteOverrides } : {}) };\n return <SplitHubProvider {...props} remote={remoteOptions} />;\n}\n\n/** Records an exposure for an experiment rendered by a Server Component. */\nexport function Exposure({ id }: { id: string }) {\n const client = useSplitHub();\n useEffect(() => {\n client.exposure(id);\n }, [client, id]);\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAA0E;AAC1E,IAAAA,gBAA0B;AAE1B,IAAAA,gBAAgH;AAqBvG;AAJF,SAAS,qBAAqB,EAAE,iBAAiB,QAAQ,GAAG,MAAM,GAA8B;AAGrG,QAAM,gBAAgB,EAAE,QAAQ,GAAG,GAAI,UAAU,CAAC,GAAI,GAAI,oBAAoB,SAAY,EAAE,WAAW,gBAAgB,IAAI,CAAC,EAAG;AAC/H,SAAO,4CAAC,iCAAkB,GAAG,OAAO,QAAQ,eAAe;AAC7D;AAGO,SAAS,SAAS,EAAE,GAAG,GAAmB;AAC/C,QAAM,aAAS,0BAAY;AAC3B,+BAAU,MAAM;AACd,WAAO,SAAS,EAAE;AAAA,EACpB,GAAG,CAAC,QAAQ,EAAE,CAAC;AACf,SAAO;AACT;","names":["import_react"]}
1
+ {"version":3,"sources":["../src/client.tsx"],"sourcesContent":["'use client';\n\nimport type { RemoteOverrides } from '@splithub/core';\nimport { SplitHubProvider, useSplitHub, type SplitHubProviderProps } from '@splithub/react';\nimport { useEffect } from 'react';\n\nexport { SplitHubProvider, useSplitHub, Experiment, Variant, useVariant, useValue, useTrack, usePageview, useIdentify } from '@splithub/react';\n\nexport interface SplitHubNextProviderProps extends SplitHubProviderProps {\n /** Overrides the server applied (`(await getSplitHub(config)).overrides`), so client and server agree. */\n remoteOverrides?: RemoteOverrides | null;\n}\n\n/**\n * Same as SplitHubProvider; pass `visitorId` from the server layout so SSR\n * and hydration agree:\n *\n * ```tsx\n * // app/layout.tsx (server component)\n * const sh = await getSplitHub(config);\n * <SplitHubNextProvider config={config} visitorId={sh.visitorId ?? undefined} remoteOverrides={sh.overrides}>{children}</SplitHubNextProvider>\n * ```\n */\nexport function SplitHubNextProvider({ remoteOverrides, remote, ...props }: SplitHubNextProviderProps) {\n // The HTML is already decided on the server: never wait for overrides here, or the\n // first client render (control) would disagree with it.\n const remoteOptions = { waitMs: 0, ...(remote ?? {}), ...(remoteOverrides !== undefined ? { overrides: remoteOverrides } : {}) };\n return <SplitHubProvider {...props} remote={remoteOptions} />;\n}\n\n/** Records an exposure for an experiment rendered by a Server Component. */\nexport function Exposure({ id }: { id: string }) {\n const client = useSplitHub();\n useEffect(() => {\n client.exposure(id);\n }, [client, id]);\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAA0E;AAC1E,IAAAA,gBAA0B;AAE1B,IAAAA,gBAA6H;AAqBpH;AAJF,SAAS,qBAAqB,EAAE,iBAAiB,QAAQ,GAAG,MAAM,GAA8B;AAGrG,QAAM,gBAAgB,EAAE,QAAQ,GAAG,GAAI,UAAU,CAAC,GAAI,GAAI,oBAAoB,SAAY,EAAE,WAAW,gBAAgB,IAAI,CAAC,EAAG;AAC/H,SAAO,4CAAC,iCAAkB,GAAG,OAAO,QAAQ,eAAe;AAC7D;AAGO,SAAS,SAAS,EAAE,GAAG,GAAmB;AAC/C,QAAM,aAAS,0BAAY;AAC3B,+BAAU,MAAM;AACd,WAAO,SAAS,EAAE;AAAA,EACpB,GAAG,CAAC,QAAQ,EAAE,CAAC;AACf,SAAO;AACT;","names":["import_react"]}
package/dist/client.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { RemoteOverrides } from '@splithub/core';
3
3
  import { SplitHubProviderProps } from '@splithub/react';
4
- export { Experiment, SplitHubProvider, Variant, usePageview, useSplitHub, useTrack, useValue, useVariant } from '@splithub/react';
4
+ export { Experiment, SplitHubProvider, Variant, useIdentify, usePageview, useSplitHub, useTrack, useValue, useVariant } from '@splithub/react';
5
5
 
6
6
  interface SplitHubNextProviderProps extends SplitHubProviderProps {
7
7
  /** Overrides the server applied (`(await getSplitHub(config)).overrides`), so client and server agree. */
package/dist/client.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { RemoteOverrides } from '@splithub/core';
3
3
  import { SplitHubProviderProps } from '@splithub/react';
4
- export { Experiment, SplitHubProvider, Variant, usePageview, useSplitHub, useTrack, useValue, useVariant } from '@splithub/react';
4
+ export { Experiment, SplitHubProvider, Variant, useIdentify, usePageview, useSplitHub, useTrack, useValue, useVariant } from '@splithub/react';
5
5
 
6
6
  interface SplitHubNextProviderProps extends SplitHubProviderProps {
7
7
  /** Overrides the server applied (`(await getSplitHub(config)).overrides`), so client and server agree. */
package/dist/client.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // src/client.tsx
5
5
  import { SplitHubProvider, useSplitHub } from "@splithub/react";
6
6
  import { useEffect } from "react";
7
- import { SplitHubProvider as SplitHubProvider2, useSplitHub as useSplitHub2, Experiment, Variant, useVariant, useValue, useTrack, usePageview } from "@splithub/react";
7
+ import { SplitHubProvider as SplitHubProvider2, useSplitHub as useSplitHub2, Experiment, Variant, useVariant, useValue, useTrack, usePageview, useIdentify } from "@splithub/react";
8
8
  import { jsx } from "react/jsx-runtime";
9
9
  function SplitHubNextProvider({ remoteOverrides, remote, ...props }) {
10
10
  const remoteOptions = { waitMs: 0, ...remote ?? {}, ...remoteOverrides !== void 0 ? { overrides: remoteOverrides } : {} };
@@ -23,6 +23,7 @@ export {
23
23
  SplitHubNextProvider,
24
24
  SplitHubProvider2 as SplitHubProvider,
25
25
  Variant,
26
+ useIdentify,
26
27
  usePageview,
27
28
  useSplitHub2 as useSplitHub,
28
29
  useTrack,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.tsx"],"sourcesContent":["'use client';\n\nimport type { RemoteOverrides } from '@splithub/core';\nimport { SplitHubProvider, useSplitHub, type SplitHubProviderProps } from '@splithub/react';\nimport { useEffect } from 'react';\n\nexport { SplitHubProvider, useSplitHub, Experiment, Variant, useVariant, useValue, useTrack, usePageview } from '@splithub/react';\n\nexport interface SplitHubNextProviderProps extends SplitHubProviderProps {\n /** Overrides the server applied (`(await getSplitHub(config)).overrides`), so client and server agree. */\n remoteOverrides?: RemoteOverrides | null;\n}\n\n/**\n * Same as SplitHubProvider; pass `visitorId` from the server layout so SSR\n * and hydration agree:\n *\n * ```tsx\n * // app/layout.tsx (server component)\n * const sh = await getSplitHub(config);\n * <SplitHubNextProvider config={config} visitorId={sh.visitorId ?? undefined} remoteOverrides={sh.overrides}>{children}</SplitHubNextProvider>\n * ```\n */\nexport function SplitHubNextProvider({ remoteOverrides, remote, ...props }: SplitHubNextProviderProps) {\n // The HTML is already decided on the server: never wait for overrides here, or the\n // first client render (control) would disagree with it.\n const remoteOptions = { waitMs: 0, ...(remote ?? {}), ...(remoteOverrides !== undefined ? { overrides: remoteOverrides } : {}) };\n return <SplitHubProvider {...props} remote={remoteOptions} />;\n}\n\n/** Records an exposure for an experiment rendered by a Server Component. */\nexport function Exposure({ id }: { id: string }) {\n const client = useSplitHub();\n useEffect(() => {\n client.exposure(id);\n }, [client, id]);\n return null;\n}\n"],"mappings":";;;;AAGA,SAAS,kBAAkB,mBAA+C;AAC1E,SAAS,iBAAiB;AAE1B,SAAS,oBAAAA,mBAAkB,eAAAC,cAAa,YAAY,SAAS,YAAY,UAAU,UAAU,mBAAmB;AAqBvG;AAJF,SAAS,qBAAqB,EAAE,iBAAiB,QAAQ,GAAG,MAAM,GAA8B;AAGrG,QAAM,gBAAgB,EAAE,QAAQ,GAAG,GAAI,UAAU,CAAC,GAAI,GAAI,oBAAoB,SAAY,EAAE,WAAW,gBAAgB,IAAI,CAAC,EAAG;AAC/H,SAAO,oBAAC,oBAAkB,GAAG,OAAO,QAAQ,eAAe;AAC7D;AAGO,SAAS,SAAS,EAAE,GAAG,GAAmB;AAC/C,QAAM,SAAS,YAAY;AAC3B,YAAU,MAAM;AACd,WAAO,SAAS,EAAE;AAAA,EACpB,GAAG,CAAC,QAAQ,EAAE,CAAC;AACf,SAAO;AACT;","names":["SplitHubProvider","useSplitHub"]}
1
+ {"version":3,"sources":["../src/client.tsx"],"sourcesContent":["'use client';\n\nimport type { RemoteOverrides } from '@splithub/core';\nimport { SplitHubProvider, useSplitHub, type SplitHubProviderProps } from '@splithub/react';\nimport { useEffect } from 'react';\n\nexport { SplitHubProvider, useSplitHub, Experiment, Variant, useVariant, useValue, useTrack, usePageview, useIdentify } from '@splithub/react';\n\nexport interface SplitHubNextProviderProps extends SplitHubProviderProps {\n /** Overrides the server applied (`(await getSplitHub(config)).overrides`), so client and server agree. */\n remoteOverrides?: RemoteOverrides | null;\n}\n\n/**\n * Same as SplitHubProvider; pass `visitorId` from the server layout so SSR\n * and hydration agree:\n *\n * ```tsx\n * // app/layout.tsx (server component)\n * const sh = await getSplitHub(config);\n * <SplitHubNextProvider config={config} visitorId={sh.visitorId ?? undefined} remoteOverrides={sh.overrides}>{children}</SplitHubNextProvider>\n * ```\n */\nexport function SplitHubNextProvider({ remoteOverrides, remote, ...props }: SplitHubNextProviderProps) {\n // The HTML is already decided on the server: never wait for overrides here, or the\n // first client render (control) would disagree with it.\n const remoteOptions = { waitMs: 0, ...(remote ?? {}), ...(remoteOverrides !== undefined ? { overrides: remoteOverrides } : {}) };\n return <SplitHubProvider {...props} remote={remoteOptions} />;\n}\n\n/** Records an exposure for an experiment rendered by a Server Component. */\nexport function Exposure({ id }: { id: string }) {\n const client = useSplitHub();\n useEffect(() => {\n client.exposure(id);\n }, [client, id]);\n return null;\n}\n"],"mappings":";;;;AAGA,SAAS,kBAAkB,mBAA+C;AAC1E,SAAS,iBAAiB;AAE1B,SAAS,oBAAAA,mBAAkB,eAAAC,cAAa,YAAY,SAAS,YAAY,UAAU,UAAU,aAAa,mBAAmB;AAqBpH;AAJF,SAAS,qBAAqB,EAAE,iBAAiB,QAAQ,GAAG,MAAM,GAA8B;AAGrG,QAAM,gBAAgB,EAAE,QAAQ,GAAG,GAAI,UAAU,CAAC,GAAI,GAAI,oBAAoB,SAAY,EAAE,WAAW,gBAAgB,IAAI,CAAC,EAAG;AAC/H,SAAO,oBAAC,oBAAkB,GAAG,OAAO,QAAQ,eAAe;AAC7D;AAGO,SAAS,SAAS,EAAE,GAAG,GAAmB;AAC/C,QAAM,SAAS,YAAY;AAC3B,YAAU,MAAM;AACd,WAAO,SAAS,EAAE;AAAA,EACpB,GAAG,CAAC,QAAQ,EAAE,CAAC;AACf,SAAO;AACT;","names":["SplitHubProvider","useSplitHub"]}
package/dist/index.cjs CHANGED
@@ -110,6 +110,8 @@ function splithubMiddleware(baseConfig, options = {}) {
110
110
  });
111
111
  const cloudDev = config.storage.mode === "cloud" && (0, import_core2.isDevEnvironment)();
112
112
  const events = [];
113
+ const ref = (0, import_core2.referrerOrigin)(request.headers.get("referer"), request.nextUrl.host);
114
+ const refField = ref === void 0 ? {} : { ref };
113
115
  if (decision) {
114
116
  if (decision.to) {
115
117
  const target = (0, import_core2.redirectTarget)(decision.to, request.nextUrl.href);
@@ -126,13 +128,13 @@ function splithubMiddleware(baseConfig, options = {}) {
126
128
  const record = !cloudDev && (decision.reason === "assigned" || decision.reason === "dev" && config.storage.mode === "self");
127
129
  if (trackRedirects && record && request.cookies.get(exposureCookie)?.value !== decision.variant) {
128
130
  cookiesToSet.push({ name: exposureCookie, value: decision.variant });
129
- events.push({ id: (0, import_core2.newId)("e_"), type: "exposure", exp: decision.experiment, var: decision.variant, vid: visitorId, sid: "edge", ts: Date.now(), url: pathname });
131
+ events.push({ id: (0, import_core2.newId)("e_"), type: "exposure", exp: decision.experiment, var: decision.variant, vid: visitorId, sid: "edge", ts: Date.now(), url: pathname, ...refField });
130
132
  }
131
133
  }
132
134
  const group = reachedTest ? (0, import_core2.holdoutGroup)(config, visitorId) : null;
133
135
  if (group && trackRedirects && !cloudDev && request.cookies.get(`sh_x_${import_core2.HOLDOUT_KEY}`)?.value !== group) {
134
136
  cookiesToSet.push({ name: `sh_x_${import_core2.HOLDOUT_KEY}`, value: group });
135
- events.push({ id: (0, import_core2.newId)("e_"), type: "exposure", exp: import_core2.HOLDOUT_KEY, var: group, vid: visitorId, sid: "edge", ts: Date.now(), url: pathname });
137
+ events.push({ id: (0, import_core2.newId)("e_"), type: "exposure", exp: import_core2.HOLDOUT_KEY, var: group, vid: visitorId, sid: "edge", ts: Date.now(), url: pathname, ...refField });
136
138
  }
137
139
  if (events.length) {
138
140
  const target = ingestTarget(config, request.nextUrl.origin);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/middleware.ts","../src/remote.ts"],"sourcesContent":["export { splithubMiddleware, matchPath, VISITOR_HEADER } from './middleware';\nexport type { MiddlewareOptions } from './middleware';\nexport { getRemoteOverrides, clearRemoteMemo } from './remote';\nexport { defineConfig } from '@splithub/core';\nexport type { SplitHubConfig, SplitHubConfigInput } from '@splithub/core';\n","import {\n applyRemoteOverrides,\n CLOUD_ENDPOINT,\n countsForHoldout,\n decideRedirect,\n explainAssignment,\n HOLDOUT_KEY,\n holdoutGroup,\n isDevEnvironment,\n matchPath,\n newId,\n newVisitorId,\n parseCookies,\n parseForceParam,\n parseUserAgent,\n redirectTarget,\n SDK_VERSION,\n type EventBatch,\n type ExposureEvent,\n type SplitHubConfig,\n type TargetingContext,\n} from '@splithub/core';\nimport { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';\nimport { getRemoteOverrides } from './remote';\n\nexport const VISITOR_HEADER = 'x-splithub-vid';\nconst ONE_YEAR = 60 * 60 * 24 * 365;\n\nexport interface MiddlewareOptions {\n /** Return true to skip a path entirely. Defaults to `_next`, `api` and files with an extension. */\n exclude?: (pathname: string) => boolean;\n /** Send exposures for redirect experiments from the edge. Default true. */\n trackRedirects?: boolean;\n /** Apply live overrides from the cloud (cloud mode only). Default true. */\n remote?: boolean;\n}\n\nfunction defaultExclude(pathname: string): boolean {\n return pathname.startsWith('/_next') || pathname.startsWith('/api/') || /\\.[a-z0-9]+$/i.test(pathname);\n}\n\n/** Same rule as sh.js and pageview goals (from `@splithub/core`). */\nexport { matchPath };\n\n/**\n * Targeting context from request headers: Cloudflare / Vercel geo, user agent, language,\n * referrer, cookies. `timezone` (for `hour` / `weekday`) comes from Vercel's\n * `x-vercel-ip-timezone` or a `cf-timezone` / `x-timezone` header you set; without one\n * the flow uses UTC.\n */\nexport function requestContext(headers: Headers, url: string, visitor?: 'new' | 'returning'): TargetingContext {\n const ua = parseUserAgent(headers.get('user-agent'));\n const country = headers.get('cf-ipcountry') ?? headers.get('x-vercel-ip-country') ?? headers.get('x-country') ?? undefined;\n const region = headers.get('x-vercel-ip-country-region') ?? headers.get('cf-region') ?? undefined;\n const city = headers.get('x-vercel-ip-city') ?? headers.get('cf-ipcity') ?? undefined;\n const timezone = headers.get('x-vercel-ip-timezone') ?? headers.get('cf-timezone') ?? headers.get('x-timezone') ?? undefined;\n return {\n country: country ?? undefined,\n region: region ? decodeURIComponent(region) : undefined,\n city: city ? decodeURIComponent(city) : undefined,\n device: ua.device,\n browser: ua.browser,\n os: ua.os,\n language: headers.get('accept-language') ?? undefined,\n referrer: headers.get('referer') ?? undefined,\n url,\n cookies: parseCookies(headers.get('cookie')),\n ...(timezone ? { timezone } : {}),\n ...(visitor ? { visitor } : {}),\n };\n}\n\nfunction ingestTarget(config: SplitHubConfig, origin: string): { url: string; key?: string } {\n if (config.storage.mode === 'self') return { url: new URL(config.storage.endpoint, origin).toString() };\n return { url: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\n/**\n * Next.js middleware:\n * 1. ensures the `sh_vid` visitor cookie, so SSR and the client agree on variants;\n * 2. forwards the visitor id to Server Components via the `x-splithub-vid` header;\n * 3. serves redirect experiments with an invisible rewrite (URL unchanged, no flash);\n * 4. records the redirect exposure from the edge, deduplicated with a cookie.\n *\n * ```ts\n * // middleware.ts\n * import { splithubMiddleware } from '@splithub/next';\n * import config from './splithub.config';\n * export default splithubMiddleware(config);\n * export const config = { matcher: ['/((?!_next|api|.*\\\\..*).*)'] };\n * ```\n */\nexport function splithubMiddleware(baseConfig: SplitHubConfig, options: MiddlewareOptions = {}) {\n const exclude = options.exclude ?? defaultExclude;\n const trackRedirects = options.trackRedirects ?? true;\n const useRemote = options.remote ?? true;\n\n return async function middleware(request: NextRequest, event?: NextFetchEvent): Promise<NextResponse> {\n const pathname = request.nextUrl.pathname;\n if (exclude(pathname)) return NextResponse.next();\n\n const config = useRemote ? applyRemoteOverrides(baseConfig, await getRemoteOverrides(baseConfig)) : baseConfig;\n\n let visitorId = request.cookies.get(config.visitorKey)?.value ?? null;\n const isNewVisitor = !visitorId;\n if (!visitorId) visitorId = newVisitorId();\n\n const overrides = parseForceParam(request.nextUrl.search);\n const context = requestContext(request.headers, request.nextUrl.href, isNewVisitor ? 'new' : 'returning');\n const requestHeaders = new Headers(request.headers);\n requestHeaders.set(VISITOR_HEADER, visitorId);\n\n let response: NextResponse | null = null;\n const cookiesToSet: Array<{ name: string; value: string }> = [];\n\n // The same decision as sh.js; in development, say why a matching test did nothing.\n // A visitor who reaches a running redirect test also joins the holdout comparison (same rule as the SDK).\n let reachedTest = false as boolean;\n const decision = decideRedirect(config, pathname, visitorId, context, overrides, (exp, a) => {\n if (countsForHoldout(a)) reachedTest = true;\n explainAssignment(exp, a);\n });\n // Development never sends to the cloud (the developer is not a visitor); a self-hosted store records it, dev drafts included.\n // Bots never reach here with a variant: assign gives them the control without one.\n const cloudDev = config.storage.mode === 'cloud' && isDevEnvironment();\n const events: ExposureEvent[] = [];\n if (decision) {\n if (decision.to) {\n const target = redirectTarget(decision.to, request.nextUrl.href);\n let url: URL = target;\n if (target.origin === request.nextUrl.origin) {\n // Keep Next's own URL (basePath, locale) and change only what the variant says.\n const next = request.nextUrl.clone();\n next.pathname = target.pathname;\n next.search = target.search;\n url = next;\n }\n response = NextResponse.rewrite(url, { request: { headers: requestHeaders } });\n }\n\n const exposureCookie = `sh_x_${decision.experiment}`;\n const record = !cloudDev && (decision.reason === 'assigned' || (decision.reason === 'dev' && config.storage.mode === 'self'));\n if (trackRedirects && record && request.cookies.get(exposureCookie)?.value !== decision.variant) {\n cookiesToSet.push({ name: exposureCookie, value: decision.variant });\n events.push({ id: newId('e_'), type: 'exposure', exp: decision.experiment, var: decision.variant, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname });\n }\n }\n const group = reachedTest ? holdoutGroup(config, visitorId) : null;\n if (group && trackRedirects && !cloudDev && request.cookies.get(`sh_x_${HOLDOUT_KEY}`)?.value !== group) {\n cookiesToSet.push({ name: `sh_x_${HOLDOUT_KEY}`, value: group });\n events.push({ id: newId('e_'), type: 'exposure', exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname });\n }\n if (events.length) {\n const target = ingestTarget(config, request.nextUrl.origin);\n const batch: EventBatch = { project: config.project, sdk: `next/${SDK_VERSION}`, events };\n const headers: Record<string, string> = { 'content-type': 'application/json' };\n if (target.key) headers.authorization = `Bearer ${target.key}`;\n // The visitor's user agent, so the ingest's bot filter judges the visitor, not this server.\n // `x-splithub-ua` too, for runtimes that replace a user-agent set on fetch.\n const ua = request.headers.get('user-agent');\n if (ua) {\n headers['user-agent'] = ua;\n headers['x-splithub-ua'] = ua;\n }\n const send = fetch(target.url, { method: 'POST', headers, body: JSON.stringify(batch) }).catch(() => undefined);\n if (event?.waitUntil) event.waitUntil(send);\n }\n\n response ??= NextResponse.next({ request: { headers: requestHeaders } });\n\n if (isNewVisitor) {\n response.cookies.set(config.visitorKey, visitorId, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n }\n for (const c of cookiesToSet) response.cookies.set(c.name, c.value, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n return response;\n };\n}\n","import { CLOUD_ENDPOINT, fetchRemoteOverrides, resolveOverridesUrl, REMOTE_TTL_MS, type RemoteOverrides, type SplitHubConfig } from '@splithub/core';\n\ninterface MemoEntry {\n at: number;\n value: RemoteOverrides | null;\n pending: Promise<RemoteOverrides | null> | null;\n}\n\n// Module-level memo: edge isolates and Node servers keep it across requests,\n// so at most one fetch per TTL per public key.\nconst memo = new Map<string, MemoEntry>();\n\nexport interface RemoteOptions {\n ttlMs?: number;\n /** Override the fetch implementation (tests). */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Live overrides for a cloud-mode config, cached in memory for `ttlMs`\n * (default 60s). Returns null in self mode or when the cloud is unreachable\n * (the config file then applies as-is).\n */\nexport async function getRemoteOverrides(config: SplitHubConfig, options: RemoteOptions = {}): Promise<RemoteOverrides | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const ttl = options.ttlMs ?? REMOTE_TTL_MS;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const entry = memo.get(url);\n const now = Date.now();\n if (entry && now - entry.at < ttl) return entry.value;\n if (entry?.pending) return entry.value ?? entry.pending;\n\n const pending = fetchRemoteOverrides(url, options.fetchImpl).then((value) => {\n memo.set(url, { at: Date.now(), value: value ?? entry?.value ?? null, pending: null });\n return value ?? entry?.value ?? null;\n });\n memo.set(url, { at: entry?.at ?? 0, value: entry?.value ?? null, pending });\n // Serve stale while revalidating; first call waits.\n return entry ? entry.value : pending;\n}\n\n/** Tests only. */\nexport function clearRemoteMemo(): void {\n memo.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,eAqBO;AACP,oBAAoE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AE,SAAS,EAAE,SAAS,eAAe,EAAE,CAAC;AAEvE,QAAI,cAAc;AAChB,eAAS,QAAQ,IAAI,OAAO,YAAY,WAAW,EAAE,QAAQ,UAAU,MAAM,KAAK,UAAU,MAAM,CAAC;AAAA,IACrG;AACA,eAAW,KAAK,aAAc,UAAS,QAAQ,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,UAAU,MAAM,KAAK,UAAU,MAAM,CAAC;AACpH,WAAO;AAAA,EACT;AACF;;;AD7KA,IAAAC,eAA6B;","names":["import_core","import_core"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/middleware.ts","../src/remote.ts"],"sourcesContent":["export { splithubMiddleware, matchPath, VISITOR_HEADER } from './middleware';\nexport type { MiddlewareOptions } from './middleware';\nexport { getRemoteOverrides, clearRemoteMemo } from './remote';\nexport { defineConfig } from '@splithub/core';\nexport type { SplitHubConfig, SplitHubConfigInput } from '@splithub/core';\n","import {\n applyRemoteOverrides,\n CLOUD_ENDPOINT,\n countsForHoldout,\n decideRedirect,\n explainAssignment,\n HOLDOUT_KEY,\n holdoutGroup,\n isDevEnvironment,\n matchPath,\n newId,\n newVisitorId,\n parseCookies,\n parseForceParam,\n parseUserAgent,\n redirectTarget,\n referrerOrigin,\n SDK_VERSION,\n type EventBatch,\n type ExposureEvent,\n type SplitHubConfig,\n type TargetingContext,\n} from '@splithub/core';\nimport { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';\nimport { getRemoteOverrides } from './remote';\n\nexport const VISITOR_HEADER = 'x-splithub-vid';\nconst ONE_YEAR = 60 * 60 * 24 * 365;\n\nexport interface MiddlewareOptions {\n /** Return true to skip a path entirely. Defaults to `_next`, `api` and files with an extension. */\n exclude?: (pathname: string) => boolean;\n /** Send exposures for redirect experiments from the edge. Default true. */\n trackRedirects?: boolean;\n /** Apply live overrides from the cloud (cloud mode only). Default true. */\n remote?: boolean;\n}\n\nfunction defaultExclude(pathname: string): boolean {\n return pathname.startsWith('/_next') || pathname.startsWith('/api/') || /\\.[a-z0-9]+$/i.test(pathname);\n}\n\n/** Same rule as sh.js and pageview goals (from `@splithub/core`). */\nexport { matchPath };\n\n/**\n * Targeting context from request headers: Cloudflare / Vercel geo, user agent, language,\n * referrer, cookies. `timezone` (for `hour` / `weekday`) comes from Vercel's\n * `x-vercel-ip-timezone` or a `cf-timezone` / `x-timezone` header you set; without one\n * the flow uses UTC.\n */\nexport function requestContext(headers: Headers, url: string, visitor?: 'new' | 'returning'): TargetingContext {\n const ua = parseUserAgent(headers.get('user-agent'));\n const country = headers.get('cf-ipcountry') ?? headers.get('x-vercel-ip-country') ?? headers.get('x-country') ?? undefined;\n const region = headers.get('x-vercel-ip-country-region') ?? headers.get('cf-region') ?? undefined;\n const city = headers.get('x-vercel-ip-city') ?? headers.get('cf-ipcity') ?? undefined;\n const timezone = headers.get('x-vercel-ip-timezone') ?? headers.get('cf-timezone') ?? headers.get('x-timezone') ?? undefined;\n return {\n country: country ?? undefined,\n region: region ? decodeURIComponent(region) : undefined,\n city: city ? decodeURIComponent(city) : undefined,\n device: ua.device,\n browser: ua.browser,\n os: ua.os,\n language: headers.get('accept-language') ?? undefined,\n referrer: headers.get('referer') ?? undefined,\n url,\n cookies: parseCookies(headers.get('cookie')),\n ...(timezone ? { timezone } : {}),\n ...(visitor ? { visitor } : {}),\n };\n}\n\nfunction ingestTarget(config: SplitHubConfig, origin: string): { url: string; key?: string } {\n if (config.storage.mode === 'self') return { url: new URL(config.storage.endpoint, origin).toString() };\n return { url: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\n/**\n * Next.js middleware:\n * 1. ensures the `sh_vid` visitor cookie, so SSR and the client agree on variants;\n * 2. forwards the visitor id to Server Components via the `x-splithub-vid` header;\n * 3. serves redirect experiments with an invisible rewrite (URL unchanged, no flash);\n * 4. records the redirect exposure from the edge, deduplicated with a cookie.\n *\n * ```ts\n * // middleware.ts\n * import { splithubMiddleware } from '@splithub/next';\n * import config from './splithub.config';\n * export default splithubMiddleware(config);\n * export const config = { matcher: ['/((?!_next|api|.*\\\\..*).*)'] };\n * ```\n */\nexport function splithubMiddleware(baseConfig: SplitHubConfig, options: MiddlewareOptions = {}) {\n const exclude = options.exclude ?? defaultExclude;\n const trackRedirects = options.trackRedirects ?? true;\n const useRemote = options.remote ?? true;\n\n return async function middleware(request: NextRequest, event?: NextFetchEvent): Promise<NextResponse> {\n const pathname = request.nextUrl.pathname;\n if (exclude(pathname)) return NextResponse.next();\n\n const config = useRemote ? applyRemoteOverrides(baseConfig, await getRemoteOverrides(baseConfig)) : baseConfig;\n\n let visitorId = request.cookies.get(config.visitorKey)?.value ?? null;\n const isNewVisitor = !visitorId;\n if (!visitorId) visitorId = newVisitorId();\n\n const overrides = parseForceParam(request.nextUrl.search);\n const context = requestContext(request.headers, request.nextUrl.href, isNewVisitor ? 'new' : 'returning');\n const requestHeaders = new Headers(request.headers);\n requestHeaders.set(VISITOR_HEADER, visitorId);\n\n let response: NextResponse | null = null;\n const cookiesToSet: Array<{ name: string; value: string }> = [];\n\n // The same decision as sh.js; in development, say why a matching test did nothing.\n // A visitor who reaches a running redirect test also joins the holdout comparison (same rule as the SDK).\n let reachedTest = false as boolean;\n const decision = decideRedirect(config, pathname, visitorId, context, overrides, (exp, a) => {\n if (countsForHoldout(a)) reachedTest = true;\n explainAssignment(exp, a);\n });\n // Development never sends to the cloud (the developer is not a visitor); a self-hosted store records it, dev drafts included.\n // Bots never reach here with a variant: assign gives them the control without one.\n const cloudDev = config.storage.mode === 'cloud' && isDevEnvironment();\n const events: ExposureEvent[] = [];\n // This request is the page load, so its Referer is where the visitor came from (the ingest\n // only sees this server). Same-site navigation says nothing about the source: left out.\n const ref = referrerOrigin(request.headers.get('referer'), request.nextUrl.host);\n const refField = ref === undefined ? {} : { ref };\n if (decision) {\n if (decision.to) {\n const target = redirectTarget(decision.to, request.nextUrl.href);\n let url: URL = target;\n if (target.origin === request.nextUrl.origin) {\n // Keep Next's own URL (basePath, locale) and change only what the variant says.\n const next = request.nextUrl.clone();\n next.pathname = target.pathname;\n next.search = target.search;\n url = next;\n }\n response = NextResponse.rewrite(url, { request: { headers: requestHeaders } });\n }\n\n const exposureCookie = `sh_x_${decision.experiment}`;\n const record = !cloudDev && (decision.reason === 'assigned' || (decision.reason === 'dev' && config.storage.mode === 'self'));\n if (trackRedirects && record && request.cookies.get(exposureCookie)?.value !== decision.variant) {\n cookiesToSet.push({ name: exposureCookie, value: decision.variant });\n events.push({ id: newId('e_'), type: 'exposure', exp: decision.experiment, var: decision.variant, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname, ...refField });\n }\n }\n const group = reachedTest ? holdoutGroup(config, visitorId) : null;\n if (group && trackRedirects && !cloudDev && request.cookies.get(`sh_x_${HOLDOUT_KEY}`)?.value !== group) {\n cookiesToSet.push({ name: `sh_x_${HOLDOUT_KEY}`, value: group });\n events.push({ id: newId('e_'), type: 'exposure', exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname, ...refField });\n }\n if (events.length) {\n const target = ingestTarget(config, request.nextUrl.origin);\n const batch: EventBatch = { project: config.project, sdk: `next/${SDK_VERSION}`, events };\n const headers: Record<string, string> = { 'content-type': 'application/json' };\n if (target.key) headers.authorization = `Bearer ${target.key}`;\n // The visitor's user agent, so the ingest's bot filter judges the visitor, not this server.\n // `x-splithub-ua` too, for runtimes that replace a user-agent set on fetch.\n const ua = request.headers.get('user-agent');\n if (ua) {\n headers['user-agent'] = ua;\n headers['x-splithub-ua'] = ua;\n }\n const send = fetch(target.url, { method: 'POST', headers, body: JSON.stringify(batch) }).catch(() => undefined);\n if (event?.waitUntil) event.waitUntil(send);\n }\n\n response ??= NextResponse.next({ request: { headers: requestHeaders } });\n\n if (isNewVisitor) {\n response.cookies.set(config.visitorKey, visitorId, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n }\n for (const c of cookiesToSet) response.cookies.set(c.name, c.value, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n return response;\n };\n}\n","import { CLOUD_ENDPOINT, fetchRemoteOverrides, resolveOverridesUrl, REMOTE_TTL_MS, type RemoteOverrides, type SplitHubConfig } from '@splithub/core';\n\ninterface MemoEntry {\n at: number;\n value: RemoteOverrides | null;\n pending: Promise<RemoteOverrides | null> | null;\n}\n\n// Module-level memo: edge isolates and Node servers keep it across requests,\n// so at most one fetch per TTL per public key.\nconst memo = new Map<string, MemoEntry>();\n\nexport interface RemoteOptions {\n ttlMs?: number;\n /** Override the fetch implementation (tests). */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Live overrides for a cloud-mode config, cached in memory for `ttlMs`\n * (default 60s). Returns null in self mode or when the cloud is unreachable\n * (the config file then applies as-is).\n */\nexport async function getRemoteOverrides(config: SplitHubConfig, options: RemoteOptions = {}): Promise<RemoteOverrides | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const ttl = options.ttlMs ?? REMOTE_TTL_MS;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const entry = memo.get(url);\n const now = Date.now();\n if (entry && now - entry.at < ttl) return entry.value;\n if (entry?.pending) return entry.value ?? entry.pending;\n\n const pending = fetchRemoteOverrides(url, options.fetchImpl).then((value) => {\n memo.set(url, { at: Date.now(), value: value ?? entry?.value ?? null, pending: null });\n return value ?? entry?.value ?? null;\n });\n memo.set(url, { at: entry?.at ?? 0, value: entry?.value ?? null, pending });\n // Serve stale while revalidating; first call waits.\n return entry ? entry.value : pending;\n}\n\n/** Tests only. */\nexport function clearRemoteMemo(): void {\n memo.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,eAsBO;AACP,oBAAoE;;;ACvBpE,kBAAoI;AAUpI,IAAM,OAAO,oBAAI,IAAuB;AAaxC,eAAsB,mBAAmB,QAAwB,UAAyB,CAAC,GAAoC;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M,UAAU,IAAI;AAAA,IAC5C;AAEA,4BAAa,2BAAa,KAAK,EAAE,SAAS,EAAE,SAAS,eAAe,EAAE,CAAC;AAEvE,QAAI,cAAc;AAChB,eAAS,QAAQ,IAAI,OAAO,YAAY,WAAW,EAAE,QAAQ,UAAU,MAAM,KAAK,UAAU,MAAM,CAAC;AAAA,IACrG;AACA,eAAW,KAAK,aAAc,UAAS,QAAQ,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,UAAU,MAAM,KAAK,UAAU,MAAM,CAAC;AACpH,WAAO;AAAA,EACT;AACF;;;ADlLA,IAAAC,eAA6B;","names":["import_core","import_core"]}
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  getRemoteOverrides,
5
5
  matchPath,
6
6
  splithubMiddleware
7
- } from "./chunk-BH4ACCFH.js";
7
+ } from "./chunk-S5V4VC56.js";
8
8
 
9
9
  // src/index.ts
10
10
  import { defineConfig } from "@splithub/core";
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts","../src/remote.ts","../src/middleware.ts"],"sourcesContent":["import { applyRemoteOverrides, assign, explainAssignment, getExperiment, type Assignment, type RemoteOverrides, type SplitHubConfig, type TargetingContext } from '@splithub/core';\nimport { getRemoteOverrides } from './remote';\nimport { cookies, headers } from 'next/headers';\nimport { requestContext, VISITOR_HEADER } from './middleware';\n\nexport { getRemoteOverrides } from './remote';\n\n/**\n * Visitor id for the current request (header set by the middleware, else the\n * cookie). Null when the middleware is not installed and no cookie exists.\n */\nexport async function getVisitorId(config: SplitHubConfig): Promise<string | null> {\n const h = await headers();\n const fromHeader = h.get(VISITOR_HEADER);\n if (fromHeader) return fromHeader;\n const c = await cookies();\n return c.get(config.visitorKey)?.value ?? null;\n}\n\nexport interface ServerSplitHub {\n visitorId: string | null;\n /** Targeting context built from the request headers (geo, device, language, referrer). */\n context: TargetingContext;\n /** Live overrides applied to this request; pass them to <SplitHubNextProvider remoteOverrides={...}> so hydration agrees. */\n overrides: RemoteOverrides | null;\n /** Config with overrides applied. */\n config: SplitHubConfig;\n assignment(experimentKey: string): Assignment;\n /** Variant key; control when unassigned. No exposure is recorded on the server: render `<Exposure id>` from `@splithub/next/client`. */\n variant(experimentKey: string): string;\n value<T = unknown>(experimentKey: string): T;\n}\n\n/**\n * Assignments inside Server Components and Route Handlers:\n *\n * ```tsx\n * const sh = await getSplitHub(config);\n * const title = sh.value<string>('hero-title');\n * ```\n */\nexport async function getSplitHub(baseConfig: SplitHubConfig): Promise<ServerSplitHub> {\n const [visitorId, fetched] = await Promise.all([getVisitorId(baseConfig), getRemoteOverrides(baseConfig)]);\n const config = applyRemoteOverrides(baseConfig, fetched);\n const h = await headers();\n const context: TargetingContext = requestContext(h, h.get('x-url') ?? h.get('referer') ?? '');\n // The overrides were fetched (and memoized) by this server, so their `ctx` is the server's\n // location, not the visitor's. Hand the browser the visitor's geo from the request headers\n // instead, so the client provider decides geo targeting exactly as this render did.\n const geo = Object.fromEntries(\n (['country', 'region', 'city', 'timezone'] as const).filter((k) => context[k]).map((k) => [k, context[k]])\n ) as NonNullable<RemoteOverrides['ctx']>;\n const overrides: RemoteOverrides | null = fetched ? { ...fetched, ctx: geo } : Object.keys(geo).length ? { version: 0, experiments: {}, ctx: geo } : null;\n const control = (key: string) => getExperiment(config, key)?.variants[0];\n const opts = { context };\n // Assign and, in development, explain a surprising result in the terminal.\n const decide = (key: string) => {\n if (!visitorId) return null;\n const a = assign(config, key, visitorId, opts);\n explainAssignment(getExperiment(config, key), a);\n return a;\n };\n return {\n visitorId,\n context,\n overrides,\n config,\n assignment(key) {\n return decide(key) ?? { experiment: key, variant: null, reason: 'not_running' };\n },\n variant(key) {\n const a = decide(key);\n return (a?.variant ?? control(key))?.key ?? 'control';\n },\n value<T>(key: string): T {\n const a = decide(key);\n return (a?.variant ?? control(key))?.value as T;\n },\n };\n}\n","import { CLOUD_ENDPOINT, fetchRemoteOverrides, resolveOverridesUrl, REMOTE_TTL_MS, type RemoteOverrides, type SplitHubConfig } from '@splithub/core';\n\ninterface MemoEntry {\n at: number;\n value: RemoteOverrides | null;\n pending: Promise<RemoteOverrides | null> | null;\n}\n\n// Module-level memo: edge isolates and Node servers keep it across requests,\n// so at most one fetch per TTL per public key.\nconst memo = new Map<string, MemoEntry>();\n\nexport interface RemoteOptions {\n ttlMs?: number;\n /** Override the fetch implementation (tests). */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Live overrides for a cloud-mode config, cached in memory for `ttlMs`\n * (default 60s). Returns null in self mode or when the cloud is unreachable\n * (the config file then applies as-is).\n */\nexport async function getRemoteOverrides(config: SplitHubConfig, options: RemoteOptions = {}): Promise<RemoteOverrides | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const ttl = options.ttlMs ?? REMOTE_TTL_MS;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const entry = memo.get(url);\n const now = Date.now();\n if (entry && now - entry.at < ttl) return entry.value;\n if (entry?.pending) return entry.value ?? entry.pending;\n\n const pending = fetchRemoteOverrides(url, options.fetchImpl).then((value) => {\n memo.set(url, { at: Date.now(), value: value ?? entry?.value ?? null, pending: null });\n return value ?? entry?.value ?? null;\n });\n memo.set(url, { at: entry?.at ?? 0, value: entry?.value ?? null, pending });\n // Serve stale while revalidating; first call waits.\n return entry ? entry.value : pending;\n}\n\n/** Tests only. */\nexport function clearRemoteMemo(): void {\n memo.clear();\n}\n","import {\n applyRemoteOverrides,\n CLOUD_ENDPOINT,\n countsForHoldout,\n decideRedirect,\n explainAssignment,\n HOLDOUT_KEY,\n holdoutGroup,\n isDevEnvironment,\n matchPath,\n newId,\n newVisitorId,\n parseCookies,\n parseForceParam,\n parseUserAgent,\n redirectTarget,\n SDK_VERSION,\n type EventBatch,\n type ExposureEvent,\n type SplitHubConfig,\n type TargetingContext,\n} from '@splithub/core';\nimport { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';\nimport { getRemoteOverrides } from './remote';\n\nexport const VISITOR_HEADER = 'x-splithub-vid';\nconst ONE_YEAR = 60 * 60 * 24 * 365;\n\nexport interface MiddlewareOptions {\n /** Return true to skip a path entirely. Defaults to `_next`, `api` and files with an extension. */\n exclude?: (pathname: string) => boolean;\n /** Send exposures for redirect experiments from the edge. Default true. */\n trackRedirects?: boolean;\n /** Apply live overrides from the cloud (cloud mode only). Default true. */\n remote?: boolean;\n}\n\nfunction defaultExclude(pathname: string): boolean {\n return pathname.startsWith('/_next') || pathname.startsWith('/api/') || /\\.[a-z0-9]+$/i.test(pathname);\n}\n\n/** Same rule as sh.js and pageview goals (from `@splithub/core`). */\nexport { matchPath };\n\n/**\n * Targeting context from request headers: Cloudflare / Vercel geo, user agent, language,\n * referrer, cookies. `timezone` (for `hour` / `weekday`) comes from Vercel's\n * `x-vercel-ip-timezone` or a `cf-timezone` / `x-timezone` header you set; without one\n * the flow uses UTC.\n */\nexport function requestContext(headers: Headers, url: string, visitor?: 'new' | 'returning'): TargetingContext {\n const ua = parseUserAgent(headers.get('user-agent'));\n const country = headers.get('cf-ipcountry') ?? headers.get('x-vercel-ip-country') ?? headers.get('x-country') ?? undefined;\n const region = headers.get('x-vercel-ip-country-region') ?? headers.get('cf-region') ?? undefined;\n const city = headers.get('x-vercel-ip-city') ?? headers.get('cf-ipcity') ?? undefined;\n const timezone = headers.get('x-vercel-ip-timezone') ?? headers.get('cf-timezone') ?? headers.get('x-timezone') ?? undefined;\n return {\n country: country ?? undefined,\n region: region ? decodeURIComponent(region) : undefined,\n city: city ? decodeURIComponent(city) : undefined,\n device: ua.device,\n browser: ua.browser,\n os: ua.os,\n language: headers.get('accept-language') ?? undefined,\n referrer: headers.get('referer') ?? undefined,\n url,\n cookies: parseCookies(headers.get('cookie')),\n ...(timezone ? { timezone } : {}),\n ...(visitor ? { visitor } : {}),\n };\n}\n\nfunction ingestTarget(config: SplitHubConfig, origin: string): { url: string; key?: string } {\n if (config.storage.mode === 'self') return { url: new URL(config.storage.endpoint, origin).toString() };\n return { url: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\n/**\n * Next.js middleware:\n * 1. ensures the `sh_vid` visitor cookie, so SSR and the client agree on variants;\n * 2. forwards the visitor id to Server Components via the `x-splithub-vid` header;\n * 3. serves redirect experiments with an invisible rewrite (URL unchanged, no flash);\n * 4. records the redirect exposure from the edge, deduplicated with a cookie.\n *\n * ```ts\n * // middleware.ts\n * import { splithubMiddleware } from '@splithub/next';\n * import config from './splithub.config';\n * export default splithubMiddleware(config);\n * export const config = { matcher: ['/((?!_next|api|.*\\\\..*).*)'] };\n * ```\n */\nexport function splithubMiddleware(baseConfig: SplitHubConfig, options: MiddlewareOptions = {}) {\n const exclude = options.exclude ?? defaultExclude;\n const trackRedirects = options.trackRedirects ?? true;\n const useRemote = options.remote ?? true;\n\n return async function middleware(request: NextRequest, event?: NextFetchEvent): Promise<NextResponse> {\n const pathname = request.nextUrl.pathname;\n if (exclude(pathname)) return NextResponse.next();\n\n const config = useRemote ? applyRemoteOverrides(baseConfig, await getRemoteOverrides(baseConfig)) : baseConfig;\n\n let visitorId = request.cookies.get(config.visitorKey)?.value ?? null;\n const isNewVisitor = !visitorId;\n if (!visitorId) visitorId = newVisitorId();\n\n const overrides = parseForceParam(request.nextUrl.search);\n const context = requestContext(request.headers, request.nextUrl.href, isNewVisitor ? 'new' : 'returning');\n const requestHeaders = new Headers(request.headers);\n requestHeaders.set(VISITOR_HEADER, visitorId);\n\n let response: NextResponse | null = null;\n const cookiesToSet: Array<{ name: string; value: string }> = [];\n\n // The same decision as sh.js; in development, say why a matching test did nothing.\n // A visitor who reaches a running redirect test also joins the holdout comparison (same rule as the SDK).\n let reachedTest = false as boolean;\n const decision = decideRedirect(config, pathname, visitorId, context, overrides, (exp, a) => {\n if (countsForHoldout(a)) reachedTest = true;\n explainAssignment(exp, a);\n });\n // Development never sends to the cloud (the developer is not a visitor); a self-hosted store records it, dev drafts included.\n // Bots never reach here with a variant: assign gives them the control without one.\n const cloudDev = config.storage.mode === 'cloud' && isDevEnvironment();\n const events: ExposureEvent[] = [];\n if (decision) {\n if (decision.to) {\n const target = redirectTarget(decision.to, request.nextUrl.href);\n let url: URL = target;\n if (target.origin === request.nextUrl.origin) {\n // Keep Next's own URL (basePath, locale) and change only what the variant says.\n const next = request.nextUrl.clone();\n next.pathname = target.pathname;\n next.search = target.search;\n url = next;\n }\n response = NextResponse.rewrite(url, { request: { headers: requestHeaders } });\n }\n\n const exposureCookie = `sh_x_${decision.experiment}`;\n const record = !cloudDev && (decision.reason === 'assigned' || (decision.reason === 'dev' && config.storage.mode === 'self'));\n if (trackRedirects && record && request.cookies.get(exposureCookie)?.value !== decision.variant) {\n cookiesToSet.push({ name: exposureCookie, value: decision.variant });\n events.push({ id: newId('e_'), type: 'exposure', exp: decision.experiment, var: decision.variant, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname });\n }\n }\n const group = reachedTest ? holdoutGroup(config, visitorId) : null;\n if (group && trackRedirects && !cloudDev && request.cookies.get(`sh_x_${HOLDOUT_KEY}`)?.value !== group) {\n cookiesToSet.push({ name: `sh_x_${HOLDOUT_KEY}`, value: group });\n events.push({ id: newId('e_'), type: 'exposure', exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname });\n }\n if (events.length) {\n const target = ingestTarget(config, request.nextUrl.origin);\n const batch: EventBatch = { project: config.project, sdk: `next/${SDK_VERSION}`, events };\n const headers: Record<string, string> = { 'content-type': 'application/json' };\n if (target.key) headers.authorization = `Bearer ${target.key}`;\n // The visitor's user agent, so the ingest's bot filter judges the visitor, not this server.\n // `x-splithub-ua` too, for runtimes that replace a user-agent set on fetch.\n const ua = request.headers.get('user-agent');\n if (ua) {\n headers['user-agent'] = ua;\n headers['x-splithub-ua'] = ua;\n }\n const send = fetch(target.url, { method: 'POST', headers, body: JSON.stringify(batch) }).catch(() => undefined);\n if (event?.waitUntil) event.waitUntil(send);\n }\n\n response ??= NextResponse.next({ request: { headers: requestHeaders } });\n\n if (isNewVisitor) {\n response.cookies.set(config.visitorKey, visitorId, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n }\n for (const c of cookiesToSet) response.cookies.set(c.name, c.value, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n return response;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,eAAkK;;;ACAlK,kBAAoI;AAUpI,IAAM,OAAO,oBAAI,IAAuB;AAaxC,eAAsB,mBAAmB,QAAwB,UAAyB,CAAC,GAAoC;AAC7H,MAAI,OAAO,QAAQ,SAAS,WAAW,CAAC,OAAO,QAAQ,IAAK,QAAO;AACnE,QAAM,MAAM,QAAQ,SAAS;AAC7B,QAAM,UAAM,iCAAoB,OAAO,QAAQ,YAAY,4BAAgB,OAAO,QAAQ,GAAG;AAC7F,QAAM,QAAQ,KAAK,IAAI,GAAG;AAC1B,QAAM,MAAM,KAAK,IAAI;AACrB,MAAI,SAAS,MAAM,MAAM,KAAK,IAAK,QAAO,MAAM;AAChD,MAAI,OAAO,QAAS,QAAO,MAAM,SAAS,MAAM;AAEhD,QAAM,cAAU,kCAAqB,KAAK,QAAQ,SAAS,EAAE,KAAK,CAAC,UAAU;AAC3E,SAAK,IAAI,KAAK,EAAE,IAAI,KAAK,IAAI,GAAG,OAAO,SAAS,OAAO,SAAS,MAAM,SAAS,KAAK,CAAC;AACrF,WAAO,SAAS,OAAO,SAAS;AAAA,EAClC,CAAC;AACD,OAAK,IAAI,KAAK,EAAE,IAAI,OAAO,MAAM,GAAG,OAAO,OAAO,SAAS,MAAM,QAAQ,CAAC;AAE1E,SAAO,QAAQ,MAAM,QAAQ;AAC/B;;;ADrCA,qBAAiC;;;AEFjC,IAAAC,eAqBO;AACP,oBAAoE;AAG7D,IAAM,iBAAiB;AAC9B,IAAM,WAAW,KAAK,KAAK,KAAK;AAwBzB,SAAS,eAAeC,UAAkB,KAAa,SAA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leware.ts"],"sourcesContent":["import { applyRemoteOverrides, assign, explainAssignment, getExperiment, type Assignment, type RemoteOverrides, type SplitHubConfig, type TargetingContext } from '@splithub/core';\nimport { getRemoteOverrides } from './remote';\nimport { cookies, headers } from 'next/headers';\nimport { requestContext, VISITOR_HEADER } from './middleware';\n\nexport { getRemoteOverrides } from './remote';\n\n/**\n * Visitor id for the current request (header set by the middleware, else the\n * cookie). Null when the middleware is not installed and no cookie exists.\n */\nexport async function getVisitorId(config: SplitHubConfig): Promise<string | null> {\n const h = await headers();\n const fromHeader = h.get(VISITOR_HEADER);\n if (fromHeader) return fromHeader;\n const c = await cookies();\n return c.get(config.visitorKey)?.value ?? null;\n}\n\nexport interface ServerSplitHub {\n visitorId: string | null;\n /** Targeting context built from the request headers (geo, device, language, referrer). */\n context: TargetingContext;\n /** Live overrides applied to this request; pass them to <SplitHubNextProvider remoteOverrides={...}> so hydration agrees. */\n overrides: RemoteOverrides | null;\n /** Config with overrides applied. */\n config: SplitHubConfig;\n assignment(experimentKey: string): Assignment;\n /** Variant key; control when unassigned. No exposure is recorded on the server: render `<Exposure id>` from `@splithub/next/client`. */\n variant(experimentKey: string): string;\n value<T = unknown>(experimentKey: string): T;\n}\n\n/**\n * Assignments inside Server Components and Route Handlers:\n *\n * ```tsx\n * const sh = await getSplitHub(config);\n * const title = sh.value<string>('hero-title');\n * ```\n */\nexport async function getSplitHub(baseConfig: SplitHubConfig): Promise<ServerSplitHub> {\n const [visitorId, fetched] = await Promise.all([getVisitorId(baseConfig), getRemoteOverrides(baseConfig)]);\n const config = applyRemoteOverrides(baseConfig, fetched);\n const h = await headers();\n const context: TargetingContext = requestContext(h, h.get('x-url') ?? h.get('referer') ?? '');\n // The overrides were fetched (and memoized) by this server, so their `ctx` is the server's\n // location, not the visitor's. Hand the browser the visitor's geo from the request headers\n // instead, so the client provider decides geo targeting exactly as this render did.\n const geo = Object.fromEntries(\n (['country', 'region', 'city', 'timezone'] as const).filter((k) => context[k]).map((k) => [k, context[k]])\n ) as NonNullable<RemoteOverrides['ctx']>;\n const overrides: RemoteOverrides | null = fetched ? { ...fetched, ctx: geo } : Object.keys(geo).length ? { version: 0, experiments: {}, ctx: geo } : null;\n const control = (key: string) => getExperiment(config, key)?.variants[0];\n const opts = { context };\n // Assign and, in development, explain a surprising result in the terminal.\n const decide = (key: string) => {\n if (!visitorId) return null;\n const a = assign(config, key, visitorId, opts);\n explainAssignment(getExperiment(config, key), a);\n return a;\n };\n return {\n visitorId,\n context,\n overrides,\n config,\n assignment(key) {\n return decide(key) ?? { experiment: key, variant: null, reason: 'not_running' };\n },\n variant(key) {\n const a = decide(key);\n return (a?.variant ?? control(key))?.key ?? 'control';\n },\n value<T>(key: string): T {\n const a = decide(key);\n return (a?.variant ?? control(key))?.value as T;\n },\n };\n}\n","import { CLOUD_ENDPOINT, fetchRemoteOverrides, resolveOverridesUrl, REMOTE_TTL_MS, type RemoteOverrides, type SplitHubConfig } from '@splithub/core';\n\ninterface MemoEntry {\n at: number;\n value: RemoteOverrides | null;\n pending: Promise<RemoteOverrides | null> | null;\n}\n\n// Module-level memo: edge isolates and Node servers keep it across requests,\n// so at most one fetch per TTL per public key.\nconst memo = new Map<string, MemoEntry>();\n\nexport interface RemoteOptions {\n ttlMs?: number;\n /** Override the fetch implementation (tests). */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Live overrides for a cloud-mode config, cached in memory for `ttlMs`\n * (default 60s). Returns null in self mode or when the cloud is unreachable\n * (the config file then applies as-is).\n */\nexport async function getRemoteOverrides(config: SplitHubConfig, options: RemoteOptions = {}): Promise<RemoteOverrides | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const ttl = options.ttlMs ?? REMOTE_TTL_MS;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const entry = memo.get(url);\n const now = Date.now();\n if (entry && now - entry.at < ttl) return entry.value;\n if (entry?.pending) return entry.value ?? entry.pending;\n\n const pending = fetchRemoteOverrides(url, options.fetchImpl).then((value) => {\n memo.set(url, { at: Date.now(), value: value ?? entry?.value ?? null, pending: null });\n return value ?? entry?.value ?? null;\n });\n memo.set(url, { at: entry?.at ?? 0, value: entry?.value ?? null, pending });\n // Serve stale while revalidating; first call waits.\n return entry ? entry.value : pending;\n}\n\n/** Tests only. */\nexport function clearRemoteMemo(): void {\n memo.clear();\n}\n","import {\n applyRemoteOverrides,\n CLOUD_ENDPOINT,\n countsForHoldout,\n decideRedirect,\n explainAssignment,\n HOLDOUT_KEY,\n holdoutGroup,\n isDevEnvironment,\n matchPath,\n newId,\n newVisitorId,\n parseCookies,\n parseForceParam,\n parseUserAgent,\n redirectTarget,\n referrerOrigin,\n SDK_VERSION,\n type EventBatch,\n type ExposureEvent,\n type SplitHubConfig,\n type TargetingContext,\n} from '@splithub/core';\nimport { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';\nimport { getRemoteOverrides } from './remote';\n\nexport const VISITOR_HEADER = 'x-splithub-vid';\nconst ONE_YEAR = 60 * 60 * 24 * 365;\n\nexport interface MiddlewareOptions {\n /** Return true to skip a path entirely. Defaults to `_next`, `api` and files with an extension. */\n exclude?: (pathname: string) => boolean;\n /** Send exposures for redirect experiments from the edge. Default true. */\n trackRedirects?: boolean;\n /** Apply live overrides from the cloud (cloud mode only). Default true. */\n remote?: boolean;\n}\n\nfunction defaultExclude(pathname: string): boolean {\n return pathname.startsWith('/_next') || pathname.startsWith('/api/') || /\\.[a-z0-9]+$/i.test(pathname);\n}\n\n/** Same rule as sh.js and pageview goals (from `@splithub/core`). */\nexport { matchPath };\n\n/**\n * Targeting context from request headers: Cloudflare / Vercel geo, user agent, language,\n * referrer, cookies. `timezone` (for `hour` / `weekday`) comes from Vercel's\n * `x-vercel-ip-timezone` or a `cf-timezone` / `x-timezone` header you set; without one\n * the flow uses UTC.\n */\nexport function requestContext(headers: Headers, url: string, visitor?: 'new' | 'returning'): TargetingContext {\n const ua = parseUserAgent(headers.get('user-agent'));\n const country = headers.get('cf-ipcountry') ?? headers.get('x-vercel-ip-country') ?? headers.get('x-country') ?? undefined;\n const region = headers.get('x-vercel-ip-country-region') ?? headers.get('cf-region') ?? undefined;\n const city = headers.get('x-vercel-ip-city') ?? headers.get('cf-ipcity') ?? undefined;\n const timezone = headers.get('x-vercel-ip-timezone') ?? headers.get('cf-timezone') ?? headers.get('x-timezone') ?? undefined;\n return {\n country: country ?? undefined,\n region: region ? decodeURIComponent(region) : undefined,\n city: city ? decodeURIComponent(city) : undefined,\n device: ua.device,\n browser: ua.browser,\n os: ua.os,\n language: headers.get('accept-language') ?? undefined,\n referrer: headers.get('referer') ?? undefined,\n url,\n cookies: parseCookies(headers.get('cookie')),\n ...(timezone ? { timezone } : {}),\n ...(visitor ? { visitor } : {}),\n };\n}\n\nfunction ingestTarget(config: SplitHubConfig, origin: string): { url: string; key?: string } {\n if (config.storage.mode === 'self') return { url: new URL(config.storage.endpoint, origin).toString() };\n return { url: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\n/**\n * Next.js middleware:\n * 1. ensures the `sh_vid` visitor cookie, so SSR and the client agree on variants;\n * 2. forwards the visitor id to Server Components via the `x-splithub-vid` header;\n * 3. serves redirect experiments with an invisible rewrite (URL unchanged, no flash);\n * 4. records the redirect exposure from the edge, deduplicated with a cookie.\n *\n * ```ts\n * // middleware.ts\n * import { splithubMiddleware } from '@splithub/next';\n * import config from './splithub.config';\n * export default splithubMiddleware(config);\n * export const config = { matcher: ['/((?!_next|api|.*\\\\..*).*)'] };\n * ```\n */\nexport function splithubMiddleware(baseConfig: SplitHubConfig, options: MiddlewareOptions = {}) {\n const exclude = options.exclude ?? defaultExclude;\n const trackRedirects = options.trackRedirects ?? true;\n const useRemote = options.remote ?? true;\n\n return async function middleware(request: NextRequest, event?: NextFetchEvent): Promise<NextResponse> {\n const pathname = request.nextUrl.pathname;\n if (exclude(pathname)) return NextResponse.next();\n\n const config = useRemote ? applyRemoteOverrides(baseConfig, await getRemoteOverrides(baseConfig)) : baseConfig;\n\n let visitorId = request.cookies.get(config.visitorKey)?.value ?? null;\n const isNewVisitor = !visitorId;\n if (!visitorId) visitorId = newVisitorId();\n\n const overrides = parseForceParam(request.nextUrl.search);\n const context = requestContext(request.headers, request.nextUrl.href, isNewVisitor ? 'new' : 'returning');\n const requestHeaders = new Headers(request.headers);\n requestHeaders.set(VISITOR_HEADER, visitorId);\n\n let response: NextResponse | null = null;\n const cookiesToSet: Array<{ name: string; value: string }> = [];\n\n // The same decision as sh.js; in development, say why a matching test did nothing.\n // A visitor who reaches a running redirect test also joins the holdout comparison (same rule as the SDK).\n let reachedTest = false as boolean;\n const decision = decideRedirect(config, pathname, visitorId, context, overrides, (exp, a) => {\n if (countsForHoldout(a)) reachedTest = true;\n explainAssignment(exp, a);\n });\n // Development never sends to the cloud (the developer is not a visitor); a self-hosted store records it, dev drafts included.\n // Bots never reach here with a variant: assign gives them the control without one.\n const cloudDev = config.storage.mode === 'cloud' && isDevEnvironment();\n const events: ExposureEvent[] = [];\n // This request is the page load, so its Referer is where the visitor came from (the ingest\n // only sees this server). Same-site navigation says nothing about the source: left out.\n const ref = referrerOrigin(request.headers.get('referer'), request.nextUrl.host);\n const refField = ref === undefined ? {} : { ref };\n if (decision) {\n if (decision.to) {\n const target = redirectTarget(decision.to, request.nextUrl.href);\n let url: URL = target;\n if (target.origin === request.nextUrl.origin) {\n // Keep Next's own URL (basePath, locale) and change only what the variant says.\n const next = request.nextUrl.clone();\n next.pathname = target.pathname;\n next.search = target.search;\n url = next;\n }\n response = NextResponse.rewrite(url, { request: { headers: requestHeaders } });\n }\n\n const exposureCookie = `sh_x_${decision.experiment}`;\n const record = !cloudDev && (decision.reason === 'assigned' || (decision.reason === 'dev' && config.storage.mode === 'self'));\n if (trackRedirects && record && request.cookies.get(exposureCookie)?.value !== decision.variant) {\n cookiesToSet.push({ name: exposureCookie, value: decision.variant });\n events.push({ id: newId('e_'), type: 'exposure', exp: decision.experiment, var: decision.variant, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname, ...refField });\n }\n }\n const group = reachedTest ? holdoutGroup(config, visitorId) : null;\n if (group && trackRedirects && !cloudDev && request.cookies.get(`sh_x_${HOLDOUT_KEY}`)?.value !== group) {\n cookiesToSet.push({ name: `sh_x_${HOLDOUT_KEY}`, value: group });\n events.push({ id: newId('e_'), type: 'exposure', exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname, ...refField });\n }\n if (events.length) {\n const target = ingestTarget(config, request.nextUrl.origin);\n const batch: EventBatch = { project: config.project, sdk: `next/${SDK_VERSION}`, events };\n const headers: Record<string, string> = { 'content-type': 'application/json' };\n if (target.key) headers.authorization = `Bearer ${target.key}`;\n // The visitor's user agent, so the ingest's bot filter judges the visitor, not this server.\n // `x-splithub-ua` too, for runtimes that replace a user-agent set on fetch.\n const ua = request.headers.get('user-agent');\n if (ua) {\n headers['user-agent'] = ua;\n headers['x-splithub-ua'] = ua;\n }\n const send = fetch(target.url, { method: 'POST', headers, body: JSON.stringify(batch) }).catch(() => undefined);\n if (event?.waitUntil) event.waitUntil(send);\n }\n\n response ??= NextResponse.next({ request: { headers: requestHeaders } });\n\n if (isNewVisitor) {\n response.cookies.set(config.visitorKey, visitorId, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n }\n for (const c of cookiesToSet) response.cookies.set(c.name, c.value, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n return response;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,eAAkK;;;ACAlK,kBAAoI;AAUpI,IAAM,OAAO,oBAAI,IAAuB;AAaxC,eAAsB,mBAAmB,QAAwB,UAAyB,CAAC,GAAoC;AAC7H,MAAI,OAAO,QAAQ,SAAS,WAAW,CAAC,OAAO,QAAQ,IAAK,QAAO;AACnE,QAAM,MAAM,QAAQ,SAAS;AAC7B,QAAM,UAAM,i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YAAgB,4BAAc,QAAQ,GAAG,GAAG,SAAS,CAAC;AACvE,QAAM,OAAO,EAAE,QAAQ;AAEvB,QAAM,SAAS,CAAC,QAAgB;AAC9B,QAAI,CAAC,UAAW,QAAO;AACvB,UAAM,QAAI,qBAAO,QAAQ,KAAK,WAAW,IAAI;AAC7C,4CAAkB,4BAAc,QAAQ,GAAG,GAAG,CAAC;AAC/C,WAAO;AAAA,EACT;AACA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW,KAAK;AACd,aAAO,OAAO,GAAG,KAAK,EAAE,YAAY,KAAK,SAAS,MAAM,QAAQ,cAAc;AAAA,IAChF;AAAA,IACA,QAAQ,KAAK;AACX,YAAM,IAAI,OAAO,GAAG;AACpB,cAAQ,GAAG,WAAW,QAAQ,GAAG,IAAI,OAAO;AAAA,IAC9C;AAAA,IACA,MAAS,KAAgB;AACvB,YAAM,IAAI,OAAO,GAAG;AACpB,cAAQ,GAAG,WAAW,QAAQ,GAAG,IAAI;AAAA,IACvC;AAAA,EACF;AACF;","names":["import_core","import_core","headers"]}
package/dist/server.js CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  VISITOR_HEADER,
3
3
  getRemoteOverrides,
4
4
  requestContext
5
- } from "./chunk-BH4ACCFH.js";
5
+ } from "./chunk-S5V4VC56.js";
6
6
 
7
7
  // src/server.ts
8
8
  import { applyRemoteOverrides, assign, explainAssignment, getExperiment } from "@splithub/core";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@splithub/next",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "SplitHub for Next.js: middleware, server components, redirect tests and the route for your own database.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -43,8 +43,8 @@
43
43
  "react": ">=18"
44
44
  },
45
45
  "dependencies": {
46
- "@splithub/core": "0.3.0",
47
- "@splithub/react": "0.3.0"
46
+ "@splithub/core": "0.4.0",
47
+ "@splithub/react": "0.4.0"
48
48
  },
49
49
  "devDependencies": {
50
50
  "@types/react": "^18.3.12",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/remote.ts","../src/middleware.ts"],"sourcesContent":["import { CLOUD_ENDPOINT, fetchRemoteOverrides, resolveOverridesUrl, REMOTE_TTL_MS, type RemoteOverrides, type SplitHubConfig } from '@splithub/core';\n\ninterface MemoEntry {\n at: number;\n value: RemoteOverrides | null;\n pending: Promise<RemoteOverrides | null> | null;\n}\n\n// Module-level memo: edge isolates and Node servers keep it across requests,\n// so at most one fetch per TTL per public key.\nconst memo = new Map<string, MemoEntry>();\n\nexport interface RemoteOptions {\n ttlMs?: number;\n /** Override the fetch implementation (tests). */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Live overrides for a cloud-mode config, cached in memory for `ttlMs`\n * (default 60s). Returns null in self mode or when the cloud is unreachable\n * (the config file then applies as-is).\n */\nexport async function getRemoteOverrides(config: SplitHubConfig, options: RemoteOptions = {}): Promise<RemoteOverrides | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const ttl = options.ttlMs ?? REMOTE_TTL_MS;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const entry = memo.get(url);\n const now = Date.now();\n if (entry && now - entry.at < ttl) return entry.value;\n if (entry?.pending) return entry.value ?? entry.pending;\n\n const pending = fetchRemoteOverrides(url, options.fetchImpl).then((value) => {\n memo.set(url, { at: Date.now(), value: value ?? entry?.value ?? null, pending: null });\n return value ?? entry?.value ?? null;\n });\n memo.set(url, { at: entry?.at ?? 0, value: entry?.value ?? null, pending });\n // Serve stale while revalidating; first call waits.\n return entry ? entry.value : pending;\n}\n\n/** Tests only. */\nexport function clearRemoteMemo(): void {\n memo.clear();\n}\n","import {\n applyRemoteOverrides,\n CLOUD_ENDPOINT,\n countsForHoldout,\n decideRedirect,\n explainAssignment,\n HOLDOUT_KEY,\n holdoutGroup,\n isDevEnvironment,\n matchPath,\n newId,\n newVisitorId,\n parseCookies,\n parseForceParam,\n parseUserAgent,\n redirectTarget,\n SDK_VERSION,\n type EventBatch,\n type ExposureEvent,\n type SplitHubConfig,\n type TargetingContext,\n} from '@splithub/core';\nimport { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';\nimport { getRemoteOverrides } from './remote';\n\nexport const VISITOR_HEADER = 'x-splithub-vid';\nconst ONE_YEAR = 60 * 60 * 24 * 365;\n\nexport interface MiddlewareOptions {\n /** Return true to skip a path entirely. Defaults to `_next`, `api` and files with an extension. */\n exclude?: (pathname: string) => boolean;\n /** Send exposures for redirect experiments from the edge. Default true. */\n trackRedirects?: boolean;\n /** Apply live overrides from the cloud (cloud mode only). Default true. */\n remote?: boolean;\n}\n\nfunction defaultExclude(pathname: string): boolean {\n return pathname.startsWith('/_next') || pathname.startsWith('/api/') || /\\.[a-z0-9]+$/i.test(pathname);\n}\n\n/** Same rule as sh.js and pageview goals (from `@splithub/core`). */\nexport { matchPath };\n\n/**\n * Targeting context from request headers: Cloudflare / Vercel geo, user agent, language,\n * referrer, cookies. `timezone` (for `hour` / `weekday`) comes from Vercel's\n * `x-vercel-ip-timezone` or a `cf-timezone` / `x-timezone` header you set; without one\n * the flow uses UTC.\n */\nexport function requestContext(headers: Headers, url: string, visitor?: 'new' | 'returning'): TargetingContext {\n const ua = parseUserAgent(headers.get('user-agent'));\n const country = headers.get('cf-ipcountry') ?? headers.get('x-vercel-ip-country') ?? headers.get('x-country') ?? undefined;\n const region = headers.get('x-vercel-ip-country-region') ?? headers.get('cf-region') ?? undefined;\n const city = headers.get('x-vercel-ip-city') ?? headers.get('cf-ipcity') ?? undefined;\n const timezone = headers.get('x-vercel-ip-timezone') ?? headers.get('cf-timezone') ?? headers.get('x-timezone') ?? undefined;\n return {\n country: country ?? undefined,\n region: region ? decodeURIComponent(region) : undefined,\n city: city ? decodeURIComponent(city) : undefined,\n device: ua.device,\n browser: ua.browser,\n os: ua.os,\n language: headers.get('accept-language') ?? undefined,\n referrer: headers.get('referer') ?? undefined,\n url,\n cookies: parseCookies(headers.get('cookie')),\n ...(timezone ? { timezone } : {}),\n ...(visitor ? { visitor } : {}),\n };\n}\n\nfunction ingestTarget(config: SplitHubConfig, origin: string): { url: string; key?: string } {\n if (config.storage.mode === 'self') return { url: new URL(config.storage.endpoint, origin).toString() };\n return { url: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\n/**\n * Next.js middleware:\n * 1. ensures the `sh_vid` visitor cookie, so SSR and the client agree on variants;\n * 2. forwards the visitor id to Server Components via the `x-splithub-vid` header;\n * 3. serves redirect experiments with an invisible rewrite (URL unchanged, no flash);\n * 4. records the redirect exposure from the edge, deduplicated with a cookie.\n *\n * ```ts\n * // middleware.ts\n * import { splithubMiddleware } from '@splithub/next';\n * import config from './splithub.config';\n * export default splithubMiddleware(config);\n * export const config = { matcher: ['/((?!_next|api|.*\\\\..*).*)'] };\n * ```\n */\nexport function splithubMiddleware(baseConfig: SplitHubConfig, options: MiddlewareOptions = {}) {\n const exclude = options.exclude ?? defaultExclude;\n const trackRedirects = options.trackRedirects ?? true;\n const useRemote = options.remote ?? true;\n\n return async function middleware(request: NextRequest, event?: NextFetchEvent): Promise<NextResponse> {\n const pathname = request.nextUrl.pathname;\n if (exclude(pathname)) return NextResponse.next();\n\n const config = useRemote ? applyRemoteOverrides(baseConfig, await getRemoteOverrides(baseConfig)) : baseConfig;\n\n let visitorId = request.cookies.get(config.visitorKey)?.value ?? null;\n const isNewVisitor = !visitorId;\n if (!visitorId) visitorId = newVisitorId();\n\n const overrides = parseForceParam(request.nextUrl.search);\n const context = requestContext(request.headers, request.nextUrl.href, isNewVisitor ? 'new' : 'returning');\n const requestHeaders = new Headers(request.headers);\n requestHeaders.set(VISITOR_HEADER, visitorId);\n\n let response: NextResponse | null = null;\n const cookiesToSet: Array<{ name: string; value: string }> = [];\n\n // The same decision as sh.js; in development, say why a matching test did nothing.\n // A visitor who reaches a running redirect test also joins the holdout comparison (same rule as the SDK).\n let reachedTest = false as boolean;\n const decision = decideRedirect(config, pathname, visitorId, context, overrides, (exp, a) => {\n if (countsForHoldout(a)) reachedTest = true;\n explainAssignment(exp, a);\n });\n // Development never sends to the cloud (the developer is not a visitor); a self-hosted store records it, dev drafts included.\n // Bots never reach here with a variant: assign gives them the control without one.\n const cloudDev = config.storage.mode === 'cloud' && isDevEnvironment();\n const events: ExposureEvent[] = [];\n if (decision) {\n if (decision.to) {\n const target = redirectTarget(decision.to, request.nextUrl.href);\n let url: URL = target;\n if (target.origin === request.nextUrl.origin) {\n // Keep Next's own URL (basePath, locale) and change only what the variant says.\n const next = request.nextUrl.clone();\n next.pathname = target.pathname;\n next.search = target.search;\n url = next;\n }\n response = NextResponse.rewrite(url, { request: { headers: requestHeaders } });\n }\n\n const exposureCookie = `sh_x_${decision.experiment}`;\n const record = !cloudDev && (decision.reason === 'assigned' || (decision.reason === 'dev' && config.storage.mode === 'self'));\n if (trackRedirects && record && request.cookies.get(exposureCookie)?.value !== decision.variant) {\n cookiesToSet.push({ name: exposureCookie, value: decision.variant });\n events.push({ id: newId('e_'), type: 'exposure', exp: decision.experiment, var: decision.variant, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname });\n }\n }\n const group = reachedTest ? holdoutGroup(config, visitorId) : null;\n if (group && trackRedirects && !cloudDev && request.cookies.get(`sh_x_${HOLDOUT_KEY}`)?.value !== group) {\n cookiesToSet.push({ name: `sh_x_${HOLDOUT_KEY}`, value: group });\n events.push({ id: newId('e_'), type: 'exposure', exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: 'edge', ts: Date.now(), url: pathname });\n }\n if (events.length) {\n const target = ingestTarget(config, request.nextUrl.origin);\n const batch: EventBatch = { project: config.project, sdk: `next/${SDK_VERSION}`, events };\n const headers: Record<string, string> = { 'content-type': 'application/json' };\n if (target.key) headers.authorization = `Bearer ${target.key}`;\n // The visitor's user agent, so the ingest's bot filter judges the visitor, not this server.\n // `x-splithub-ua` too, for runtimes that replace a user-agent set on fetch.\n const ua = request.headers.get('user-agent');\n if (ua) {\n headers['user-agent'] = ua;\n headers['x-splithub-ua'] = ua;\n }\n const send = fetch(target.url, { method: 'POST', headers, body: JSON.stringify(batch) }).catch(() => undefined);\n if (event?.waitUntil) event.waitUntil(send);\n }\n\n response ??= NextResponse.next({ request: { headers: requestHeaders } });\n\n if (isNewVisitor) {\n response.cookies.set(config.visitorKey, visitorId, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n }\n for (const c of cookiesToSet) response.cookies.set(c.name, c.value, { maxAge: ONE_YEAR, path: '/', sameSite: 'lax' });\n return response;\n };\n}\n"],"mappings":";AAAA,SAAS,gBAAgB,sBAAsB,qBAAqB,qBAAgE;AAUpI,IAAM,OAAO,oBAAI,IAAuB;AAaxC,eAAsB,mBAAmB,QAAwB,UAAyB,CAAC,GAAoC;AAC7H,MAAI,OAAO,QAAQ,SAAS,WAAW,CAAC,OAAO,QAAQ,IAAK,QAAO;AACnE,QAAM,MAAM,QAAQ,SAAS;AAC7B,QAAM,MAAM,oBAAoB,OAAO,QAAQ,YAAY,gBAAgB,OAAO,QAAQ,GAAG;AAC7F,QAAM,QAAQ,KAAK,IAAI,GAAG;AAC1B,QAAM,MAAM,KAAK,IAAI;AACrB,MAAI,SAAS,MAAM,MAAM,KAAK,IAAK,QAAO,MAAM;AAChD,MAAI,OAAO,QAAS,QAAO,MAAM,SAAS,MAAM;AAEhD,QAAM,UAAU,qBAAqB,KAAK,QAAQ,SAAS,EAAE,KAAK,CAAC,UAAU;AAC3E,SAAK,IAAI,KAAK,EAAE,IAAI,KAAK,IAAI,GAAG,OAAO,SAAS,OAAO,SAAS,MAAM,SAAS,KAAK,CAAC;AACrF,WAAO,SAAS,OAAO,SAAS;AAAA,EAClC,CAAC;AACD,OAAK,IAAI,KAAK,EAAE,IAAI,OAAO,MAAM,GAAG,OAAO,OAAO,SAAS,MAAM,QAAQ,CAAC;AAE1E,SAAO,QAAQ,MAAM,QAAQ;AAC/B;AAG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