@founderhq/journeys 0.8.1 → 0.9.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.
@@ -970,6 +970,22 @@ export { evaluateCondition as evaluateCondition_alias_1 }
970
970
 
971
971
  export declare function evaluateSafeExpression(expression: string, scope: Scope): unknown;
972
972
 
973
+ /** `fhq_consent_<fingerprint>` — the cookie the events SDK remembers consent in. */
974
+ export declare function eventsConsentCookieName(apiKey: string): string;
975
+
976
+ /**
977
+ * `fhq_id_<key without punctuation, first 16 characters>` — the identity
978
+ * cookie the events SDK shares across subdomains. On init the SDK lets it
979
+ * win over this origin's stored copy, so a visitor identified on `www` is
980
+ * the same person on `app`; the journey reads it for the same reason.
981
+ */
982
+ export declare function eventsIdentityCookieName(apiKey: string): string;
983
+
984
+ /** `founderhq:events:v2:<first 16 characters of the key>` — the events SDK's key. */
985
+ declare function eventsStorageKey(apiKey: string): string;
986
+ export { eventsStorageKey }
987
+ export { eventsStorageKey as eventsStorageKey_alias_1 }
988
+
973
989
  declare type ExitAnimationPreset = "fade-out" | "slide-up" | "slide-down" | "slide-left" | "slide-right" | "scale-down" | "blur-out" | "none";
974
990
  export { ExitAnimationPreset }
975
991
  export { ExitAnimationPreset as ExitAnimationPreset_alias_1 }
