@faceyoga/analytics 0.0.0-stage → 0.2.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-J4RHGPNT.js +233 -0
- package/dist/chunk-J4RHGPNT.js.map +1 -0
- package/dist/client.d.ts +99 -0
- package/dist/client.js +320 -0
- package/dist/client.js.map +1 -0
- package/dist/names-CWW29ek_.d.ts +63 -0
- package/dist/server.d.ts +255 -0
- package/dist/server.js +323 -0
- package/dist/server.js.map +1 -0
- package/package.json +43 -3
- package/README.md +0 -3
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { b as AssignmentUnit, E as Experiment, A as Assignment } from './names-CWW29ek_.js';
|
|
3
|
+
export { a as EventNames } from './names-CWW29ek_.js';
|
|
4
|
+
|
|
5
|
+
declare const experimentSchema: z.ZodObject<{
|
|
6
|
+
key: z.ZodString;
|
|
7
|
+
status: z.ZodEnum<{
|
|
8
|
+
launched: "launched";
|
|
9
|
+
running: "running";
|
|
10
|
+
}>;
|
|
11
|
+
salt: z.ZodString;
|
|
12
|
+
allocation: z.ZodNumber;
|
|
13
|
+
variants: z.ZodArray<z.ZodObject<{
|
|
14
|
+
key: z.ZodString;
|
|
15
|
+
weight: z.ZodNumber;
|
|
16
|
+
params: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
17
|
+
}, z.core.$strip>>;
|
|
18
|
+
launchedVariant: z.ZodOptional<z.ZodString>;
|
|
19
|
+
targeting: z.ZodOptional<z.ZodObject<{
|
|
20
|
+
countries: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
21
|
+
locales: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
22
|
+
}, z.core.$strip>>;
|
|
23
|
+
}, z.core.$strip>;
|
|
24
|
+
declare const experimentsPayloadSchema: z.ZodObject<{
|
|
25
|
+
product: z.ZodString;
|
|
26
|
+
version: z.ZodString;
|
|
27
|
+
experiments: z.ZodArray<z.ZodObject<{
|
|
28
|
+
key: z.ZodString;
|
|
29
|
+
status: z.ZodEnum<{
|
|
30
|
+
launched: "launched";
|
|
31
|
+
running: "running";
|
|
32
|
+
}>;
|
|
33
|
+
salt: z.ZodString;
|
|
34
|
+
allocation: z.ZodNumber;
|
|
35
|
+
variants: z.ZodArray<z.ZodObject<{
|
|
36
|
+
key: z.ZodString;
|
|
37
|
+
weight: z.ZodNumber;
|
|
38
|
+
params: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
39
|
+
}, z.core.$strip>>;
|
|
40
|
+
launchedVariant: z.ZodOptional<z.ZodString>;
|
|
41
|
+
targeting: z.ZodOptional<z.ZodObject<{
|
|
42
|
+
countries: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
43
|
+
locales: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
44
|
+
}, z.core.$strip>>;
|
|
45
|
+
}, z.core.$strip>>;
|
|
46
|
+
previews: z.ZodDefault<z.ZodArray<z.ZodObject<{
|
|
47
|
+
key: z.ZodString;
|
|
48
|
+
variants: z.ZodArray<z.ZodObject<{
|
|
49
|
+
params: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
50
|
+
key: z.ZodString;
|
|
51
|
+
}, z.core.$strip>>;
|
|
52
|
+
}, z.core.$strip>>>;
|
|
53
|
+
}, z.core.$strip>;
|
|
54
|
+
type ExperimentConfig = z.infer<typeof experimentSchema>;
|
|
55
|
+
type ExperimentsPayload = z.infer<typeof experimentsPayloadSchema>;
|
|
56
|
+
/** What the endpoint may send: `previews` is optional so older servers still parse. */
|
|
57
|
+
type ExperimentsPayloadInput = z.input<typeof experimentsPayloadSchema>;
|
|
58
|
+
|
|
59
|
+
declare const eventSchema: z.ZodObject<{
|
|
60
|
+
id: z.ZodString;
|
|
61
|
+
name: z.ZodString;
|
|
62
|
+
ts: z.ZodNumber;
|
|
63
|
+
anonymousId: z.ZodString;
|
|
64
|
+
userId: z.ZodOptional<z.ZodString>;
|
|
65
|
+
sessionId: z.ZodOptional<z.ZodString>;
|
|
66
|
+
url: z.ZodOptional<z.ZodString>;
|
|
67
|
+
referrer: z.ZodOptional<z.ZodString>;
|
|
68
|
+
value: z.ZodOptional<z.ZodNumber>;
|
|
69
|
+
currency: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
|
|
70
|
+
orderId: z.ZodOptional<z.ZodString>;
|
|
71
|
+
experiments: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
72
|
+
props: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>>>;
|
|
73
|
+
}, z.core.$strip>;
|
|
74
|
+
/** An event as the SDK sends it. */
|
|
75
|
+
type AnalyticsEvent = z.input<typeof eventSchema>;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Server-side event sender for events that originate on the server (pithos `dispatchTrackingEvent`,
|
|
79
|
+
* upsell charges from cron, webhook-driven purchases) and for experiment exposures.
|
|
80
|
+
*
|
|
81
|
+
* Serverless functions freeze after the response, so nothing is sent on a timer: queue with
|
|
82
|
+
* `track()` and call `flush()` inside Next.js `after()` (or `waitUntil`) before the request ends.
|
|
83
|
+
*/
|
|
84
|
+
interface ServerAnalyticsOptions {
|
|
85
|
+
/** Collector URL, e.g. `https://analytics.example.com/api/collect`. */
|
|
86
|
+
endpoint: string;
|
|
87
|
+
/** Secret server key for the product. Never ship it to the browser. */
|
|
88
|
+
serverKey: string;
|
|
89
|
+
/** `production` | `preview` | `development`. Default: `VERCEL_ENV`, or `development` when unset. */
|
|
90
|
+
environment?: string;
|
|
91
|
+
/** Flush automatically once this many events are queued. Default 100 (the batch cap). */
|
|
92
|
+
maxBatchSize?: number;
|
|
93
|
+
fetch?: typeof fetch;
|
|
94
|
+
onError?: (error: unknown) => void;
|
|
95
|
+
}
|
|
96
|
+
type ServerEventInput = Omit<AnalyticsEvent, "id" | "ts" | "name" | "props"> & {
|
|
97
|
+
name: string;
|
|
98
|
+
id?: string;
|
|
99
|
+
ts?: number;
|
|
100
|
+
props?: Record<string, unknown>;
|
|
101
|
+
};
|
|
102
|
+
interface ServerAnalytics {
|
|
103
|
+
track(event: ServerEventInput): string;
|
|
104
|
+
flush(): Promise<void>;
|
|
105
|
+
/** Events waiting to be sent. */
|
|
106
|
+
pending(): number;
|
|
107
|
+
}
|
|
108
|
+
declare function createServerAnalytics(options: ServerAnalyticsOptions): ServerAnalytics;
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Server-side experiments, the replacement for `statsig.getExperiment(user, name)`.
|
|
112
|
+
*
|
|
113
|
+
* Config is fetched from the analytics app and kept in memory; assignment is a local hash, so
|
|
114
|
+
* `getExperiment` never waits on the network once `ready()` has resolved. Stale config is
|
|
115
|
+
* refreshed in the background on the next read after `refreshIntervalMs`.
|
|
116
|
+
*/
|
|
117
|
+
interface ExperimentsOptions {
|
|
118
|
+
/** Analytics app base URL, e.g. `https://analytics.example.com`. */
|
|
119
|
+
baseUrl: string;
|
|
120
|
+
serverKey: string;
|
|
121
|
+
/** Exposures are queued here; flush it in `after()`. Without it no exposures are logged. */
|
|
122
|
+
analytics?: ServerAnalytics;
|
|
123
|
+
refreshIntervalMs?: number;
|
|
124
|
+
/**
|
|
125
|
+
* Max wait for one config request. On timeout or error the last loaded config is kept, or
|
|
126
|
+
* every `get()` returns its fallback when none was loaded. Default 1000 ms.
|
|
127
|
+
*/
|
|
128
|
+
timeoutMs?: number;
|
|
129
|
+
/** Seed config, e.g. a build-time snapshot, so the very first request has values. */
|
|
130
|
+
initial?: ExperimentsPayloadInput;
|
|
131
|
+
fetch?: typeof fetch;
|
|
132
|
+
onError?: (error: unknown) => void;
|
|
133
|
+
}
|
|
134
|
+
interface ExperimentUnit extends AssignmentUnit {
|
|
135
|
+
/** Logged-in user id, copied onto exposure events. */
|
|
136
|
+
userId?: string;
|
|
137
|
+
/** Page URL, copied onto exposure events. */
|
|
138
|
+
url?: string;
|
|
139
|
+
/**
|
|
140
|
+
* Variants forced by a preview link (`readPreview(...).overrides`): experiment key -> variant.
|
|
141
|
+
* Forced variants work for drafts too and never log exposures.
|
|
142
|
+
*/
|
|
143
|
+
preview?: Record<string, string>;
|
|
144
|
+
}
|
|
145
|
+
interface Experiments {
|
|
146
|
+
/**
|
|
147
|
+
* Resolves after the first config load, at most `timeoutMs` later (immediately when `initial`
|
|
148
|
+
* was given). Never rejects; failures go to `onError`.
|
|
149
|
+
*/
|
|
150
|
+
ready(): Promise<void>;
|
|
151
|
+
/** Assign and log one exposure (per unit and experiment, per instance) when the user is in the test. */
|
|
152
|
+
getExperiment(unit: ExperimentUnit, key: string): Experiment;
|
|
153
|
+
/** Assign without logging an exposure, e.g. to decide what to prefetch. */
|
|
154
|
+
peek(unit: ExperimentUnit, key: string): Experiment;
|
|
155
|
+
/** Experiment key -> variant for every test the unit is in (forced variants included). Tag client events with this. */
|
|
156
|
+
getAssignments(unit: ExperimentUnit): Record<string, string>;
|
|
157
|
+
/** Everything a browser needs to evaluate experiments locally (Hoola-style client reads). */
|
|
158
|
+
getClientBootstrap(unit: ExperimentUnit): {
|
|
159
|
+
assignments: Record<string, Assignment>;
|
|
160
|
+
environment: string;
|
|
161
|
+
};
|
|
162
|
+
/** Force a config reload. */
|
|
163
|
+
refresh(): Promise<void>;
|
|
164
|
+
/** Version of the config currently in memory, or null before the first load. */
|
|
165
|
+
version(): string | null;
|
|
166
|
+
}
|
|
167
|
+
declare function createExperiments(options: ExperimentsOptions): Experiments;
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Same-origin collect route for a storefront. The browser pixel posts to `/a/collect` on the
|
|
171
|
+
* storefront itself, which:
|
|
172
|
+
* - keeps analytics requests first-party, so ad blockers and CORS never get involved;
|
|
173
|
+
* - means the browser needs no key at all: this route signs the batch with the server key;
|
|
174
|
+
* - forwards the visitor's Vercel geo headers and user agent, which the collector would not
|
|
175
|
+
* see on a server-to-server request (or reliably through a rewrite);
|
|
176
|
+
* - stamps the batch with this deployment's environment, so preview and local traffic is never
|
|
177
|
+
* counted as production whatever the browser sent;
|
|
178
|
+
* - marks the batch as QA when the visitor opened a preview link (`fy_qa` cookie), so the
|
|
179
|
+
* collector stores it as `test` even if the page runs an older pixel.
|
|
180
|
+
*
|
|
181
|
+
* // app/a/collect/route.ts
|
|
182
|
+
* export const POST = createCollectHandler({
|
|
183
|
+
* collectorUrl: `${process.env.ANALYTICS_URL}/api/collect`,
|
|
184
|
+
* serverKey: process.env.ANALYTICS_SERVER_KEY!,
|
|
185
|
+
* });
|
|
186
|
+
*
|
|
187
|
+
* The collector answers before it writes to Axiom, so awaiting it adds little latency, and its
|
|
188
|
+
* status is passed back so the pixel retries on 429 / 5xx.
|
|
189
|
+
*/
|
|
190
|
+
interface CollectHandlerOptions {
|
|
191
|
+
/** Collector URL, e.g. `https://analytics.example.com/api/collect`. */
|
|
192
|
+
collectorUrl: string;
|
|
193
|
+
/** Secret server key for the product. */
|
|
194
|
+
serverKey: string;
|
|
195
|
+
/** Overrides the batch's `environment`. Default: `VERCEL_ENV`, or `development` when unset. */
|
|
196
|
+
environment?: string;
|
|
197
|
+
fetch?: typeof fetch;
|
|
198
|
+
onError?: (error: unknown) => void;
|
|
199
|
+
}
|
|
200
|
+
declare function createCollectHandler(options: CollectHandlerOptions): (request: Request) => Promise<Response>;
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Preview links and QA mode. Pure and dependency-free: used by the browser pixel, the server SDK
|
|
204
|
+
* and the collector.
|
|
205
|
+
*
|
|
206
|
+
* ?fy_preview=<experiment>:<variant>[,<experiment>:<variant>] force variants for this browser
|
|
207
|
+
* ?fy_qa=1 QA mode only, no forced variant
|
|
208
|
+
* ?fy_preview=off (or ?fy_qa=0) back to normal
|
|
209
|
+
*
|
|
210
|
+
* Either parameter turns on QA mode for a day: every event from that browser, and every server
|
|
211
|
+
* event for the same visitor id (purchases, upsells), is stored with environment `test`, so it
|
|
212
|
+
* never counts in production numbers but can still be inspected in Live events.
|
|
213
|
+
*/
|
|
214
|
+
declare const PREVIEW_PARAM = "fy_preview";
|
|
215
|
+
declare const QA_PARAM = "fy_qa";
|
|
216
|
+
/** Environment stored on events from a browser in QA mode. */
|
|
217
|
+
declare const QA_ENVIRONMENT = "test";
|
|
218
|
+
interface PreviewState {
|
|
219
|
+
qa: boolean;
|
|
220
|
+
overrides: Record<string, string>;
|
|
221
|
+
/**
|
|
222
|
+
* What the URL asked for, if anything: `set` to store new cookies, `clear` to remove them.
|
|
223
|
+
* Null when the URL had no preview parameters (keep whatever the cookies say).
|
|
224
|
+
*/
|
|
225
|
+
change: {
|
|
226
|
+
action: "set";
|
|
227
|
+
preview: string;
|
|
228
|
+
} | {
|
|
229
|
+
action: "clear";
|
|
230
|
+
} | null;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Preview links on the server. Read the state once per request and pass `overrides` to
|
|
235
|
+
* experiments as `unit.preview`:
|
|
236
|
+
*
|
|
237
|
+
* const preview = readPreview(request); // or readPreview({ url, cookieHeader })
|
|
238
|
+
* const experiment = experiments.getExperiment({ id, preview: preview.overrides }, "checkout-test");
|
|
239
|
+
* // in middleware / proxy, so the choice survives navigation:
|
|
240
|
+
* for (const cookie of preview.setCookies) response.headers.append("Set-Cookie", cookie);
|
|
241
|
+
*
|
|
242
|
+
* The browser pixel also stores the cookies itself on the page that has the link, so
|
|
243
|
+
* `setCookies` is only needed for server-rendered pages read before the pixel has run.
|
|
244
|
+
*/
|
|
245
|
+
interface ServerPreviewState extends PreviewState {
|
|
246
|
+
/** `Set-Cookie` header values to store (or clear) the preview, empty when nothing changed. */
|
|
247
|
+
setCookies: string[];
|
|
248
|
+
}
|
|
249
|
+
declare function readPreview(input: Request | {
|
|
250
|
+
url: string;
|
|
251
|
+
cookieHeader?: string | null;
|
|
252
|
+
}): ServerPreviewState;
|
|
253
|
+
declare function previewCookies(state: PreviewState): string[];
|
|
254
|
+
|
|
255
|
+
export { type AnalyticsEvent, Assignment, AssignmentUnit, type CollectHandlerOptions, Experiment, type ExperimentConfig, type ExperimentUnit, type Experiments, type ExperimentsOptions, type ExperimentsPayload, type ExperimentsPayloadInput, PREVIEW_PARAM, QA_ENVIRONMENT, QA_PARAM, type ServerAnalytics, type ServerAnalyticsOptions, type ServerEventInput, type ServerPreviewState, createCollectHandler, createExperiments, createServerAnalytics, previewCookies, readPreview };
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import { toEventName, uuid, cleanProps, assign, toExperiment, cookieFromHeader, QA_COOKIE, readPreviewState, PREVIEW_COOKIE, previewAssignment, notFound, EventNames, LIBRARY, QA_MAX_AGE_SECONDS } from './chunk-J4RHGPNT.js';
|
|
2
|
+
export { EventNames, PREVIEW_PARAM, QA_ENVIRONMENT, QA_PARAM } from './chunk-J4RHGPNT.js';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
|
|
5
|
+
// src/server/environment.ts
|
|
6
|
+
function serverEnvironment() {
|
|
7
|
+
return typeof process !== "undefined" && process.env.VERCEL_ENV || "development";
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// src/server/analytics.ts
|
|
11
|
+
function createServerAnalytics(options) {
|
|
12
|
+
const maxBatchSize = Math.min(options.maxBatchSize ?? 100, 100);
|
|
13
|
+
const environment = options.environment ?? serverEnvironment();
|
|
14
|
+
const doFetch = options.fetch ?? fetch;
|
|
15
|
+
const onError = options.onError ?? ((error) => console.error("[analytics] server flush failed:", error));
|
|
16
|
+
const queue = [];
|
|
17
|
+
let inFlight = Promise.resolve();
|
|
18
|
+
async function send(events) {
|
|
19
|
+
try {
|
|
20
|
+
const response = await doFetch(options.endpoint, {
|
|
21
|
+
method: "POST",
|
|
22
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${options.serverKey}` },
|
|
23
|
+
body: JSON.stringify({
|
|
24
|
+
sentAt: Date.now(),
|
|
25
|
+
source: "server",
|
|
26
|
+
environment,
|
|
27
|
+
library: LIBRARY,
|
|
28
|
+
events
|
|
29
|
+
})
|
|
30
|
+
});
|
|
31
|
+
if (!response.ok) onError(new Error(`collector responded ${response.status}: ${await response.text()}`));
|
|
32
|
+
} catch (error) {
|
|
33
|
+
onError(error);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function flush() {
|
|
37
|
+
const batches = [];
|
|
38
|
+
while (queue.length) batches.push(queue.splice(0, maxBatchSize));
|
|
39
|
+
inFlight = inFlight.then(() => Promise.all(batches.map(send)).then(() => {
|
|
40
|
+
}));
|
|
41
|
+
return inFlight;
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
track(input) {
|
|
45
|
+
const { props, name, id, ts, ...rest } = input;
|
|
46
|
+
const event = {
|
|
47
|
+
...rest,
|
|
48
|
+
id: id || uuid(),
|
|
49
|
+
name: toEventName(name),
|
|
50
|
+
ts: ts ?? Date.now()
|
|
51
|
+
};
|
|
52
|
+
const cleaned = cleanProps(props);
|
|
53
|
+
if (cleaned) event.props = cleaned;
|
|
54
|
+
queue.push(event);
|
|
55
|
+
if (queue.length >= maxBatchSize) void flush();
|
|
56
|
+
return event.id;
|
|
57
|
+
},
|
|
58
|
+
flush,
|
|
59
|
+
pending: () => queue.length
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
var variantSchema = z.object({
|
|
63
|
+
key: z.string().min(1).max(64),
|
|
64
|
+
/** Relative weight. Weights do not need to sum to 100. */
|
|
65
|
+
weight: z.number().min(0),
|
|
66
|
+
/** Parameters read with `experiment.get(name, fallback)`, e.g. `{ preselect_3_pack: true }`. */
|
|
67
|
+
params: z.record(z.string(), z.unknown()).default({})
|
|
68
|
+
});
|
|
69
|
+
var targetingSchema = z.object({
|
|
70
|
+
/** ISO 3166 alpha-2, upper case. Empty or missing = all countries. */
|
|
71
|
+
countries: z.array(z.string().length(2)).optional(),
|
|
72
|
+
/** Lower-case language codes, e.g. `en`, `de`. Empty or missing = all locales. */
|
|
73
|
+
locales: z.array(z.string().min(2).max(16)).optional()
|
|
74
|
+
});
|
|
75
|
+
var experimentSchema = z.object({
|
|
76
|
+
key: z.string().min(1).max(128),
|
|
77
|
+
status: z.enum(["running", "launched"]),
|
|
78
|
+
/**
|
|
79
|
+
* Hash salt. Defaults to the key; changing it reshuffles every user, so only do that when
|
|
80
|
+
* restarting a test from scratch.
|
|
81
|
+
*/
|
|
82
|
+
salt: z.string().min(1).max(128),
|
|
83
|
+
/** Share of eligible traffic in the test, 0..1. Raising it only adds users; nobody switches variant. */
|
|
84
|
+
allocation: z.number().min(0).max(1),
|
|
85
|
+
variants: z.array(variantSchema).min(1),
|
|
86
|
+
/** Required when `status` is `launched`: everyone gets this variant and no exposures are logged. */
|
|
87
|
+
launchedVariant: z.string().optional(),
|
|
88
|
+
targeting: targetingSchema.optional()
|
|
89
|
+
});
|
|
90
|
+
var previewConfigSchema = z.object({
|
|
91
|
+
key: z.string().min(1).max(128),
|
|
92
|
+
variants: z.array(variantSchema.pick({ key: true, params: true })).min(1)
|
|
93
|
+
});
|
|
94
|
+
var experimentsPayloadSchema = z.object({
|
|
95
|
+
product: z.string(),
|
|
96
|
+
/** Changes whenever any served experiment changes, so SDKs can skip re-parsing. */
|
|
97
|
+
version: z.string(),
|
|
98
|
+
experiments: z.array(experimentSchema),
|
|
99
|
+
previews: z.array(previewConfigSchema).default([])
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
// src/server/experiments.ts
|
|
103
|
+
var EXPOSURE_CACHE_LIMIT = 5e4;
|
|
104
|
+
function createExperiments(options) {
|
|
105
|
+
const refreshIntervalMs = options.refreshIntervalMs ?? 3e4;
|
|
106
|
+
const timeoutMs = options.timeoutMs ?? 1e3;
|
|
107
|
+
const doFetch = options.fetch ?? fetch;
|
|
108
|
+
const onError = options.onError ?? ((error) => console.error("[analytics] experiments refresh failed:", error));
|
|
109
|
+
const url = `${options.baseUrl.replace(/\/+$/, "")}/api/experiments`;
|
|
110
|
+
let byKey = /* @__PURE__ */ new Map();
|
|
111
|
+
let previewsByKey = /* @__PURE__ */ new Map();
|
|
112
|
+
let currentVersion = null;
|
|
113
|
+
let loadedAt = 0;
|
|
114
|
+
let loading = null;
|
|
115
|
+
const exposed = /* @__PURE__ */ new Set();
|
|
116
|
+
function apply(payload) {
|
|
117
|
+
byKey = new Map(payload.experiments.map((e) => [e.key, e]));
|
|
118
|
+
previewsByKey = new Map(payload.previews.map((e) => [e.key, e]));
|
|
119
|
+
currentVersion = payload.version;
|
|
120
|
+
}
|
|
121
|
+
if (options.initial) {
|
|
122
|
+
apply(experimentsPayloadSchema.parse(options.initial));
|
|
123
|
+
loadedAt = Date.now();
|
|
124
|
+
}
|
|
125
|
+
async function fetchConfig(signal) {
|
|
126
|
+
const response = await doFetch(url, {
|
|
127
|
+
headers: {
|
|
128
|
+
Authorization: `Bearer ${options.serverKey}`,
|
|
129
|
+
...currentVersion ? { "If-None-Match": `"${currentVersion}"` } : {}
|
|
130
|
+
},
|
|
131
|
+
cache: "no-store",
|
|
132
|
+
signal
|
|
133
|
+
});
|
|
134
|
+
if (response.status === 304) return;
|
|
135
|
+
if (!response.ok) throw new Error(`experiments endpoint responded ${response.status}`);
|
|
136
|
+
apply(experimentsPayloadSchema.parse(await response.json()));
|
|
137
|
+
}
|
|
138
|
+
async function load() {
|
|
139
|
+
const controller = new AbortController();
|
|
140
|
+
let timer;
|
|
141
|
+
const timedOut = new Promise((_, reject) => {
|
|
142
|
+
timer = setTimeout(() => {
|
|
143
|
+
const error = new Error(`experiments request timed out after ${timeoutMs} ms`);
|
|
144
|
+
controller.abort(error);
|
|
145
|
+
reject(error);
|
|
146
|
+
}, timeoutMs);
|
|
147
|
+
});
|
|
148
|
+
try {
|
|
149
|
+
await Promise.race([fetchConfig(controller.signal), timedOut]);
|
|
150
|
+
} catch (error) {
|
|
151
|
+
onError(error);
|
|
152
|
+
} finally {
|
|
153
|
+
clearTimeout(timer);
|
|
154
|
+
loadedAt = Date.now();
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
function refresh() {
|
|
158
|
+
if (!loading) {
|
|
159
|
+
loading = load().finally(() => {
|
|
160
|
+
loading = null;
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
return loading;
|
|
164
|
+
}
|
|
165
|
+
function maybeRefresh() {
|
|
166
|
+
if (Date.now() - loadedAt > refreshIntervalMs) void refresh();
|
|
167
|
+
}
|
|
168
|
+
function forced(unit, key) {
|
|
169
|
+
const variant = unit.preview?.[key];
|
|
170
|
+
if (!variant) return null;
|
|
171
|
+
const config = byKey.get(key) ?? previewsByKey.get(key);
|
|
172
|
+
return config ? previewAssignment(config, variant) : null;
|
|
173
|
+
}
|
|
174
|
+
function resolve(unit, key) {
|
|
175
|
+
maybeRefresh();
|
|
176
|
+
const preview = forced(unit, key);
|
|
177
|
+
if (preview) return preview;
|
|
178
|
+
const config = byKey.get(key);
|
|
179
|
+
return config ? assign(config, unit) : notFound(key);
|
|
180
|
+
}
|
|
181
|
+
function logExposure(unit, assignment) {
|
|
182
|
+
if (!options.analytics || assignment.reason !== "assigned" || !assignment.variant) return;
|
|
183
|
+
const cacheKey = `${assignment.experiment}\0${assignment.variant}\0${unit.id}`;
|
|
184
|
+
if (exposed.has(cacheKey)) return;
|
|
185
|
+
exposed.add(cacheKey);
|
|
186
|
+
if (exposed.size > EXPOSURE_CACHE_LIMIT) exposed.delete(exposed.values().next().value);
|
|
187
|
+
options.analytics.track({
|
|
188
|
+
name: EventNames.ExperimentExposure,
|
|
189
|
+
anonymousId: unit.id,
|
|
190
|
+
...unit.userId && { userId: unit.userId },
|
|
191
|
+
...unit.url && { url: unit.url },
|
|
192
|
+
experiments: { [assignment.experiment]: assignment.variant },
|
|
193
|
+
props: {
|
|
194
|
+
experiment: assignment.experiment,
|
|
195
|
+
variant: assignment.variant,
|
|
196
|
+
...unit.country && { country: unit.country },
|
|
197
|
+
...unit.locale && { locale: unit.locale }
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
return {
|
|
202
|
+
ready: () => loadedAt ? Promise.resolve() : refresh(),
|
|
203
|
+
getExperiment(unit, key) {
|
|
204
|
+
const assignment = resolve(unit, key);
|
|
205
|
+
logExposure(unit, assignment);
|
|
206
|
+
return toExperiment(assignment);
|
|
207
|
+
},
|
|
208
|
+
peek: (unit, key) => toExperiment(resolve(unit, key)),
|
|
209
|
+
getAssignments(unit) {
|
|
210
|
+
maybeRefresh();
|
|
211
|
+
const out = {};
|
|
212
|
+
for (const config of byKey.values()) {
|
|
213
|
+
if (config.status !== "running") continue;
|
|
214
|
+
const assignment = assign(config, unit);
|
|
215
|
+
if (assignment.reason === "assigned" && assignment.variant) out[config.key] = assignment.variant;
|
|
216
|
+
}
|
|
217
|
+
for (const key of Object.keys(unit.preview ?? {})) {
|
|
218
|
+
const assignment = forced(unit, key);
|
|
219
|
+
if (assignment?.variant) out[key] = assignment.variant;
|
|
220
|
+
}
|
|
221
|
+
return out;
|
|
222
|
+
},
|
|
223
|
+
getClientBootstrap(unit) {
|
|
224
|
+
maybeRefresh();
|
|
225
|
+
const assignments = {};
|
|
226
|
+
for (const config of byKey.values()) assignments[config.key] = assign(config, unit);
|
|
227
|
+
for (const key of Object.keys(unit.preview ?? {})) {
|
|
228
|
+
const assignment = forced(unit, key);
|
|
229
|
+
if (assignment) assignments[key] = assignment;
|
|
230
|
+
}
|
|
231
|
+
return { assignments, environment: serverEnvironment() };
|
|
232
|
+
},
|
|
233
|
+
refresh,
|
|
234
|
+
version: () => currentVersion
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// ../schema/src/forwarding.ts
|
|
239
|
+
var FORWARD_HEADERS = {
|
|
240
|
+
/** Marks a forwarded browser batch: stored as `source: "client"` and bot-filtered. */
|
|
241
|
+
forwarded: "x-fya-forwarded",
|
|
242
|
+
userAgent: "x-fya-client-user-agent",
|
|
243
|
+
country: "x-fya-client-country",
|
|
244
|
+
region: "x-fya-client-region",
|
|
245
|
+
city: "x-fya-client-city"
|
|
246
|
+
};
|
|
247
|
+
var VERCEL_GEO_HEADERS = {
|
|
248
|
+
"x-vercel-ip-country": FORWARD_HEADERS.country,
|
|
249
|
+
"x-vercel-ip-country-region": FORWARD_HEADERS.region,
|
|
250
|
+
"x-vercel-ip-city": FORWARD_HEADERS.city
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
// src/server/collect-handler.ts
|
|
254
|
+
var MAX_BODY_BYTES = 512 * 1024;
|
|
255
|
+
function createCollectHandler(options) {
|
|
256
|
+
const doFetch = options.fetch ?? fetch;
|
|
257
|
+
const environment = options.environment ?? serverEnvironment();
|
|
258
|
+
const onError = options.onError ?? ((error) => console.error("[analytics] collect forward failed:", error));
|
|
259
|
+
return async function collect(request) {
|
|
260
|
+
if (request.method !== "POST") return new Response(null, { status: 405, headers: { Allow: "POST" } });
|
|
261
|
+
if (Number(request.headers.get("content-length") ?? 0) > MAX_BODY_BYTES) return new Response(null, { status: 413 });
|
|
262
|
+
const raw = await request.text();
|
|
263
|
+
if (raw.length > MAX_BODY_BYTES) return new Response(null, { status: 413 });
|
|
264
|
+
const qa = Boolean(cookieFromHeader(request.headers.get("cookie"), QA_COOKIE));
|
|
265
|
+
const body = withBatchFields(raw, environment, qa);
|
|
266
|
+
const headers = new Headers({
|
|
267
|
+
"Content-Type": "application/json",
|
|
268
|
+
Authorization: `Bearer ${options.serverKey}`,
|
|
269
|
+
[FORWARD_HEADERS.forwarded]: "1"
|
|
270
|
+
});
|
|
271
|
+
const userAgent = request.headers.get("user-agent");
|
|
272
|
+
if (userAgent) headers.set(FORWARD_HEADERS.userAgent, userAgent);
|
|
273
|
+
for (const [vercel, forwarded] of Object.entries(VERCEL_GEO_HEADERS)) {
|
|
274
|
+
const value = request.headers.get(vercel);
|
|
275
|
+
if (value) headers.set(forwarded, value);
|
|
276
|
+
}
|
|
277
|
+
try {
|
|
278
|
+
const response = await doFetch(options.collectorUrl, { method: "POST", headers, body });
|
|
279
|
+
if (response.status >= 500) onError(new Error(`collector responded ${response.status}`));
|
|
280
|
+
return new Response(null, { status: response.ok ? 204 : response.status });
|
|
281
|
+
} catch (error) {
|
|
282
|
+
onError(error);
|
|
283
|
+
return new Response(null, { status: 502 });
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
function withBatchFields(body, environment, qa) {
|
|
288
|
+
try {
|
|
289
|
+
const batch = JSON.parse(body);
|
|
290
|
+
if (!batch || typeof batch !== "object" || Array.isArray(batch)) return body;
|
|
291
|
+
return JSON.stringify({ ...batch, environment, ...qa && { qa: true } });
|
|
292
|
+
} catch {
|
|
293
|
+
return body;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// src/server/preview.ts
|
|
298
|
+
function readPreview(input) {
|
|
299
|
+
const url = input.url;
|
|
300
|
+
const cookieHeader = input instanceof Request ? input.headers.get("cookie") : input.cookieHeader;
|
|
301
|
+
let search = "";
|
|
302
|
+
try {
|
|
303
|
+
search = new URL(url, "http://localhost").search;
|
|
304
|
+
} catch {
|
|
305
|
+
}
|
|
306
|
+
const state = readPreviewState(search, (name) => cookieFromHeader(cookieHeader, name));
|
|
307
|
+
return { ...state, setCookies: previewCookies(state) };
|
|
308
|
+
}
|
|
309
|
+
function cookie(name, value, maxAge) {
|
|
310
|
+
return `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=${maxAge}; SameSite=Lax; Secure`;
|
|
311
|
+
}
|
|
312
|
+
function previewCookies(state) {
|
|
313
|
+
if (!state.change) return [];
|
|
314
|
+
if (state.change.action === "clear") return [cookie(PREVIEW_COOKIE, "", 0), cookie(QA_COOKIE, "", 0)];
|
|
315
|
+
return [
|
|
316
|
+
cookie(QA_COOKIE, "1", QA_MAX_AGE_SECONDS),
|
|
317
|
+
state.change.preview ? cookie(PREVIEW_COOKIE, state.change.preview, QA_MAX_AGE_SECONDS) : cookie(PREVIEW_COOKIE, "", 0)
|
|
318
|
+
];
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
export { createCollectHandler, createExperiments, createServerAnalytics, previewCookies, readPreview };
|
|
322
|
+
//# sourceMappingURL=server.js.map
|
|
323
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/environment.ts","../src/server/analytics.ts","../../schema/src/experiments.ts","../src/server/experiments.ts","../../schema/src/forwarding.ts","../src/server/collect-handler.ts","../src/server/preview.ts"],"names":[],"mappings":";;;;;AAKO,SAAS,iBAAA,GAA4B;AAC1C,EAAA,OAAQ,OAAO,OAAA,KAAY,WAAA,IAAe,OAAA,CAAQ,IAAI,UAAA,IAAe,aAAA;AACvE;;;ACgCO,SAAS,sBAAsB,OAAA,EAAkD;AACtF,EAAA,MAAM,eAAe,IAAA,CAAK,GAAA,CAAI,OAAA,CAAQ,YAAA,IAAgB,KAAK,GAAG,CAAA;AAC9D,EAAA,MAAM,WAAA,GAAc,OAAA,CAAQ,WAAA,IAAe,iBAAA,EAAkB;AAC7D,EAAA,MAAM,OAAA,GAAU,QAAQ,KAAA,IAAS,KAAA;AACjC,EAAA,MAAM,OAAA,GAAU,QAAQ,OAAA,KAAY,CAAC,UAAU,OAAA,CAAQ,KAAA,CAAM,oCAAoC,KAAK,CAAA,CAAA;AACtG,EAAA,MAAM,QAA0B,EAAC;AACjC,EAAA,IAAI,QAAA,GAA0B,QAAQ,OAAA,EAAQ;AAE9C,EAAA,eAAe,KAAK,MAAA,EAA0B;AAC5C,IAAA,IAAI;AACF,MAAA,MAAM,QAAA,GAAW,MAAM,OAAA,CAAQ,OAAA,CAAQ,QAAA,EAAU;AAAA,QAC/C,MAAA,EAAQ,MAAA;AAAA,QACR,OAAA,EAAS,EAAE,cAAA,EAAgB,kBAAA,EAAoB,eAAe,CAAA,OAAA,EAAU,OAAA,CAAQ,SAAS,CAAA,CAAA,EAAG;AA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A;AAAA,EAC5C,CAAA,CAAA,MAAQ;AAAA,EAER;AACA,EAAA,MAAM,KAAA,GAAQ,iBAAiB,MAAA,EAAQ,CAAC,SAAS,gBAAA,CAAiB,YAAA,EAAc,IAAI,CAAC,CAAA;AAErF,EAAA,OAAO,EAAE,GAAG,KAAA,EAAO,UAAA,EAAY,cAAA,CAAe,KAAK,CAAA,EAAE;AACvD;AAEA,SAAS,MAAA,CAAO,IAAA,EAAc,KAAA,EAAe,MAAA,EAAgB;AAC3D,EAAA,OAAO,GAAG,IAAI,CAAA,CAAA,EAAI,mBAAmB,KAAK,CAAC,qBAAqB,MAAM,CAAA,sBAAA,CAAA;AACxE;AAEO,SAAS,eAAe,KAAA,EAA+B;AAC5D,EAAA,IAAI,CAAC,KAAA,CAAM,MAAA,EAAQ,OAAO,EAAC;AAC3B,EAAA,IAAI,KAAA,CAAM,MAAA,CAAO,MAAA,KAAW,OAAA,SAAgB,CAAC,MAAA,CAAO,cAAA,EAAgB,EAAA,EAAI,CAAC,CAAA,EAAG,MAAA,CAAO,SAAA,EAAW,EAAA,EAAI,CAAC,CAAC,CAAA;AAEpG,EAAA,OAAO;AAAA,IACL,MAAA,CAAO,SAAA,EAAW,GAAA,EAAK,kBAAkB,CAAA;AAAA,IACzC,KAAA,CAAM,MAAA,CAAO,OAAA,GAAU,MAAA,CAAO,cAAA,EAAgB,KAAA,CAAM,MAAA,CAAO,OAAA,EAAS,kBAAkB,CAAA,GAAI,MAAA,CAAO,cAAA,EAAgB,IAAI,CAAC;AAAA,GACxH;AACF","file":"server.js","sourcesContent":["/**\n * Deployment tier of the app this SDK runs in: Vercel's `VERCEL_ENV` (`production`, `preview`,\n * `development`), or `development` when it is unset (local runs, tests). Apps not hosted on\n * Vercel pass `environment` explicitly.\n */\nexport function serverEnvironment(): string {\n return (typeof process !== \"undefined\" && process.env.VERCEL_ENV) || \"development\";\n}\n","import type { AnalyticsEvent } from \"@faceyoga/analytics-schema/events\";\nimport { cleanProps, LIBRARY, toEventName, uuid } from \"../shared/util\";\nimport { serverEnvironment } from \"./environment\";\n\n/**\n * Server-side event sender for events that originate on the server (pithos `dispatchTrackingEvent`,\n * upsell charges from cron, webhook-driven purchases) and for experiment exposures.\n *\n * Serverless functions freeze after the response, so nothing is sent on a timer: queue with\n * `track()` and call `flush()` inside Next.js `after()` (or `waitUntil`) before the request ends.\n */\n\nexport interface ServerAnalyticsOptions {\n /** Collector URL, e.g. `https://analytics.example.com/api/collect`. */\n endpoint: string;\n /** Secret server key for the product. Never ship it to the browser. */\n serverKey: string;\n /** `production` | `preview` | `development`. Default: `VERCEL_ENV`, or `development` when unset. */\n environment?: string;\n /** Flush automatically once this many events are queued. Default 100 (the batch cap). */\n maxBatchSize?: number;\n fetch?: typeof fetch;\n onError?: (error: unknown) => void;\n}\n\nexport type ServerEventInput = Omit<AnalyticsEvent, \"id\" | \"ts\" | \"name\" | \"props\"> & {\n name: string;\n id?: string;\n ts?: number;\n props?: Record<string, unknown>;\n};\n\nexport interface ServerAnalytics {\n track(event: ServerEventInput): string;\n flush(): Promise<void>;\n /** Events waiting to be sent. */\n pending(): number;\n}\n\nexport function createServerAnalytics(options: ServerAnalyticsOptions): ServerAnalytics {\n const maxBatchSize = Math.min(options.maxBatchSize ?? 100, 100);\n const environment = options.environment ?? serverEnvironment();\n const doFetch = options.fetch ?? fetch;\n const onError = options.onError ?? ((error) => console.error(\"[analytics] server flush failed:\", error));\n const queue: AnalyticsEvent[] = [];\n let inFlight: Promise<void> = Promise.resolve();\n\n async function send(events: AnalyticsEvent[]) {\n try {\n const response = await doFetch(options.endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", Authorization: `Bearer ${options.serverKey}` },\n body: JSON.stringify({\n sentAt: Date.now(),\n source: \"server\",\n environment,\n library: LIBRARY,\n events,\n }),\n });\n if (!response.ok) onError(new Error(`collector responded ${response.status}: ${await response.text()}`));\n } catch (error) {\n onError(error);\n }\n }\n\n function flush(): Promise<void> {\n const batches: AnalyticsEvent[][] = [];\n while (queue.length) batches.push(queue.splice(0, maxBatchSize));\n inFlight = inFlight.then(() => Promise.all(batches.map(send)).then(() => {}));\n\n return inFlight;\n }\n\n return {\n track(input) {\n const { props, name, id, ts, ...rest } = input;\n const event: AnalyticsEvent = {\n ...rest,\n id: id || uuid(),\n name: toEventName(name),\n ts: ts ?? Date.now(),\n };\n const cleaned = cleanProps(props);\n if (cleaned) event.props = cleaned;\n queue.push(event);\n if (queue.length >= maxBatchSize) void flush();\n\n return event.id;\n },\n flush,\n pending: () => queue.length,\n };\n}\n","import { z } from \"zod\";\n\n/**\n * Experiment config as served to SDKs by `GET /api/experiments`. Only `running` and `launched`\n * experiments are sent; drafts and stopped tests never reach a storefront. The source of truth\n * is the `experiments` / `experiment_variants` tables in Turso.\n */\n\nexport const variantSchema = z.object({\n key: z.string().min(1).max(64),\n /** Relative weight. Weights do not need to sum to 100. */\n weight: z.number().min(0),\n /** Parameters read with `experiment.get(name, fallback)`, e.g. `{ preselect_3_pack: true }`. */\n params: z.record(z.string(), z.unknown()).default({}),\n});\n\nexport const targetingSchema = z.object({\n /** ISO 3166 alpha-2, upper case. Empty or missing = all countries. */\n countries: z.array(z.string().length(2)).optional(),\n /** Lower-case language codes, e.g. `en`, `de`. Empty or missing = all locales. */\n locales: z.array(z.string().min(2).max(16)).optional(),\n});\n\nexport const experimentSchema = z.object({\n key: z.string().min(1).max(128),\n status: z.enum([\"running\", \"launched\"]),\n /**\n * Hash salt. Defaults to the key; changing it reshuffles every user, so only do that when\n * restarting a test from scratch.\n */\n salt: z.string().min(1).max(128),\n /** Share of eligible traffic in the test, 0..1. Raising it only adds users; nobody switches variant. */\n allocation: z.number().min(0).max(1),\n variants: z.array(variantSchema).min(1),\n /** Required when `status` is `launched`: everyone gets this variant and no exposures are logged. */\n launchedVariant: z.string().optional(),\n targeting: targetingSchema.optional(),\n});\n\n/**\n * Draft and stopped experiments, served only so preview links can force their variants. Never\n * assigned to normal visitors. SDKs from before preview links ignore this field.\n */\nexport const previewConfigSchema = z.object({\n key: z.string().min(1).max(128),\n variants: z.array(variantSchema.pick({ key: true, params: true })).min(1),\n});\n\nexport const experimentsPayloadSchema = z.object({\n product: z.string(),\n /** Changes whenever any served experiment changes, so SDKs can skip re-parsing. */\n version: z.string(),\n experiments: z.array(experimentSchema),\n previews: z.array(previewConfigSchema).default([]),\n});\n\nexport type Variant = z.infer<typeof variantSchema>;\nexport type Targeting = z.infer<typeof targetingSchema>;\nexport type ExperimentConfig = z.infer<typeof experimentSchema>;\nexport type PreviewConfig = z.infer<typeof previewConfigSchema>;\nexport type ExperimentsPayload = z.infer<typeof experimentsPayloadSchema>;\n/** What the endpoint may send: `previews` is optional so older servers still parse. */\nexport type ExperimentsPayloadInput = z.input<typeof experimentsPayloadSchema>;\n","import {\n experimentsPayloadSchema,\n type ExperimentConfig,\n type ExperimentsPayload,\n type ExperimentsPayloadInput,\n type PreviewConfig,\n} from \"@faceyoga/analytics-schema/experiments\";\nimport {\n assign,\n notFound,\n previewAssignment,\n type Assignment,\n type AssignmentUnit,\n} from \"@faceyoga/analytics-schema/assign\";\nimport { EventNames } from \"@faceyoga/analytics-schema/names\";\nimport { toExperiment, type Experiment } from \"../shared/experiment\";\nimport type { ServerAnalytics } from \"./analytics\";\nimport { serverEnvironment } from \"./environment\";\n\n/**\n * Server-side experiments, the replacement for `statsig.getExperiment(user, name)`.\n *\n * Config is fetched from the analytics app and kept in memory; assignment is a local hash, so\n * `getExperiment` never waits on the network once `ready()` has resolved. Stale config is\n * refreshed in the background on the next read after `refreshIntervalMs`.\n */\n\nexport interface ExperimentsOptions {\n /** Analytics app base URL, e.g. `https://analytics.example.com`. */\n baseUrl: string;\n serverKey: string;\n /** Exposures are queued here; flush it in `after()`. Without it no exposures are logged. */\n analytics?: ServerAnalytics;\n refreshIntervalMs?: number;\n /**\n * Max wait for one config request. On timeout or error the last loaded config is kept, or\n * every `get()` returns its fallback when none was loaded. Default 1000 ms.\n */\n timeoutMs?: number;\n /** Seed config, e.g. a build-time snapshot, so the very first request has values. */\n initial?: ExperimentsPayloadInput;\n fetch?: typeof fetch;\n onError?: (error: unknown) => void;\n}\n\nexport interface ExperimentUnit extends AssignmentUnit {\n /** Logged-in user id, copied onto exposure events. */\n userId?: string;\n /** Page URL, copied onto exposure events. */\n url?: string;\n /**\n * Variants forced by a preview link (`readPreview(...).overrides`): experiment key -> variant.\n * Forced variants work for drafts too and never log exposures.\n */\n preview?: Record<string, string>;\n}\n\nexport interface Experiments {\n /**\n * Resolves after the first config load, at most `timeoutMs` later (immediately when `initial`\n * was given). Never rejects; failures go to `onError`.\n */\n ready(): Promise<void>;\n /** Assign and log one exposure (per unit and experiment, per instance) when the user is in the test. */\n getExperiment(unit: ExperimentUnit, key: string): Experiment;\n /** Assign without logging an exposure, e.g. to decide what to prefetch. */\n peek(unit: ExperimentUnit, key: string): Experiment;\n /** Experiment key -> variant for every test the unit is in (forced variants included). Tag client events with this. */\n getAssignments(unit: ExperimentUnit): Record<string, string>;\n /** Everything a browser needs to evaluate experiments locally (Hoola-style client reads). */\n getClientBootstrap(unit: ExperimentUnit): { assignments: Record<string, Assignment>; environment: string };\n /** Force a config reload. */\n refresh(): Promise<void>;\n /** Version of the config currently in memory, or null before the first load. */\n version(): string | null;\n}\n\nconst EXPOSURE_CACHE_LIMIT = 50_000;\n\nexport function createExperiments(options: ExperimentsOptions): Experiments {\n const refreshIntervalMs = options.refreshIntervalMs ?? 30_000;\n const timeoutMs = options.timeoutMs ?? 1_000;\n const doFetch = options.fetch ?? fetch;\n const onError = options.onError ?? ((error) => console.error(\"[analytics] experiments refresh failed:\", error));\n const url = `${options.baseUrl.replace(/\\/+$/, \"\")}/api/experiments`;\n\n let byKey = new Map<string, ExperimentConfig>();\n let previewsByKey = new Map<string, PreviewConfig>();\n let currentVersion: string | null = null;\n let loadedAt = 0;\n let loading: Promise<void> | null = null;\n // Insertion-ordered set used as a small LRU so exposures are logged once per user per instance.\n const exposed = new Set<string>();\n\n function apply(payload: ExperimentsPayload) {\n byKey = new Map(payload.experiments.map((e) => [e.key, e]));\n previewsByKey = new Map(payload.previews.map((e) => [e.key, e]));\n currentVersion = payload.version;\n }\n\n if (options.initial) {\n apply(experimentsPayloadSchema.parse(options.initial));\n loadedAt = Date.now();\n }\n\n async function fetchConfig(signal: AbortSignal): Promise<void> {\n const response = await doFetch(url, {\n headers: {\n Authorization: `Bearer ${options.serverKey}`,\n ...(currentVersion ? { \"If-None-Match\": `\"${currentVersion}\"` } : {}),\n },\n cache: \"no-store\",\n signal,\n });\n if (response.status === 304) return;\n if (!response.ok) throw new Error(`experiments endpoint responded ${response.status}`);\n apply(experimentsPayloadSchema.parse(await response.json()));\n }\n\n async function load(): Promise<void> {\n // The timer also bounds a custom fetch that ignores the abort signal.\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timedOut = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const error = new Error(`experiments request timed out after ${timeoutMs} ms`);\n controller.abort(error);\n reject(error);\n }, timeoutMs);\n });\n\n try {\n await Promise.race([fetchConfig(controller.signal), timedOut]);\n } catch (error) {\n // Keep serving the last good config (or fallbacks when there is none).\n onError(error);\n } finally {\n clearTimeout(timer);\n loadedAt = Date.now();\n }\n }\n\n function refresh(): Promise<void> {\n if (!loading) {\n loading = load().finally(() => {\n loading = null;\n });\n }\n\n return loading;\n }\n\n function maybeRefresh() {\n if (Date.now() - loadedAt > refreshIntervalMs) void refresh();\n }\n\n function forced(unit: ExperimentUnit, key: string): Assignment | null {\n const variant = unit.preview?.[key];\n if (!variant) return null;\n const config = byKey.get(key) ?? previewsByKey.get(key);\n\n return config ? previewAssignment(config, variant) : null;\n }\n\n function resolve(unit: ExperimentUnit, key: string): Assignment {\n maybeRefresh();\n const preview = forced(unit, key);\n if (preview) return preview;\n const config = byKey.get(key);\n\n return config ? assign(config, unit) : notFound(key);\n }\n\n function logExposure(unit: ExperimentUnit, assignment: Assignment) {\n if (!options.analytics || assignment.reason !== \"assigned\" || !assignment.variant) return;\n const cacheKey = `${assignment.experiment}\\u0000${assignment.variant}\\u0000${unit.id}`;\n if (exposed.has(cacheKey)) return;\n exposed.add(cacheKey);\n if (exposed.size > EXPOSURE_CACHE_LIMIT) exposed.delete(exposed.values().next().value!);\n\n options.analytics.track({\n name: EventNames.ExperimentExposure,\n anonymousId: unit.id,\n ...(unit.userId && { userId: unit.userId }),\n ...(unit.url && { url: unit.url }),\n experiments: { [assignment.experiment]: assignment.variant },\n props: {\n experiment: assignment.experiment,\n variant: assignment.variant,\n ...(unit.country && { country: unit.country }),\n ...(unit.locale && { locale: unit.locale }),\n },\n });\n }\n\n return {\n ready: () => (loadedAt ? Promise.resolve() : refresh()),\n getExperiment(unit, key) {\n const assignment = resolve(unit, key);\n logExposure(unit, assignment);\n\n return toExperiment(assignment);\n },\n peek: (unit, key) => toExperiment(resolve(unit, key)),\n getAssignments(unit) {\n maybeRefresh();\n const out: Record<string, string> = {};\n for (const config of byKey.values()) {\n if (config.status !== \"running\") continue;\n const assignment = assign(config, unit);\n if (assignment.reason === \"assigned\" && assignment.variant) out[config.key] = assignment.variant;\n }\n for (const key of Object.keys(unit.preview ?? {})) {\n const assignment = forced(unit, key);\n if (assignment?.variant) out[key] = assignment.variant;\n }\n\n return out;\n },\n getClientBootstrap(unit) {\n maybeRefresh();\n const assignments: Record<string, Assignment> = {};\n for (const config of byKey.values()) assignments[config.key] = assign(config, unit);\n for (const key of Object.keys(unit.preview ?? {})) {\n const assignment = forced(unit, key);\n if (assignment) assignments[key] = assignment;\n }\n\n return { assignments, environment: serverEnvironment() };\n },\n refresh,\n version: () => currentVersion,\n };\n}\n","/**\n * Headers a storefront's same-origin collect route (`createCollectHandler`) adds when it forwards\n * a browser batch to the collector with its server key. The storefront sees the visitor's\n * Vercel geo headers and user agent; the collector, receiving a server-to-server request, does\n * not. The collector honours these only on requests authenticated with a server key.\n */\nexport const FORWARD_HEADERS = {\n /** Marks a forwarded browser batch: stored as `source: \"client\"` and bot-filtered. */\n forwarded: \"x-fya-forwarded\",\n userAgent: \"x-fya-client-user-agent\",\n country: \"x-fya-client-country\",\n region: \"x-fya-client-region\",\n city: \"x-fya-client-city\",\n} as const;\n\n/** Vercel request headers on the storefront, mapped to the forwarding header that carries each. */\nexport const VERCEL_GEO_HEADERS = {\n \"x-vercel-ip-country\": FORWARD_HEADERS.country,\n \"x-vercel-ip-country-region\": FORWARD_HEADERS.region,\n \"x-vercel-ip-city\": FORWARD_HEADERS.city,\n} as const;\n","import { FORWARD_HEADERS, VERCEL_GEO_HEADERS } from \"@faceyoga/analytics-schema/forwarding\";\nimport { cookieFromHeader, QA_COOKIE } from \"@faceyoga/analytics-schema/preview\";\nimport { serverEnvironment } from \"./environment\";\n\n/**\n * Same-origin collect route for a storefront. The browser pixel posts to `/a/collect` on the\n * storefront itself, which:\n * - keeps analytics requests first-party, so ad blockers and CORS never get involved;\n * - means the browser needs no key at all: this route signs the batch with the server key;\n * - forwards the visitor's Vercel geo headers and user agent, which the collector would not\n * see on a server-to-server request (or reliably through a rewrite);\n * - stamps the batch with this deployment's environment, so preview and local traffic is never\n * counted as production whatever the browser sent;\n * - marks the batch as QA when the visitor opened a preview link (`fy_qa` cookie), so the\n * collector stores it as `test` even if the page runs an older pixel.\n *\n * // app/a/collect/route.ts\n * export const POST = createCollectHandler({\n * collectorUrl: `${process.env.ANALYTICS_URL}/api/collect`,\n * serverKey: process.env.ANALYTICS_SERVER_KEY!,\n * });\n *\n * The collector answers before it writes to Axiom, so awaiting it adds little latency, and its\n * status is passed back so the pixel retries on 429 / 5xx.\n */\n\nexport interface CollectHandlerOptions {\n /** Collector URL, e.g. `https://analytics.example.com/api/collect`. */\n collectorUrl: string;\n /** Secret server key for the product. */\n serverKey: string;\n /** Overrides the batch's `environment`. Default: `VERCEL_ENV`, or `development` when unset. */\n environment?: string;\n fetch?: typeof fetch;\n onError?: (error: unknown) => void;\n}\n\n/** Same cap as the collector. */\nconst MAX_BODY_BYTES = 512 * 1024;\n\nexport function createCollectHandler(options: CollectHandlerOptions): (request: Request) => Promise<Response> {\n const doFetch = options.fetch ?? fetch;\n const environment = options.environment ?? serverEnvironment();\n const onError = options.onError ?? ((error) => console.error(\"[analytics] collect forward failed:\", error));\n\n return async function collect(request) {\n if (request.method !== \"POST\") return new Response(null, { status: 405, headers: { Allow: \"POST\" } });\n if (Number(request.headers.get(\"content-length\") ?? 0) > MAX_BODY_BYTES) return new Response(null, { status: 413 });\n\n const raw = await request.text();\n if (raw.length > MAX_BODY_BYTES) return new Response(null, { status: 413 });\n const qa = Boolean(cookieFromHeader(request.headers.get(\"cookie\"), QA_COOKIE));\n const body = withBatchFields(raw, environment, qa);\n\n const headers = new Headers({\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${options.serverKey}`,\n [FORWARD_HEADERS.forwarded]: \"1\",\n });\n const userAgent = request.headers.get(\"user-agent\");\n if (userAgent) headers.set(FORWARD_HEADERS.userAgent, userAgent);\n for (const [vercel, forwarded] of Object.entries(VERCEL_GEO_HEADERS)) {\n const value = request.headers.get(vercel);\n if (value) headers.set(forwarded, value);\n }\n\n try {\n const response = await doFetch(options.collectorUrl, { method: \"POST\", headers, body });\n if (response.status >= 500) onError(new Error(`collector responded ${response.status}`));\n\n return new Response(null, { status: response.ok ? 204 : response.status });\n } catch (error) {\n onError(error);\n\n return new Response(null, { status: 502 });\n }\n };\n}\n\n/**\n * Sets `environment` (and `qa` when the visitor is in QA mode) on a JSON batch. Anything that is\n * not a JSON object is forwarded unchanged for the collector to reject.\n */\nfunction withBatchFields(body: string, environment: string, qa: boolean): string {\n try {\n const batch: unknown = JSON.parse(body);\n if (!batch || typeof batch !== \"object\" || Array.isArray(batch)) return body;\n\n return JSON.stringify({ ...batch, environment, ...(qa && { qa: true }) });\n } catch {\n return body;\n }\n}\n","import {\n cookieFromHeader,\n PREVIEW_COOKIE,\n QA_COOKIE,\n QA_MAX_AGE_SECONDS,\n readPreviewState,\n type PreviewState,\n} from \"@faceyoga/analytics-schema/preview\";\n\n/**\n * Preview links on the server. Read the state once per request and pass `overrides` to\n * experiments as `unit.preview`:\n *\n * const preview = readPreview(request); // or readPreview({ url, cookieHeader })\n * const experiment = experiments.getExperiment({ id, preview: preview.overrides }, \"checkout-test\");\n * // in middleware / proxy, so the choice survives navigation:\n * for (const cookie of preview.setCookies) response.headers.append(\"Set-Cookie\", cookie);\n *\n * The browser pixel also stores the cookies itself on the page that has the link, so\n * `setCookies` is only needed for server-rendered pages read before the pixel has run.\n */\n\nexport interface ServerPreviewState extends PreviewState {\n /** `Set-Cookie` header values to store (or clear) the preview, empty when nothing changed. */\n setCookies: string[];\n}\n\nexport function readPreview(input: Request | { url: string; cookieHeader?: string | null }): ServerPreviewState {\n const url = input.url;\n const cookieHeader = input instanceof Request ? input.headers.get(\"cookie\") : input.cookieHeader;\n let search = \"\";\n try {\n search = new URL(url, \"http://localhost\").search;\n } catch {\n // Not a URL: cookies only.\n }\n const state = readPreviewState(search, (name) => cookieFromHeader(cookieHeader, name));\n\n return { ...state, setCookies: previewCookies(state) };\n}\n\nfunction cookie(name: string, value: string, maxAge: number) {\n return `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=${maxAge}; SameSite=Lax; Secure`;\n}\n\nexport function previewCookies(state: PreviewState): string[] {\n if (!state.change) return [];\n if (state.change.action === \"clear\") return [cookie(PREVIEW_COOKIE, \"\", 0), cookie(QA_COOKIE, \"\", 0)];\n\n return [\n cookie(QA_COOKIE, \"1\", QA_MAX_AGE_SECONDS),\n state.change.preview ? cookie(PREVIEW_COOKIE, state.change.preview, QA_MAX_AGE_SECONDS) : cookie(PREVIEW_COOKIE, \"\", 0),\n ];\n}\n"]}
|