@@ -1013,6 +1029,9 @@ declare type FetchState = {
1013
1029
  export { FetchState }
1014
1030
  export { FetchState as FetchState_alias_1 }
1015
1031
 
1032
+ /** The hosted events snippet publishes its client as `globalThis.founderhq`. */
1033
+ export declare function findGlobalEventsClient(): JourneyEventsClient | null;
1034
+
1016
1035
  export declare function FloatingLabelBlock({ text, variant, color, gradient, className, }: FloatingLabelBlockProps): JSX.Element;
1017
1036
 
1018
1037
  declare type FloatingLabelBlockProps = {
@@ -1267,6 +1286,17 @@ declare type JourneyCaptureConfig = JourneyCaptureOptions & {
1267
1286
  baseUrl: string;
1268
1287
  };
1269
1288
 
1289
+ declare type JourneyCaptureIdentity = {
1290
+ anonymousId?: string;
1291
+ distinctId?: string;
1292
+ /** The analytics session id, known only when an events client is present. */
1293
+ sessionId?: string;
1294
+ /** Where the ids came from; "none" means the visit is cookieless. */
1295
+ source: "events" | "storage" | "none";
1296
+ };
1297
+ export { JourneyCaptureIdentity }
1298
+ export { JourneyCaptureIdentity as JourneyCaptureIdentity_alias_1 }
1299
+
1270
1300
  declare type JourneyCaptureOption = false | JourneyCaptureConfig;
1271
1301
  export { JourneyCaptureOption }
1272
1302
  export { JourneyCaptureOption as JourneyCaptureOption_alias_1 }
@@ -1287,6 +1317,21 @@ declare type JourneyCaptureOptions = {
1287
1317
  * bearer credentials and network policy outside the hosted renderer.
1288
1318
  */
1289
1319
  transport?: JourneyCaptureTransport;
1320
+ /**
1321
+ * The `@founderhq/events` client whose visitor identity this journey
1322
+ * shares. Left out, the hosted snippet's `globalThis.founderhq` is used
1323
+ * when present. `false` never looks at the page global.
1324
+ */
1325
+ eventsClient?: JourneyEventsClient | false;
1326
+ /**
1327
+ * Whether a visitor gets a durable anonymous id when no events client is
1328
+ * on the page and no consent choice has been remembered. Defaults to
1329
+ * "granted": a journey response has no cookieless join, so without an id
1330
+ * it belongs to nobody. Pass "denied" while a consent banner is
1331
+ * unanswered, or run `@founderhq/events`, whose consent state the journey
1332
+ * then follows exactly.
1333
+ */
1334
+ consentDefault?: JourneyEventsConsent;
1290
1335
  };
1291
1336
  export { JourneyCaptureOptions }
1292
1337
  export { JourneyCaptureOptions as JourneyCaptureOptions_alias_1 }
@@ -1408,6 +1453,52 @@ export { JourneyEventComputedVariables }
1408
1453
  export { JourneyEventComputedVariables as JourneyEventComputedVariables_alias_1 }
1409
1454
  export { JourneyEventComputedVariables as JourneyEventComputedVariables_alias_2 }
1410
1455
 
1456
+ /**
1457
+ * How a journey learns who the visitor is.
1458
+ *
1459
+ * Rule: whoever loads first mints the anonymous id; the other adopts it.
1460
+ *
1461
+ * 1. An events client is on the page (`@founderhq/events`, passed in by the
1462
+ * host or found at `globalThis.founderhq` from the hosted snippet) and
1463
+ * hands out ids: its distinct id, anonymous id and session id are read at
1464
+ * every capture, so an `identify()` after the journey opened re-labels the
1465
+ * next event. Nothing is minted beside it.
1466
+ * 2. An events client is on the page and hands out no id. Either it runs
1467
+ * cookieless because consent is pending or denied, or the snippet has not
1468
+ * called `init()` yet. Its silence is the consent signal: the journey
1469
+ * writes nothing, and only adopts the state the events SDK left in storage
1470
+ * on an earlier, consented visit. Once the client starts handing out ids,
1471
+ * the next capture carries them.
1472
+ * 3. No events client (none on the page, or one that throws when asked): the
1473
+ * journey mints the anonymous id in the events SDK's own storage shape and
1474
+ * key, so an events client that initialises later on this site finds the
1475
+ * state and adopts the id, exactly as it adopts its own from a previous
1476
+ * visit. A remembered denial or opt-out, or `consentDefault: "denied"`
1477
+ * from the host, stops the mint: then the session carries only its
1478
+ * per-tab client session id.
1479
+ *
1480
+ * The storage key, state shape, identity cookie, and consent cookie below
1481
+ * mirror `packages/events/src/index.ts` (`PersistedState`, `init()`,
1482
+ * `readIdentityCookie`, and `readConsentPreference`). This package is not
1483
+ * in the pnpm workspace, so it cannot import them; `events-identity.test.ts`
1484
+ * pins every literal.
1485
+ */
1486
+ declare type JourneyEventsClient = {
1487
+ /** The visitor's distinct id, or null while capture is not granted. */
1488
+ getDistinctId(): string | null;
1489
+ /** The anonymous and session ids, or an empty object while not granted. */
1490
+ checkoutMetadata(): {
1491
+ fhq_anonymous_id?: string;
1492
+ fhq_session_id?: string;
1493
+ };
1494
+ };
1495
+ export { JourneyEventsClient }
1496
+ export { JourneyEventsClient as JourneyEventsClient_alias_1 }
1497
+
1498
+ declare type JourneyEventsConsent = "granted" | "denied";
1499
+ export { JourneyEventsConsent }
1500
+ export { JourneyEventsConsent as JourneyEventsConsent_alias_1 }
1501
+
1411
1502
  declare const JourneyHapticContext: Context<JourneyHapticHandler | null>;
1412
1503
  export { JourneyHapticContext }
1413
1504
  export { JourneyHapticContext as JourneyHapticContext_alias_1 }
@@ -1428,6 +1519,20 @@ declare type JourneyIdentity = {
1428
1519
  export { JourneyIdentity }
1429
1520
  export { JourneyIdentity as JourneyIdentity_alias_1 }
1430
1521
 
1522
+ export declare type JourneyIdentityOptions = {
1523
+ apiKey: string;
1524
+ /** `false` never consults `globalThis.founderhq`. */
1525
+ eventsClient?: JourneyEventsClient | false;
1526
+ /**
1527
+ * Applies only with no events client and no remembered consent choice.
1528
+ * Defaults to "granted": a journey response has no cookieless join, so
1529
+ * without an id it belongs to nobody. Pass "denied" while a consent banner
1530
+ * is unanswered, or run `@founderhq/events`, whose consent state the
1531
+ * journey then follows exactly.
1532
+ */
1533
+ consentDefault?: JourneyEventsConsent;
1534
+ };
1535
+
1431
1536
  declare type JourneyOptionOverrides = Record<string, StepOption[]>;
1432
1537
  export { JourneyOptionOverrides }
1433
1538
  export { JourneyOptionOverrides as JourneyOptionOverrides_alias_1 }
@@ -2006,6 +2111,8 @@ export declare function RadioGroup({ className, ...props }: React_2.ComponentPro
2006
2111
 
2007
2112
  export declare function RadioGroupItem({ className, ...props }: React_2.ComponentProps<typeof RadioGroup_2.Item>): React_2.JSX.Element;
2008
2113
 
2114
+ export declare function readEventsConsent(apiKey: string): "granted" | "denied" | "off" | null;
2115
+
2009
2116
  /** Rewrites typed answer-key references without touching ordinary display copy. */
2010
2117
  declare function renameAnswerVariableReferences<T>(value: T, renames: ReadonlyMap<string, string>): T;
2011
2118
  export { renameAnswerVariableReferences }
@@ -2021,6 +2128,9 @@ export declare function renderExpressionTemplate(template: string, scope: Scope)
2021
2128
 
2022
2129
  export declare const renderTemplate: (template: string, variables: Record<string, unknown>, fallback: string) => string;
2023
2130
 
2131
+ /** Test seam: forgets ids minted while storage was unavailable. */
2132
+ export declare function resetJourneyIdentityMemoryForTests(): void;
2133
+
2024
2134
  /**
2025
2135
  * Evaluates all computed variable expressions against the current answers.
2026
2136
  * Returns a new answers object with computed values merged in.
@@ -2060,6 +2170,10 @@ declare function resolveJourneyFontFamily(fontFamily: string | undefined): strin
2060
2170
  export { resolveJourneyFontFamily }
2061
2171
  export { resolveJourneyFontFamily as resolveJourneyFontFamily_alias_1 }
2062
2172
 
2173
+ declare function resolveJourneyIdentity(options: JourneyIdentityOptions, storage: Storage | null, now?: () => number): JourneyCaptureIdentity;
2174
+ export { resolveJourneyIdentity }
2175
+ export { resolveJourneyIdentity as resolveJourneyIdentity_alias_1 }
2176
+
2063
2177
  /** Resolve templated strings anywhere inside a plan with `currentPlan` scoped to that plan. */
2064
2178
  export declare function resolvePricingPlanTemplates(plan: PricingPlan, answers: JourneyAnswers): PricingPlan;
2065
2179
 
@@ -2113,7 +2227,6 @@ export { RoutingRule as RoutingRule_alias_2 }
2113
2227
 
2114
2228
  declare type RuntimeIds = {
2115
2229
  journeyId: string;
2116
- visitorId: string;
2117
2230
  clientSessionId: string;
2118
2231
  queueKey: string;
2119
2232
  presentationKey: string;
@@ -2872,4 +2985,7 @@ export { withDeterministicItemIds }
2872
2985
  export { withDeterministicItemIds as withDeterministicItemIds_alias_1 }
2873
2986
  export { withDeterministicItemIds as withDeterministicItemIds_alias_2 }
2874
2987
 
2988
+ /** FNV-1a over the key, base36, seven characters — as the events SDK computes it. */
2989
+ export declare function writeKeyFingerprint(apiKey: string): string;
2990
+
2875
2991
  export { }
@@ -970,6 +970,22 @@ export { evaluateCondition as evaluateCondition_alias_1 }
970
970
 
971
971
  export declare function evaluateSafeExpression(expression: string, scope: Scope): unknown;
972
972
 
973
+ /** `fhq_consent_<fingerprint>` — the cookie the events SDK remembers consent in. */
974
+ export declare function eventsConsentCookieName(apiKey: string): string;
975
+
976
+ /**
977
+ * `fhq_id_<key without punctuation, first 16 characters>` — the identity
978
+ * cookie the events SDK shares across subdomains. On init the SDK lets it
979
+ * win over this origin's stored copy, so a visitor identified on `www` is
980
+ * the same person on `app`; the journey reads it for the same reason.
981
+ */
982
+ export declare function eventsIdentityCookieName(apiKey: string): string;
983
+
984
+ /** `founderhq:events:v2:<first 16 characters of the key>` — the events SDK's key. */
985
+ declare function eventsStorageKey(apiKey: string): string;
986
+ export { eventsStorageKey }
987
+ export { eventsStorageKey as eventsStorageKey_alias_1 }
988
+
973
989
  declare type ExitAnimationPreset = "fade-out" | "slide-up" | "slide-down" | "slide-left" | "slide-right" | "scale-down" | "blur-out" | "none";
974
990
  export { ExitAnimationPreset }
975
991
  export { ExitAnimationPreset as ExitAnimationPreset_alias_1 }
@@ -1013,6 +1029,9 @@ declare type FetchState = {
1013
1029
  export { FetchState }
1014
1030
  export { FetchState as FetchState_alias_1 }
1015
1031
 
1032
+ /** The hosted events snippet publishes its client as `globalThis.founderhq`. */
1033
+ export declare function findGlobalEventsClient(): JourneyEventsClient | null;
1034
+
1016
1035
  export declare function FloatingLabelBlock({ text, variant, color, gradient, className, }: FloatingLabelBlockProps): JSX.Element;
1017
1036
 
1018
1037
  declare type FloatingLabelBlockProps = {
@@ -1267,6 +1286,17 @@ declare type JourneyCaptureConfig = JourneyCaptureOptions & {
1267
1286
  baseUrl: string;
1268
1287
  };
1269
1288
 
1289
+ declare type JourneyCaptureIdentity = {
1290
+ anonymousId?: string;
1291
+ distinctId?: string;
1292
+ /** The analytics session id, known only when an events client is present. */
1293
+ sessionId?: string;
1294
+ /** Where the ids came from; "none" means the visit is cookieless. */
1295
+ source: "events" | "storage" | "none";
1296
+ };
1297
+ export { JourneyCaptureIdentity }
1298
+ export { JourneyCaptureIdentity as JourneyCaptureIdentity_alias_1 }
1299
+
1270
1300
  declare type JourneyCaptureOption = false | JourneyCaptureConfig;
1271
1301
  export { JourneyCaptureOption }
1272
1302
  export { JourneyCaptureOption as JourneyCaptureOption_alias_1 }
@@ -1287,6 +1317,21 @@ declare type JourneyCaptureOptions = {
1287
1317
  * bearer credentials and network policy outside the hosted renderer.
1288
1318
  */
1289
1319
  transport?: JourneyCaptureTransport;
1320
+ /**
1321
+ * The `@founderhq/events` client whose visitor identity this journey
1322
+ * shares. Left out, the hosted snippet's `globalThis.founderhq` is used
1323
+ * when present. `false` never looks at the page global.
1324
+ */
1325
+ eventsClient?: JourneyEventsClient | false;
1326
+ /**
1327
+ * Whether a visitor gets a durable anonymous id when no events client is
1328
+ * on the page and no consent choice has been remembered. Defaults to
1329
+ * "granted": a journey response has no cookieless join, so without an id
1330
+ * it belongs to nobody. Pass "denied" while a consent banner is
1331
+ * unanswered, or run `@founderhq/events`, whose consent state the journey
1332
+ * then follows exactly.
1333
+ */
1334
+ consentDefault?: JourneyEventsConsent;
1290
1335
  };
1291
1336
  export { JourneyCaptureOptions }
1292
1337
  export { JourneyCaptureOptions as JourneyCaptureOptions_alias_1 }
@@ -1408,6 +1453,52 @@ export { JourneyEventComputedVariables }
1408
1453
  export { JourneyEventComputedVariables as JourneyEventComputedVariables_alias_1 }
1409
1454
  export { JourneyEventComputedVariables as JourneyEventComputedVariables_alias_2 }
1410
1455
 
1456
+ /**
1457
+ * How a journey learns who the visitor is.
1458
+ *
1459
+ * Rule: whoever loads first mints the anonymous id; the other adopts it.
1460
+ *
1461
+ * 1. An events client is on the page (`@founderhq/events`, passed in by the
1462
+ * host or found at `globalThis.founderhq` from the hosted snippet) and
1463
+ * hands out ids: its distinct id, anonymous id and session id are read at
1464
+ * every capture, so an `identify()` after the journey opened re-labels the
1465
+ * next event. Nothing is minted beside it.
1466
+ * 2. An events client is on the page and hands out no id. Either it runs
1467
+ * cookieless because consent is pending or denied, or the snippet has not
1468
+ * called `init()` yet. Its silence is the consent signal: the journey
1469
+ * writes nothing, and only adopts the state the events SDK left in storage
1470
+ * on an earlier, consented visit. Once the client starts handing out ids,
1471
+ * the next capture carries them.
1472
+ * 3. No events client (none on the page, or one that throws when asked): the
1473
+ * journey mints the anonymous id in the events SDK's own storage shape and
1474
+ * key, so an events client that initialises later on this site finds the
1475
+ * state and adopts the id, exactly as it adopts its own from a previous
1476
+ * visit. A remembered denial or opt-out, or `consentDefault: "denied"`
1477
+ * from the host, stops the mint: then the session carries only its
1478
+ * per-tab client session id.
1479
+ *
1480
+ * The storage key, state shape, identity cookie, and consent cookie below
1481
+ * mirror `packages/events/src/index.ts` (`PersistedState`, `init()`,
1482
+ * `readIdentityCookie`, and `readConsentPreference`). This package is not
1483
+ * in the pnpm workspace, so it cannot import them; `events-identity.test.ts`
1484
+ * pins every literal.
1485
+ */
1486
+ declare type JourneyEventsClient = {
1487
+ /** The visitor's distinct id, or null while capture is not granted. */
1488
+ getDistinctId(): string | null;
1489
+ /** The anonymous and session ids, or an empty object while not granted. */
1490
+ checkoutMetadata(): {
1491
+ fhq_anonymous_id?: string;
1492
+ fhq_session_id?: string;
1493
+ };
1494
+ };
1495
+ export { JourneyEventsClient }
1496
+ export { JourneyEventsClient as JourneyEventsClient_alias_1 }
1497
+
1498
+ declare type JourneyEventsConsent = "granted" | "denied";
1499
+ export { JourneyEventsConsent }
1500
+ export { JourneyEventsConsent as JourneyEventsConsent_alias_1 }
1501
+
1411
1502
  declare const JourneyHapticContext: Context<JourneyHapticHandler | null>;
1412
1503
  export { JourneyHapticContext }
1413
1504
  export { JourneyHapticContext as JourneyHapticContext_alias_1 }
@@ -1428,6 +1519,20 @@ declare type JourneyIdentity = {
1428
1519
  export { JourneyIdentity }
1429
1520
  export { JourneyIdentity as JourneyIdentity_alias_1 }
1430
1521
 
1522
+ export declare type JourneyIdentityOptions = {
1523
+ apiKey: string;
1524
+ /** `false` never consults `globalThis.founderhq`. */
1525
+ eventsClient?: JourneyEventsClient | false;
1526
+ /**
1527
+ * Applies only with no events client and no remembered consent choice.
1528
+ * Defaults to "granted": a journey response has no cookieless join, so
1529
+ * without an id it belongs to nobody. Pass "denied" while a consent banner
1530
+ * is unanswered, or run `@founderhq/events`, whose consent state the
1531
+ * journey then follows exactly.
1532
+ */
1533
+ consentDefault?: JourneyEventsConsent;
1534
+ };
1535
+
1431
1536
  declare type JourneyOptionOverrides = Record<string, StepOption[]>;
1432
1537
  export { JourneyOptionOverrides }
1433
1538
  export { JourneyOptionOverrides as JourneyOptionOverrides_alias_1 }
@@ -2006,6 +2111,8 @@ export declare function RadioGroup({ className, ...props }: React_2.ComponentPro
2006
2111
 
2007
2112
  export declare function RadioGroupItem({ className, ...props }: React_2.ComponentProps<typeof RadioGroup_2.Item>): React_2.JSX.Element;
2008
2113
 
2114
+ export declare function readEventsConsent(apiKey: string): "granted" | "denied" | "off" | null;
2115
+
2009
2116
  /** Rewrites typed answer-key references without touching ordinary display copy. */
2010
2117
  declare function renameAnswerVariableReferences<T>(value: T, renames: ReadonlyMap<string, string>): T;
2011
2118
  export { renameAnswerVariableReferences }
@@ -2021,6 +2128,9 @@ export declare function renderExpressionTemplate(template: string, scope: Scope)
2021
2128
 
2022
2129
  export declare const renderTemplate: (template: string, variables: Record<string, unknown>, fallback: string) => string;
2023
2130
 
2131
+ /** Test seam: forgets ids minted while storage was unavailable. */
2132
+ export declare function resetJourneyIdentityMemoryForTests(): void;
2133
+
2024
2134
  /**
2025
2135
  * Evaluates all computed variable expressions against the current answers.
2026
2136
  * Returns a new answers object with computed values merged in.
@@ -2060,6 +2170,10 @@ declare function resolveJourneyFontFamily(fontFamily: string | undefined): strin
2060
2170
  export { resolveJourneyFontFamily }
2061
2171
  export { resolveJourneyFontFamily as resolveJourneyFontFamily_alias_1 }
2062
2172
 
2173
+ declare function resolveJourneyIdentity(options: JourneyIdentityOptions, storage: Storage | null, now?: () => number): JourneyCaptureIdentity;
2174
+ export { resolveJourneyIdentity }
2175
+ export { resolveJourneyIdentity as resolveJourneyIdentity_alias_1 }
2176
+
2063
2177
  /** Resolve templated strings anywhere inside a plan with `currentPlan` scoped to that plan. */
2064
2178
  export declare function resolvePricingPlanTemplates(plan: PricingPlan, answers: JourneyAnswers): PricingPlan;
2065
2179
 
@@ -2113,7 +2227,6 @@ export { RoutingRule as RoutingRule_alias_2 }
2113
2227
 
2114
2228
  declare type RuntimeIds = {
2115
2229
  journeyId: string;
2116
- visitorId: string;
2117
2230
  clientSessionId: string;
2118
2231
  queueKey: string;
2119
2232
  presentationKey: string;
@@ -2872,4 +2985,7 @@ export { withDeterministicItemIds }
2872
2985
  export { withDeterministicItemIds as withDeterministicItemIds_alias_1 }
2873
2986
  export { withDeterministicItemIds as withDeterministicItemIds_alias_2 }
2874
2987
 
2988
+ /** FNV-1a over the key, base36, seven characters — as the events SDK computes it. */
2989
+ export declare function writeKeyFingerprint(apiKey: string): string;
2990
+
2875
2991
  export { }
package/dist/index.cjs CHANGED
@@ -12442,6 +12442,190 @@ function JourneyShell({
12442
12442
  }
12443
12443
  );
12444
12444
  }
12445
+
12446
+ // src/engine/events-identity.ts
12447
+ var NO_IDENTITY = { source: "none" };
12448
+ function eventsStorageKey(apiKey) {
12449
+ return `founderhq:events:v2:${apiKey.trim().slice(0, 16)}`;
12450
+ }
12451
+ function eventsConsentCookieName(apiKey) {
12452
+ return `fhq_consent_${writeKeyFingerprint(apiKey.trim())}`;
12453
+ }
12454
+ function eventsIdentityCookieName(apiKey) {
12455
+ return `fhq_id_${apiKey.trim().replace(/[^a-zA-Z0-9]/g, "").slice(0, 16)}`;
12456
+ }
12457
+ function writeKeyFingerprint(apiKey) {
12458
+ let hash = 2166136261;
12459
+ for (let index = 0; index < apiKey.length; index++) {
12460
+ hash ^= apiKey.charCodeAt(index);
12461
+ hash = Math.imul(hash, 16777619);
12462
+ }
12463
+ return (hash >>> 0).toString(36).padStart(7, "0");
12464
+ }
12465
+ function readEventsConsent(apiKey) {
12466
+ const value = readCookie(eventsConsentCookieName(apiKey));
12467
+ if (value === "v1.g") return "granted";
12468
+ if (value === "v1.d") return "denied";
12469
+ if (value === "v1.o") return "off";
12470
+ return null;
12471
+ }
12472
+ function findGlobalEventsClient() {
12473
+ const candidate = globalThis.founderhq;
12474
+ return isEventsClient(candidate) ? candidate : null;
12475
+ }
12476
+ function isEventsClient(value) {
12477
+ return Boolean(value) && typeof value === "object" && typeof value.getDistinctId === "function" && typeof value.checkoutMetadata === "function";
12478
+ }
12479
+ function resolveJourneyIdentity(options, storage, now = Date.now) {
12480
+ var _a, _b;
12481
+ const client = options.eventsClient === false ? null : (_a = options.eventsClient) != null ? _a : findGlobalEventsClient();
12482
+ const answer = client ? askEventsClient(client) : "absent";
12483
+ if (typeof answer === "object") return answer;
12484
+ const remembered = readEventsConsent(options.apiKey);
12485
+ if (remembered === "denied" || remembered === "off") return NO_IDENTITY;
12486
+ const key = eventsStorageKey(options.apiKey);
12487
+ if (answer === "silent") {
12488
+ const state2 = readEventsIdentity(options.apiKey, storage, key);
12489
+ return state2 && !state2.opted_out ? identityFromState(state2) : NO_IDENTITY;
12490
+ }
12491
+ const consent = (_b = remembered != null ? remembered : options.consentDefault) != null ? _b : "granted";
12492
+ if (consent !== "granted") return NO_IDENTITY;
12493
+ const state = readOrMintEventsState(options.apiKey, key, storage, now);
12494
+ return state ? identityFromState(state) : NO_IDENTITY;
12495
+ }
12496
+ function askEventsClient(client) {
12497
+ var _a;
12498
+ try {
12499
+ const metadata = client.checkoutMetadata();
12500
+ const anonymousId = cleanId(metadata.fhq_anonymous_id);
12501
+ if (!anonymousId) return "silent";
12502
+ return {
12503
+ anonymousId,
12504
+ distinctId: (_a = cleanId(client.getDistinctId())) != null ? _a : anonymousId,
12505
+ sessionId: cleanId(metadata.fhq_session_id),
12506
+ source: "events"
12507
+ };
12508
+ } catch (e) {
12509
+ return "absent";
12510
+ }
12511
+ }
12512
+ function identityFromState(state) {
12513
+ return {
12514
+ anonymousId: state.anonymous_id,
12515
+ distinctId: state.distinct_id,
12516
+ source: "storage"
12517
+ };
12518
+ }
12519
+ var memoryState = /* @__PURE__ */ new Map();
12520
+ function readOrMintEventsState(apiKey, key, storage, now) {
12521
+ var _a;
12522
+ const existing = (_a = readEventsIdentity(apiKey, storage, key)) != null ? _a : memoryState.get(key);
12523
+ if (existing) return existing.opted_out ? null : existing;
12524
+ const id = createUuid();
12525
+ const state = {
12526
+ anonymous_id: id,
12527
+ anonymous_created_at: now(),
12528
+ distinct_id: id,
12529
+ identified: false,
12530
+ registered: {},
12531
+ pending_set: {},
12532
+ pending_set_once: {},
12533
+ opted_out: false,
12534
+ queue: []
12535
+ };
12536
+ try {
12537
+ storage == null ? void 0 : storage.setItem(key, JSON.stringify(state));
12538
+ } catch (e) {
12539
+ }
12540
+ memoryState.set(key, state);
12541
+ return state;
12542
+ }
12543
+ function readEventsIdentity(apiKey, storage, key) {
12544
+ const stored = readEventsState(storage, key);
12545
+ const cookie = readEventsIdentityCookie(apiKey);
12546
+ if (!cookie) return stored;
12547
+ if (!stored) return cookie;
12548
+ return __spreadProps(__spreadValues({}, stored), {
12549
+ anonymous_id: cookie.anonymous_id,
12550
+ anonymous_created_at: cookie.anonymous_created_at,
12551
+ distinct_id: cookie.distinct_id,
12552
+ identified: cookie.identified,
12553
+ opted_out: stored.opted_out || cookie.opted_out
12554
+ });
12555
+ }
12556
+ function readEventsIdentityCookie(apiKey) {
12557
+ const raw = readCookie(eventsIdentityCookieName(apiKey));
12558
+ if (!raw) return null;
12559
+ try {
12560
+ const value = JSON.parse(raw);
12561
+ if (typeof value.a !== "string" || !value.a) return null;
12562
+ return {
12563
+ anonymous_id: value.a,
12564
+ anonymous_created_at: typeof value.c === "number" ? value.c : 0,
12565
+ distinct_id: typeof value.d === "string" && value.d ? value.d : value.a,
12566
+ identified: value.i === 1,
12567
+ registered: {},
12568
+ pending_set: {},
12569
+ pending_set_once: {},
12570
+ opted_out: value.o === 1,
12571
+ queue: []
12572
+ };
12573
+ } catch (e) {
12574
+ return null;
12575
+ }
12576
+ }
12577
+ function readEventsState(storage, key) {
12578
+ var _a, _b, _c;
12579
+ try {
12580
+ const raw = storage == null ? void 0 : storage.getItem(key);
12581
+ if (!raw) return null;
12582
+ const parsed = JSON.parse(raw);
12583
+ if (typeof parsed.anonymous_id !== "string" || !parsed.anonymous_id) {
12584
+ return null;
12585
+ }
12586
+ return {
12587
+ anonymous_id: parsed.anonymous_id,
12588
+ anonymous_created_at: typeof parsed.anonymous_created_at === "number" ? parsed.anonymous_created_at : 0,
12589
+ distinct_id: typeof parsed.distinct_id === "string" && parsed.distinct_id ? parsed.distinct_id : parsed.anonymous_id,
12590
+ identified: parsed.identified === true,
12591
+ registered: (_a = parsed.registered) != null ? _a : {},
12592
+ pending_set: (_b = parsed.pending_set) != null ? _b : {},
12593
+ pending_set_once: (_c = parsed.pending_set_once) != null ? _c : {},
12594
+ opted_out: parsed.opted_out === true,
12595
+ queue: Array.isArray(parsed.queue) ? parsed.queue : []
12596
+ };
12597
+ } catch (e) {
12598
+ return null;
12599
+ }
12600
+ }
12601
+ function cleanId(value) {
12602
+ const clean = value == null ? void 0 : value.trim();
12603
+ return clean || void 0;
12604
+ }
12605
+ function readCookie(name) {
12606
+ if (typeof document === "undefined") return null;
12607
+ try {
12608
+ const prefix = `${name}=`;
12609
+ for (const part of document.cookie.split(";")) {
12610
+ const trimmed = part.trim();
12611
+ if (trimmed.startsWith(prefix)) {
12612
+ return decodeURIComponent(trimmed.slice(prefix.length));
12613
+ }
12614
+ }
12615
+ } catch (e) {
12616
+ }
12617
+ return null;
12618
+ }
12619
+ function createUuid() {
12620
+ var _a, _b;
12621
+ const cryptoRef = globalThis.crypto;
12622
+ if (cryptoRef == null ? void 0 : cryptoRef.randomUUID) return cryptoRef.randomUUID();
12623
+ const bytes = (_b = (_a = cryptoRef == null ? void 0 : cryptoRef.getRandomValues) == null ? void 0 : _a.call(cryptoRef, new Uint8Array(16))) != null ? _b : Uint8Array.from({ length: 16 }, () => Math.floor(Math.random() * 256));
12624
+ bytes[6] = bytes[6] & 15 | 64;
12625
+ bytes[8] = bytes[8] & 63 | 128;
12626
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
12627
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
12628
+ }
12445
12629
  var FOUNDERHQ_BASE_URL = "https://app.getfounderhq.com";
12446
12630
  function resolveJourneyBaseUrl(baseUrl) {
12447
12631
  if (!baseUrl) return FOUNDERHQ_BASE_URL;
@@ -12534,7 +12718,7 @@ function useJourneyConfig({
12534
12718
 
12535
12719
  // src/engine/journey-capture.ts
12536
12720
  var JOURNEY_LIBRARY_NAME = "@founderhq/journeys";
12537
- var JOURNEY_LIBRARY_VERSION = "0.8.0";
12721
+ var JOURNEY_LIBRARY_VERSION = "0.9.0";
12538
12722
  var DEFAULT_QUEUE_TTL_MS = 24 * 60 * 60 * 1e3;
12539
12723
  var MAX_QUEUED_CAPTURE_EVENTS = 100;
12540
12724
  var MAX_BEACON_BYTES = 60 * 1024;
@@ -12566,7 +12750,8 @@ function safeBrowserStorage(name) {
12566
12750
  function isQueuedCaptureEvent(value) {
12567
12751
  if (!isRecord2(value)) return false;
12568
12752
  const event = value.event;
12569
- return isRecord2(event) && typeof event.id === "string" && typeof event.type === "string" && typeof event.occurredAt === "string" && typeof value.attempts === "number" && typeof value.createdAt === "number";
12753
+ const envelope = value.envelope;
12754
+ return isRecord2(event) && typeof event.id === "string" && typeof event.type === "string" && typeof event.occurredAt === "string" && isRecord2(envelope) && typeof envelope.clientSessionId === "string" && isRecord2(envelope.context) && typeof value.attempts === "number" && typeof value.createdAt === "number";
12570
12755
  }
12571
12756
  function pruneQueuedEvents(queue, now = Date.now(), ttlMs = DEFAULT_QUEUE_TTL_MS) {
12572
12757
  const cutoff = now - ttlMs;
@@ -12578,25 +12763,12 @@ function readPersistedCaptureQueue(storage, key) {
12578
12763
  const raw = storage.getItem(key);
12579
12764
  if (!raw) return null;
12580
12765
  const parsed = JSON.parse(raw);
12581
- if (typeof parsed.visitorId !== "string" || typeof parsed.clientSessionId !== "string") {
12582
- return null;
12583
- }
12766
+ if (typeof parsed.clientSessionId !== "string") return null;
12584
12767
  const queue = Array.isArray(parsed.queue) ? pruneQueuedEvents(parsed.queue.filter(isQueuedCaptureEvent)) : [];
12585
12768
  return {
12586
- visitorId: parsed.visitorId,
12587
12769
  clientSessionId: parsed.clientSessionId,
12588
12770
  updatedAt: typeof parsed.updatedAt === "number" ? parsed.updatedAt : Date.now(),
12589
- queue: queue.map((item) => {
12590
- var _a;
12591
- return __spreadProps(__spreadValues({}, item), {
12592
- // Legacy persisted headers belong to the original batch, never the new presentation.
12593
- envelope: (_a = item.envelope) != null ? _a : {
12594
- visitorId: parsed.visitorId,
12595
- clientSessionId: parsed.clientSessionId,
12596
- context: {}
12597
- }
12598
- });
12599
- })
12771
+ queue
12600
12772
  };
12601
12773
  } catch (e) {
12602
12774
  return null;
@@ -12613,7 +12785,6 @@ function persistCaptureQueue(storage, runtime, queue) {
12613
12785
  storage.setItem(
12614
12786
  runtime.queueKey,
12615
12787
  JSON.stringify({
12616
- visitorId: runtime.visitorId,
12617
12788
  clientSessionId: runtime.clientSessionId,
12618
12789
  updatedAt: Date.now(),
12619
12790
  queue: pruned
@@ -12712,7 +12883,17 @@ function pageContext(redactUrlParams) {
12712
12883
  campaign
12713
12884
  });
12714
12885
  }
12715
- function captureContext(capture, runtime) {
12886
+ function currentIdentity(capture) {
12887
+ return resolveJourneyIdentity(
12888
+ {
12889
+ apiKey: capture.apiKey,
12890
+ eventsClient: capture.eventsClient,
12891
+ consentDefault: capture.consentDefault
12892
+ },
12893
+ safeBrowserStorage("localStorage")
12894
+ );
12895
+ }
12896
+ function captureContext(capture, identity) {
12716
12897
  var _a, _b;
12717
12898
  const customContext = cleanObject(__spreadValues(__spreadValues({}, (_a = capture.context) != null ? _a : {}), (_b = safeContextFactory(capture.contextFactory)) != null ? _b : {}));
12718
12899
  if (capture.captureContext === false) {
@@ -12727,8 +12908,13 @@ function captureContext(capture, runtime) {
12727
12908
  name: JOURNEY_LIBRARY_NAME,
12728
12909
  version: JOURNEY_LIBRARY_VERSION
12729
12910
  },
12730
- anonymousId: runtime.visitorId,
12731
- sessionId: runtime.clientSessionId,
12911
+ // The same ids the events SDK sends, so the server joins this session
12912
+ // to the visitor's contact the way it joins an event. Absent when the
12913
+ // visit is cookieless.
12914
+ anonymousId: identity.anonymousId,
12915
+ distinctId: identity.distinctId,
12916
+ sessionId: identity.sessionId,
12917
+ identitySource: identity.source,
12732
12918
  locale: navigatorRef == null ? void 0 : navigatorRef.language,
12733
12919
  timezone: safeTimezone(),
12734
12920
  userAgent: navigatorRef == null ? void 0 : navigatorRef.userAgent,
@@ -12758,12 +12944,7 @@ function safeSendBeacon() {
12758
12944
  }
12759
12945
  async function sendCaptureBatch(capture, runtime, batch, options = {}) {
12760
12946
  var _a, _b;
12761
- const payload = __spreadProps(__spreadValues(__spreadValues({}, !capture.transport && options.preferBeacon ? { apiKey: capture.apiKey } : {}), (_b = (_a = batch[0]) == null ? void 0 : _a.envelope) != null ? _b : {
12762
- clientSessionId: runtime.clientSessionId,
12763
- visitorId: runtime.visitorId,
12764
- revisionId: capture.revisionId,
12765
- context: captureContext(capture, runtime)
12766
- }), {
12947
+ const payload = __spreadProps(__spreadValues(__spreadValues({}, !capture.transport && options.preferBeacon ? { apiKey: capture.apiKey } : {}), (_b = (_a = batch[0]) == null ? void 0 : _a.envelope) != null ? _b : buildEnvelope(capture, runtime)), {
12767
12948
  events: batch.map((item) => item.event)
12768
12949
  });
12769
12950
  const url = captureUrl(capture);
@@ -12813,6 +12994,15 @@ async function sendCaptureBatch(capture, runtime, batch, options = {}) {
12813
12994
  return "failed";
12814
12995
  }
12815
12996
  }
12997
+ function buildEnvelope(capture, runtime) {
12998
+ const identity = currentIdentity(capture);
12999
+ return {
13000
+ visitorId: identity.anonymousId,
13001
+ clientSessionId: runtime.clientSessionId,
13002
+ revisionId: capture.revisionId,
13003
+ context: captureContext(capture, identity)
13004
+ };
13005
+ }
12816
13006
  function finiteRetryDelay(value) {
12817
13007
  return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
12818
13008
  }
@@ -12975,13 +13165,13 @@ function useJourneyCaptureRuntime(params) {
12975
13165
  );
12976
13166
  }, []);
12977
13167
  const ensureRuntime = React.useCallback((capture) => {
12978
- var _a, _b, _c, _d, _e;
13168
+ var _a, _b, _c, _d;
12979
13169
  if (typeof window === "undefined") return null;
12980
13170
  const queueKey = `fhq_journey_queue:v2:${capture.apiKey.slice(
12981
13171
  0,
12982
13172
  16
12983
13173
  )}:${capture.journeyId}`;
12984
- const presentationKey = `${(_a = capture.clientSessionId) != null ? _a : "legacy"}:${(_b = capture.revisionId) != null ? _b : ""}`;
13174
+ const presentationKey = `${(_a = capture.clientSessionId) != null ? _a : "runtime"}:${(_b = capture.revisionId) != null ? _b : ""}`;
12985
13175
  const existing = runtimeRef.current;
12986
13176
  if ((existing == null ? void 0 : existing.queueKey) === queueKey && existing.presentationKey === presentationKey) {
12987
13177
  return existing;
@@ -12990,22 +13180,20 @@ function useJourneyCaptureRuntime(params) {
12990
13180
  const session = safeBrowserStorage("sessionStorage");
12991
13181
  if (existing) persistCaptureQueue(local, existing, queueRef.current);
12992
13182
  const persisted = readPersistedCaptureQueue(local, queueKey);
12993
- const visitorId = (_c = persisted == null ? void 0 : persisted.visitorId) != null ? _c : local ? getStoredId(local, "fhq_journey_visitor_id", "fhqv") : randomId("fhqv");
12994
13183
  const sessionKey = `fhq_journey_session:${capture.journeyId}`;
12995
- const clientSessionId = (_d = capture.clientSessionId) != null ? _d : session ? getStoredId(session, sessionKey, "fhqs") : randomId("fhqs");
13184
+ const clientSessionId = (_c = capture.clientSessionId) != null ? _c : session ? getStoredId(session, sessionKey, "fhqs") : randomId("fhqs");
12996
13185
  try {
12997
13186
  session == null ? void 0 : session.setItem(sessionKey, clientSessionId);
12998
13187
  } catch (e) {
12999
13188
  }
13000
13189
  const runtime = {
13001
13190
  journeyId: capture.journeyId,
13002
- visitorId,
13003
13191
  clientSessionId,
13004
13192
  queueKey,
13005
13193
  presentationKey
13006
13194
  };
13007
13195
  runtimeRef.current = runtime;
13008
- queueRef.current = (_e = persisted == null ? void 0 : persisted.queue) != null ? _e : [];
13196
+ queueRef.current = (_d = persisted == null ? void 0 : persisted.queue) != null ? _d : [];
13009
13197
  return runtime;
13010
13198
  }, []);
13011
13199
  const flush = React.useCallback(
@@ -13022,10 +13210,7 @@ function useJourneyCaptureRuntime(params) {
13022
13210
  if (first && ((_b = first.retryAt) != null ? _b : 0) > Date.now()) return;
13023
13211
  const envelope = first == null ? void 0 : first.envelope;
13024
13212
  const batch = queueRef.current.filter(
13025
- (item) => {
13026
- var _a2, _b2;
13027
- return ((_a2 = item.envelope) == null ? void 0 : _a2.clientSessionId) === (envelope == null ? void 0 : envelope.clientSessionId) && ((_b2 = item.envelope) == null ? void 0 : _b2.revisionId) === (envelope == null ? void 0 : envelope.revisionId);
13028
- }
13213
+ (item) => item.envelope.clientSessionId === (envelope == null ? void 0 : envelope.clientSessionId) && item.envelope.revisionId === (envelope == null ? void 0 : envelope.revisionId)
13029
13214
  ).slice(0, options.preferBeacon ? Math.min(batchSize, 5) : batchSize);
13030
13215
  if (batch.length === 0) {
13031
13216
  persistQueue();
@@ -13107,12 +13292,7 @@ function useJourneyCaptureRuntime(params) {
13107
13292
  if (!runtime) return;
13108
13293
  sequenceRef.current += 1;
13109
13294
  queueRef.current.push({
13110
- envelope: {
13111
- visitorId: runtime.visitorId,
13112
- clientSessionId: runtime.clientSessionId,
13113
- revisionId: capture.revisionId,
13114
- context: captureContext(capture, runtime)
13115
- },
13295
+ envelope: buildEnvelope(capture, runtime),
13116
13296
  event: toCaptureEvent(
13117
13297
  config,
13118
13298
  event,
@@ -13282,6 +13462,7 @@ exports.createStepTypeChangePatch = createStepTypeChangePatch;
13282
13462
  exports.createStepTypeDefaults = createStepTypeDefaults;
13283
13463
  exports.createVariableName = createVariableName;
13284
13464
  exports.evaluateCondition = evaluateCondition;
13465
+ exports.eventsStorageKey = eventsStorageKey;
13285
13466
  exports.getScreenNameError = getScreenNameError;
13286
13467
  exports.getStableItemEntries = getStableItemEntries;
13287
13468
  exports.getStepVariable = getStepVariable;
@@ -13301,6 +13482,7 @@ exports.resolveComputedVariableValues = resolveComputedVariableValues;
13301
13482
  exports.resolveComputedVariables = resolveComputedVariables;
13302
13483
  exports.resolveJourneyBlobDefaultSize = resolveJourneyBlobDefaultSize;
13303
13484
  exports.resolveJourneyFontFamily = resolveJourneyFontFamily;
13485
+ exports.resolveJourneyIdentity = resolveJourneyIdentity;
13304
13486
  exports.resolveStepBackgroundMode = resolveStepBackgroundMode;
13305
13487
  exports.useJourneyActions = useJourneyActions;
13306
13488
  exports.useJourneyCaptureRuntime = useJourneyCaptureRuntime;
package/dist/index.d.cts CHANGED
@@ -9,6 +9,11 @@ export { JourneyCaptureTransport } from './_tsup-dts-rollup.cjs';
9
9
  export { JourneyCaptureTransportRequest } from './_tsup-dts-rollup.cjs';
10
10
  export { JourneyIdentity } from './_tsup-dts-rollup.cjs';
11
11
  export { useJourneyCaptureRuntime } from './_tsup-dts-rollup.cjs';
12
+ export { JourneyCaptureIdentity } from './_tsup-dts-rollup.cjs';
13
+ export { JourneyEventsClient } from './_tsup-dts-rollup.cjs';
14
+ export { JourneyEventsConsent } from './_tsup-dts-rollup.cjs';
15
+ export { eventsStorageKey } from './_tsup-dts-rollup.cjs';
16
+ export { resolveJourneyIdentity } from './_tsup-dts-rollup.cjs';
12
17
  export { JourneyHapticContext } from './_tsup-dts-rollup.cjs';
13
18
  export { JourneyHapticHandler } from './_tsup-dts-rollup.cjs';
14
19
  export { JourneyHapticType } from './_tsup-dts-rollup.cjs';
package/dist/index.d.ts CHANGED
@@ -9,6 +9,11 @@ export { JourneyCaptureTransport } from './_tsup-dts-rollup.js';
9
9
  export { JourneyCaptureTransportRequest } from './_tsup-dts-rollup.js';
10
10
  export { JourneyIdentity } from './_tsup-dts-rollup.js';
11
11
  export { useJourneyCaptureRuntime } from './_tsup-dts-rollup.js';
12
+ export { JourneyCaptureIdentity } from './_tsup-dts-rollup.js';
13
+ export { JourneyEventsClient } from './_tsup-dts-rollup.js';
14
+ export { JourneyEventsConsent } from './_tsup-dts-rollup.js';
15
+ export { eventsStorageKey } from './_tsup-dts-rollup.js';
16
+ export { resolveJourneyIdentity } from './_tsup-dts-rollup.js';
12
17
  export { JourneyHapticContext } from './_tsup-dts-rollup.js';
13
18
  export { JourneyHapticHandler } from './_tsup-dts-rollup.js';
14
19
  export { JourneyHapticType } from './_tsup-dts-rollup.js';
package/dist/index.js CHANGED
@@ -10336,6 +10336,190 @@ function JourneyShell({
10336
10336
  }
10337
10337
  );
10338
10338
  }
10339
+
10340
+ // src/engine/events-identity.ts
10341
+ var NO_IDENTITY = { source: "none" };
10342
+ function eventsStorageKey(apiKey) {
10343
+ return `founderhq:events:v2:${apiKey.trim().slice(0, 16)}`;
10344
+ }
10345
+ function eventsConsentCookieName(apiKey) {
10346
+ return `fhq_consent_${writeKeyFingerprint(apiKey.trim())}`;
10347
+ }
10348
+ function eventsIdentityCookieName(apiKey) {
10349
+ return `fhq_id_${apiKey.trim().replace(/[^a-zA-Z0-9]/g, "").slice(0, 16)}`;
10350
+ }
10351
+ function writeKeyFingerprint(apiKey) {
10352
+ let hash = 2166136261;
10353
+ for (let index = 0; index < apiKey.length; index++) {
10354
+ hash ^= apiKey.charCodeAt(index);
10355
+ hash = Math.imul(hash, 16777619);
10356
+ }
10357
+ return (hash >>> 0).toString(36).padStart(7, "0");
10358
+ }
10359
+ function readEventsConsent(apiKey) {
10360
+ const value = readCookie(eventsConsentCookieName(apiKey));
10361
+ if (value === "v1.g") return "granted";
10362
+ if (value === "v1.d") return "denied";
10363
+ if (value === "v1.o") return "off";
10364
+ return null;
10365
+ }
10366
+ function findGlobalEventsClient() {
10367
+ const candidate = globalThis.founderhq;
10368
+ return isEventsClient(candidate) ? candidate : null;
10369
+ }
10370
+ function isEventsClient(value) {
10371
+ return Boolean(value) && typeof value === "object" && typeof value.getDistinctId === "function" && typeof value.checkoutMetadata === "function";
10372
+ }
10373
+ function resolveJourneyIdentity(options, storage, now = Date.now) {
10374
+ var _a, _b;
10375
+ const client = options.eventsClient === false ? null : (_a = options.eventsClient) != null ? _a : findGlobalEventsClient();
10376
+ const answer = client ? askEventsClient(client) : "absent";
10377
+ if (typeof answer === "object") return answer;
10378
+ const remembered = readEventsConsent(options.apiKey);
10379
+ if (remembered === "denied" || remembered === "off") return NO_IDENTITY;
10380
+ const key = eventsStorageKey(options.apiKey);
10381
+ if (answer === "silent") {
10382
+ const state2 = readEventsIdentity(options.apiKey, storage, key);
10383
+ return state2 && !state2.opted_out ? identityFromState(state2) : NO_IDENTITY;
10384
+ }
10385
+ const consent = (_b = remembered != null ? remembered : options.consentDefault) != null ? _b : "granted";
10386
+ if (consent !== "granted") return NO_IDENTITY;
10387
+ const state = readOrMintEventsState(options.apiKey, key, storage, now);
10388
+ return state ? identityFromState(state) : NO_IDENTITY;
10389
+ }
10390
+ function askEventsClient(client) {
10391
+ var _a;
10392
+ try {
10393
+ const metadata = client.checkoutMetadata();
10394
+ const anonymousId = cleanId(metadata.fhq_anonymous_id);
10395
+ if (!anonymousId) return "silent";
10396
+ return {
10397
+ anonymousId,
10398
+ distinctId: (_a = cleanId(client.getDistinctId())) != null ? _a : anonymousId,
10399
+ sessionId: cleanId(metadata.fhq_session_id),
10400
+ source: "events"
10401
+ };
10402
+ } catch (e) {
10403
+ return "absent";
10404
+ }
10405
+ }
10406
+ function identityFromState(state) {
10407
+ return {
10408
+ anonymousId: state.anonymous_id,
10409
+ distinctId: state.distinct_id,
10410
+ source: "storage"
10411
+ };
10412
+ }
10413
+ var memoryState = /* @__PURE__ */ new Map();
10414
+ function readOrMintEventsState(apiKey, key, storage, now) {
10415
+ var _a;
10416
+ const existing = (_a = readEventsIdentity(apiKey, storage, key)) != null ? _a : memoryState.get(key);
10417
+ if (existing) return existing.opted_out ? null : existing;
10418
+ const id = createUuid();
10419
+ const state = {
10420
+ anonymous_id: id,
10421
+ anonymous_created_at: now(),
10422
+ distinct_id: id,
10423
+ identified: false,
10424
+ registered: {},
10425
+ pending_set: {},
10426
+ pending_set_once: {},
10427
+ opted_out: false,
10428
+ queue: []
10429
+ };
10430
+ try {
10431
+ storage == null ? void 0 : storage.setItem(key, JSON.stringify(state));
10432
+ } catch (e) {
10433
+ }
10434
+ memoryState.set(key, state);
10435
+ return state;
10436
+ }
10437
+ function readEventsIdentity(apiKey, storage, key) {
10438
+ const stored = readEventsState(storage, key);
10439
+ const cookie = readEventsIdentityCookie(apiKey);
10440
+ if (!cookie) return stored;
10441
+ if (!stored) return cookie;
10442
+ return __spreadProps(__spreadValues({}, stored), {
10443
+ anonymous_id: cookie.anonymous_id,
10444
+ anonymous_created_at: cookie.anonymous_created_at,
10445
+ distinct_id: cookie.distinct_id,
10446
+ identified: cookie.identified,
10447
+ opted_out: stored.opted_out || cookie.opted_out
10448
+ });
10449
+ }
10450
+ function readEventsIdentityCookie(apiKey) {
10451
+ const raw = readCookie(eventsIdentityCookieName(apiKey));
10452
+ if (!raw) return null;
10453
+ try {
10454
+ const value = JSON.parse(raw);
10455
+ if (typeof value.a !== "string" || !value.a) return null;
10456
+ return {
10457
+ anonymous_id: value.a,
10458
+ anonymous_created_at: typeof value.c === "number" ? value.c : 0,
10459
+ distinct_id: typeof value.d === "string" && value.d ? value.d : value.a,
10460
+ identified: value.i === 1,
10461
+ registered: {},
10462
+ pending_set: {},
10463
+ pending_set_once: {},
10464
+ opted_out: value.o === 1,
10465
+ queue: []
10466
+ };
10467
+ } catch (e) {
10468
+ return null;
10469
+ }
10470
+ }
10471
+ function readEventsState(storage, key) {
10472
+ var _a, _b, _c;
10473
+ try {
10474
+ const raw = storage == null ? void 0 : storage.getItem(key);
10475
+ if (!raw) return null;
10476
+ const parsed = JSON.parse(raw);
10477
+ if (typeof parsed.anonymous_id !== "string" || !parsed.anonymous_id) {
10478
+ return null;
10479
+ }
10480
+ return {
10481
+ anonymous_id: parsed.anonymous_id,
10482
+ anonymous_created_at: typeof parsed.anonymous_created_at === "number" ? parsed.anonymous_created_at : 0,
10483
+ distinct_id: typeof parsed.distinct_id === "string" && parsed.distinct_id ? parsed.distinct_id : parsed.anonymous_id,
10484
+ identified: parsed.identified === true,
10485
+ registered: (_a = parsed.registered) != null ? _a : {},
10486
+ pending_set: (_b = parsed.pending_set) != null ? _b : {},
10487
+ pending_set_once: (_c = parsed.pending_set_once) != null ? _c : {},
10488
+ opted_out: parsed.opted_out === true,
10489
+ queue: Array.isArray(parsed.queue) ? parsed.queue : []
10490
+ };
10491
+ } catch (e) {
10492
+ return null;
10493
+ }
10494
+ }
10495
+ function cleanId(value) {
10496
+ const clean = value == null ? void 0 : value.trim();
10497
+ return clean || void 0;
10498
+ }
10499
+ function readCookie(name) {
10500
+ if (typeof document === "undefined") return null;
10501
+ try {
10502
+ const prefix = `${name}=`;
10503
+ for (const part of document.cookie.split(";")) {
10504
+ const trimmed = part.trim();
10505
+ if (trimmed.startsWith(prefix)) {
10506
+ return decodeURIComponent(trimmed.slice(prefix.length));
10507
+ }
10508
+ }
10509
+ } catch (e) {
10510
+ }
10511
+ return null;
10512
+ }
10513
+ function createUuid() {
10514
+ var _a, _b;
10515
+ const cryptoRef = globalThis.crypto;
10516
+ if (cryptoRef == null ? void 0 : cryptoRef.randomUUID) return cryptoRef.randomUUID();
10517
+ const bytes = (_b = (_a = cryptoRef == null ? void 0 : cryptoRef.getRandomValues) == null ? void 0 : _a.call(cryptoRef, new Uint8Array(16))) != null ? _b : Uint8Array.from({ length: 16 }, () => Math.floor(Math.random() * 256));
10518
+ bytes[6] = bytes[6] & 15 | 64;
10519
+ bytes[8] = bytes[8] & 63 | 128;
10520
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
10521
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
10522
+ }
10339
10523
  var FOUNDERHQ_BASE_URL = "https://app.getfounderhq.com";
10340
10524
  function resolveJourneyBaseUrl(baseUrl) {
10341
10525
  if (!baseUrl) return FOUNDERHQ_BASE_URL;
@@ -10428,7 +10612,7 @@ function useJourneyConfig({
10428
10612
 
10429
10613
  // src/engine/journey-capture.ts
10430
10614
  var JOURNEY_LIBRARY_NAME = "@founderhq/journeys";
10431
- var JOURNEY_LIBRARY_VERSION = "0.8.0";
10615
+ var JOURNEY_LIBRARY_VERSION = "0.9.0";
10432
10616
  var DEFAULT_QUEUE_TTL_MS = 24 * 60 * 60 * 1e3;
10433
10617
  var MAX_QUEUED_CAPTURE_EVENTS = 100;
10434
10618
  var MAX_BEACON_BYTES = 60 * 1024;
@@ -10460,7 +10644,8 @@ function safeBrowserStorage(name) {
10460
10644
  function isQueuedCaptureEvent(value) {
10461
10645
  if (!isRecord(value)) return false;
10462
10646
  const event = value.event;
10463
- return isRecord(event) && typeof event.id === "string" && typeof event.type === "string" && typeof event.occurredAt === "string" && typeof value.attempts === "number" && typeof value.createdAt === "number";
10647
+ const envelope = value.envelope;
10648
+ return isRecord(event) && typeof event.id === "string" && typeof event.type === "string" && typeof event.occurredAt === "string" && isRecord(envelope) && typeof envelope.clientSessionId === "string" && isRecord(envelope.context) && typeof value.attempts === "number" && typeof value.createdAt === "number";
10464
10649
  }
10465
10650
  function pruneQueuedEvents(queue, now = Date.now(), ttlMs = DEFAULT_QUEUE_TTL_MS) {
10466
10651
  const cutoff = now - ttlMs;
@@ -10472,25 +10657,12 @@ function readPersistedCaptureQueue(storage, key) {
10472
10657
  const raw = storage.getItem(key);
10473
10658
  if (!raw) return null;
10474
10659
  const parsed = JSON.parse(raw);
10475
- if (typeof parsed.visitorId !== "string" || typeof parsed.clientSessionId !== "string") {
10476
- return null;
10477
- }
10660
+ if (typeof parsed.clientSessionId !== "string") return null;
10478
10661
  const queue = Array.isArray(parsed.queue) ? pruneQueuedEvents(parsed.queue.filter(isQueuedCaptureEvent)) : [];
10479
10662
  return {
10480
- visitorId: parsed.visitorId,
10481
10663
  clientSessionId: parsed.clientSessionId,
10482
10664
  updatedAt: typeof parsed.updatedAt === "number" ? parsed.updatedAt : Date.now(),
10483
- queue: queue.map((item) => {
10484
- var _a;
10485
- return __spreadProps(__spreadValues({}, item), {
10486
- // Legacy persisted headers belong to the original batch, never the new presentation.
10487
- envelope: (_a = item.envelope) != null ? _a : {
10488
- visitorId: parsed.visitorId,
10489
- clientSessionId: parsed.clientSessionId,
10490
- context: {}
10491
- }
10492
- });
10493
- })
10665
+ queue
10494
10666
  };
10495
10667
  } catch (e) {
10496
10668
  return null;
@@ -10507,7 +10679,6 @@ function persistCaptureQueue(storage, runtime, queue) {
10507
10679
  storage.setItem(
10508
10680
  runtime.queueKey,
10509
10681
  JSON.stringify({
10510
- visitorId: runtime.visitorId,
10511
10682
  clientSessionId: runtime.clientSessionId,
10512
10683
  updatedAt: Date.now(),
10513
10684
  queue: pruned
@@ -10606,7 +10777,17 @@ function pageContext(redactUrlParams) {
10606
10777
  campaign
10607
10778
  });
10608
10779
  }
10609
- function captureContext(capture, runtime) {
10780
+ function currentIdentity(capture) {
10781
+ return resolveJourneyIdentity(
10782
+ {
10783
+ apiKey: capture.apiKey,
10784
+ eventsClient: capture.eventsClient,
10785
+ consentDefault: capture.consentDefault
10786
+ },
10787
+ safeBrowserStorage("localStorage")
10788
+ );
10789
+ }
10790
+ function captureContext(capture, identity) {
10610
10791
  var _a, _b;
10611
10792
  const customContext = cleanObject(__spreadValues(__spreadValues({}, (_a = capture.context) != null ? _a : {}), (_b = safeContextFactory(capture.contextFactory)) != null ? _b : {}));
10612
10793
  if (capture.captureContext === false) {
@@ -10621,8 +10802,13 @@ function captureContext(capture, runtime) {
10621
10802
  name: JOURNEY_LIBRARY_NAME,
10622
10803
  version: JOURNEY_LIBRARY_VERSION
10623
10804
  },
10624
- anonymousId: runtime.visitorId,
10625
- sessionId: runtime.clientSessionId,
10805
+ // The same ids the events SDK sends, so the server joins this session
10806
+ // to the visitor's contact the way it joins an event. Absent when the
10807
+ // visit is cookieless.
10808
+ anonymousId: identity.anonymousId,
10809
+ distinctId: identity.distinctId,
10810
+ sessionId: identity.sessionId,
10811
+ identitySource: identity.source,
10626
10812
  locale: navigatorRef == null ? void 0 : navigatorRef.language,
10627
10813
  timezone: safeTimezone(),
10628
10814
  userAgent: navigatorRef == null ? void 0 : navigatorRef.userAgent,
@@ -10652,12 +10838,7 @@ function safeSendBeacon() {
10652
10838
  }
10653
10839
  async function sendCaptureBatch(capture, runtime, batch, options = {}) {
10654
10840
  var _a, _b;
10655
- const payload = __spreadProps(__spreadValues(__spreadValues({}, !capture.transport && options.preferBeacon ? { apiKey: capture.apiKey } : {}), (_b = (_a = batch[0]) == null ? void 0 : _a.envelope) != null ? _b : {
10656
- clientSessionId: runtime.clientSessionId,
10657
- visitorId: runtime.visitorId,
10658
- revisionId: capture.revisionId,
10659
- context: captureContext(capture, runtime)
10660
- }), {
10841
+ const payload = __spreadProps(__spreadValues(__spreadValues({}, !capture.transport && options.preferBeacon ? { apiKey: capture.apiKey } : {}), (_b = (_a = batch[0]) == null ? void 0 : _a.envelope) != null ? _b : buildEnvelope(capture, runtime)), {
10661
10842
  events: batch.map((item) => item.event)
10662
10843
  });
10663
10844
  const url = captureUrl(capture);
@@ -10707,6 +10888,15 @@ async function sendCaptureBatch(capture, runtime, batch, options = {}) {
10707
10888
  return "failed";
10708
10889
  }
10709
10890
  }
10891
+ function buildEnvelope(capture, runtime) {
10892
+ const identity = currentIdentity(capture);
10893
+ return {
10894
+ visitorId: identity.anonymousId,
10895
+ clientSessionId: runtime.clientSessionId,
10896
+ revisionId: capture.revisionId,
10897
+ context: captureContext(capture, identity)
10898
+ };
10899
+ }
10710
10900
  function finiteRetryDelay(value) {
10711
10901
  return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
10712
10902
  }
@@ -10869,13 +11059,13 @@ function useJourneyCaptureRuntime(params) {
10869
11059
  );
10870
11060
  }, []);
10871
11061
  const ensureRuntime = useCallback((capture) => {
10872
- var _a, _b, _c, _d, _e;
11062
+ var _a, _b, _c, _d;
10873
11063
  if (typeof window === "undefined") return null;
10874
11064
  const queueKey = `fhq_journey_queue:v2:${capture.apiKey.slice(
10875
11065
  0,
10876
11066
  16
10877
11067
  )}:${capture.journeyId}`;
10878
- const presentationKey = `${(_a = capture.clientSessionId) != null ? _a : "legacy"}:${(_b = capture.revisionId) != null ? _b : ""}`;
11068
+ const presentationKey = `${(_a = capture.clientSessionId) != null ? _a : "runtime"}:${(_b = capture.revisionId) != null ? _b : ""}`;
10879
11069
  const existing = runtimeRef.current;
10880
11070
  if ((existing == null ? void 0 : existing.queueKey) === queueKey && existing.presentationKey === presentationKey) {
10881
11071
  return existing;
@@ -10884,22 +11074,20 @@ function useJourneyCaptureRuntime(params) {
10884
11074
  const session = safeBrowserStorage("sessionStorage");
10885
11075
  if (existing) persistCaptureQueue(local, existing, queueRef.current);
10886
11076
  const persisted = readPersistedCaptureQueue(local, queueKey);
10887
- const visitorId = (_c = persisted == null ? void 0 : persisted.visitorId) != null ? _c : local ? getStoredId(local, "fhq_journey_visitor_id", "fhqv") : randomId("fhqv");
10888
11077
  const sessionKey = `fhq_journey_session:${capture.journeyId}`;
10889
- const clientSessionId = (_d = capture.clientSessionId) != null ? _d : session ? getStoredId(session, sessionKey, "fhqs") : randomId("fhqs");
11078
+ const clientSessionId = (_c = capture.clientSessionId) != null ? _c : session ? getStoredId(session, sessionKey, "fhqs") : randomId("fhqs");
10890
11079
  try {
10891
11080
  session == null ? void 0 : session.setItem(sessionKey, clientSessionId);
10892
11081
  } catch (e) {
10893
11082
  }
10894
11083
  const runtime = {
10895
11084
  journeyId: capture.journeyId,
10896
- visitorId,
10897
11085
  clientSessionId,
10898
11086
  queueKey,
10899
11087
  presentationKey
10900
11088
  };
10901
11089
  runtimeRef.current = runtime;
10902
- queueRef.current = (_e = persisted == null ? void 0 : persisted.queue) != null ? _e : [];
11090
+ queueRef.current = (_d = persisted == null ? void 0 : persisted.queue) != null ? _d : [];
10903
11091
  return runtime;
10904
11092
  }, []);
10905
11093
  const flush = useCallback(
@@ -10916,10 +11104,7 @@ function useJourneyCaptureRuntime(params) {
10916
11104
  if (first && ((_b = first.retryAt) != null ? _b : 0) > Date.now()) return;
10917
11105
  const envelope = first == null ? void 0 : first.envelope;
10918
11106
  const batch = queueRef.current.filter(
10919
- (item) => {
10920
- var _a2, _b2;
10921
- return ((_a2 = item.envelope) == null ? void 0 : _a2.clientSessionId) === (envelope == null ? void 0 : envelope.clientSessionId) && ((_b2 = item.envelope) == null ? void 0 : _b2.revisionId) === (envelope == null ? void 0 : envelope.revisionId);
10922
- }
11107
+ (item) => item.envelope.clientSessionId === (envelope == null ? void 0 : envelope.clientSessionId) && item.envelope.revisionId === (envelope == null ? void 0 : envelope.revisionId)
10923
11108
  ).slice(0, options.preferBeacon ? Math.min(batchSize, 5) : batchSize);
10924
11109
  if (batch.length === 0) {
10925
11110
  persistQueue();
@@ -11001,12 +11186,7 @@ function useJourneyCaptureRuntime(params) {
11001
11186
  if (!runtime) return;
11002
11187
  sequenceRef.current += 1;
11003
11188
  queueRef.current.push({
11004
- envelope: {
11005
- visitorId: runtime.visitorId,
11006
- clientSessionId: runtime.clientSessionId,
11007
- revisionId: capture.revisionId,
11008
- context: captureContext(capture, runtime)
11009
- },
11189
+ envelope: buildEnvelope(capture, runtime),
11010
11190
  event: toCaptureEvent(
11011
11191
  config,
11012
11192
  event,
@@ -11152,4 +11332,4 @@ function Journey({
11152
11332
  );
11153
11333
  }
11154
11334
 
11155
- export { BLOCK_META, DiscountCodeDialog, GravityBin, Journey, JourneyBlobLayer, JourneyContext, JourneyHapticContext, JourneyProvider, JourneyShell, SegmentedProgress, StepRenderer, TimelineBlock, arePageInputsValid, evaluateCondition, hasVisibleProgress, resolveJourneyBlobDefaultSize, resolveJourneyFontFamily, resolveStepBackgroundMode, useJourneyActions, useJourneyCaptureRuntime, useJourneyConfig, useJourneyState };
11335
+ export { BLOCK_META, DiscountCodeDialog, GravityBin, Journey, JourneyBlobLayer, JourneyContext, JourneyHapticContext, JourneyProvider, JourneyShell, SegmentedProgress, StepRenderer, TimelineBlock, arePageInputsValid, evaluateCondition, eventsStorageKey, hasVisibleProgress, resolveJourneyBlobDefaultSize, resolveJourneyFontFamily, resolveJourneyIdentity, resolveStepBackgroundMode, useJourneyActions, useJourneyCaptureRuntime, useJourneyConfig, useJourneyState };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@founderhq/journeys",
3
- "version": "0.8.1",
3
+ "version": "0.9.0",
4
4
  "description": "Config-driven interactive journey/questionnaire engine for React",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",