@wildo-ai/saas-frontend-lib 1.1.14 → 1.1.15

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.
Files changed (50) hide show
  1. package/dist/esm/components/ai-elements/meta/agent-wrappers.d.ts +1 -0
  2. package/dist/esm/components/ai-elements/meta/agent-wrappers.d.ts.map +1 -1
  3. package/dist/esm/components/ai-elements/meta/agent-wrappers.js.map +1 -1
  4. package/dist/esm/components/compliance/EmbeddedSigningFrame.d.ts +38 -0
  5. package/dist/esm/components/compliance/EmbeddedSigningFrame.d.ts.map +1 -0
  6. package/dist/esm/components/compliance/EmbeddedSigningFrame.js +106 -0
  7. package/dist/esm/components/compliance/EmbeddedSigningFrame.js.map +1 -0
  8. package/dist/esm/components/data-display/ResourceAutomaticDisplayer.d.ts.map +1 -1
  9. package/dist/esm/components/data-display/ResourceAutomaticDisplayer.js +22 -0
  10. package/dist/esm/components/data-display/ResourceAutomaticDisplayer.js.map +1 -1
  11. package/dist/esm/components/flows-actors/agent-config.labels.d.ts.map +1 -1
  12. package/dist/esm/components/flows-actors/agent-config.labels.js +2 -0
  13. package/dist/esm/components/flows-actors/agent-config.labels.js.map +1 -1
  14. package/dist/esm/components/flows-actors/approval.d.ts +7 -1
  15. package/dist/esm/components/flows-actors/approval.d.ts.map +1 -1
  16. package/dist/esm/components/flows-actors/approval.js +22 -5
  17. package/dist/esm/components/flows-actors/approval.js.map +1 -1
  18. package/dist/esm/core/events/events.frontend.schemas.d.ts +40 -0
  19. package/dist/esm/core/events/events.frontend.schemas.d.ts.map +1 -1
  20. package/dist/esm/core/events/events.frontend.schemas.js +24 -1
  21. package/dist/esm/core/events/events.frontend.schemas.js.map +1 -1
  22. package/dist/esm/core/monitoring/analytics/AnalyticsContext.d.ts.map +1 -1
  23. package/dist/esm/core/monitoring/analytics/AnalyticsContext.js +50 -18
  24. package/dist/esm/core/monitoring/analytics/AnalyticsContext.js.map +1 -1
  25. package/dist/esm/core/resources/resource-read-cache.frontend.service.d.ts +6 -1
  26. package/dist/esm/core/resources/resource-read-cache.frontend.service.d.ts.map +1 -1
  27. package/dist/esm/core/resources/resource-read-cache.frontend.service.js +11 -1
  28. package/dist/esm/core/resources/resource-read-cache.frontend.service.js.map +1 -1
  29. package/dist/esm/core/runtime/ApplicationMainContext.d.ts +1 -1
  30. package/dist/esm/core/runtime/ApplicationMainContext.d.ts.map +1 -1
  31. package/dist/esm/core/runtime/ApplicationMainContext.js +12 -3
  32. package/dist/esm/core/runtime/ApplicationMainContext.js.map +1 -1
  33. package/dist/esm/core/security/UserOrgsContext.d.ts +6 -1
  34. package/dist/esm/core/security/UserOrgsContext.d.ts.map +1 -1
  35. package/dist/esm/core/security/UserOrgsContext.js +35 -11
  36. package/dist/esm/core/security/UserOrgsContext.js.map +1 -1
  37. package/dist/esm/core/security/consent-gate.frontend.utils.d.ts +17 -5
  38. package/dist/esm/core/security/consent-gate.frontend.utils.d.ts.map +1 -1
  39. package/dist/esm/core/security/consent-gate.frontend.utils.js +16 -7
  40. package/dist/esm/core/security/consent-gate.frontend.utils.js.map +1 -1
  41. package/dist/esm/core/security/useConsentGateBehavior.js +1 -1
  42. package/dist/esm/core/security/useConsentGateBehavior.js.map +1 -1
  43. package/dist/esm/core/security/useGrantedConsentPurposes.js +1 -1
  44. package/dist/esm/core/security/useGrantedConsentPurposes.js.map +1 -1
  45. package/dist/esm/index.d.ts +1 -0
  46. package/dist/esm/index.d.ts.map +1 -1
  47. package/dist/esm/index.js +1 -0
  48. package/dist/esm/index.js.map +1 -1
  49. package/dist/tsconfig.build.tsbuildinfo +1 -1
  50. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"AnalyticsContext.js","sourceRoot":"","sources":["../../../../../src/core/monitoring/analytics/AnalyticsContext.tsx"],"names":[],"mappings":";AAAA;;;;;GAKG;AAEH,OAAc,EAAE,aAAa,EAAE,UAAU,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,E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AAI,aAAa,CAAC,OAAO;YAAE,aAAa,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;;YACjE,SAAS,EAAE,CAAC;IACnB,CAAC,EAAE,CAAC,QAAQ,EAAE,aAAa,EAAE,WAAW,CAAC,CAAC,CAAC;IAE3C,iEAAiE;IAEjE,MAAM,YAAY,GAAG,OAAO,CAAwB,GAAG,EAAE,CAAC,CAAC;QACzD,KAAK;QACL,IAAI;QACJ,QAAQ,EAAE,aAAa;QACvB,qBAAqB;QACrB,eAAe;QACf,kBAAkB;QAClB,WAAW,EAAE,UAAU;KACxB,CAAC,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,qBAAqB,EAAE,eAAe,EAAE,kBAAkB,CAAC,CAAC,CAAC;IAE9F,OAAO,CACL,KAAC,iCAAiC,CAAC,QAAQ,IAAC,KAAK,EAAE,eAAe,YAClE,MAAC,gBAAgB,CAAC,QAAQ,IAAC,KAAK,EAAE,YAAY,aAC3C,aAAa,IAAI,QAAQ,IAAI,eAAe,IAAI,CAC/C,KAAC,oBAAoB,IAEnB,QAAQ,EAAE,QAAQ,EAClB,QAAQ,EAAE,cAAc,CAAC,OAAO,EAChC,MAAM,EAAE,eAAe,CAAC,mBAAmB,EAC3C,YAAY,EAAE,eAAe,CAAC,YAAY,IAJrC,GAAG,WAAW,IAAI,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,YAAY,CAAC,EAAE,CAKrE,CACH,EACA,QAAQ,IACiB,GACiB,CAC9C,CAAC;AACJ,CAAC,CAAC","sourcesContent":["/**\n * Analytics Context Provider\n * \n * Provides analytics tracking, value moment achievement persistence,\n * consent gating, and provider lifecycle management.\n */\n\nimport React, { createContext, useContext, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { AnalyticsEventName, BUILTIN_PROVIDER_CAPABILITY, ConsentPurpose, CoreResourceType, hasGrantedConsentPurposes, isReadShapedOperation, normalizeConsentPurposes, ValueMomentRole, ValueMomentScope, AnalyticsTriggerSource, type AnalyticsConfig, ANALYTICS_ACHIEVED_STORAGE_KEY_PREFIX } from '@wildo-ai/saas-models';\nimport type { IAnalyticsProvider, AnalyticsEvent } from './analytics-provider.frontend.interface';\nimport { AnalyticsProviderRegistry } from './analytics-provider-registry.frontend.service';\nimport { ApplicationContext } from '~wildo-frontend-lib/core/runtime/ApplicationContext.shared';\nimport { useEventBus } from '~wildo-frontend-lib/core/events/useEventBus';\nimport { FrontendEvents, SessionEndReason, SessionEstablishment } from '~wildo-frontend-lib/core/events/events.frontend.schemas';\nimport { getManualCallsHttpClient } from '~wildo-frontend-lib/core/requests/wildo-http-client-manual-calls.frontend.service';\nimport { useResourceReachability } from '~wildo-frontend-lib/core/resources/useResourceRegistry';\nimport { AnalyticsEventBridge, type AnalyticsMomentProgress } from './AnalyticsEventBridge';\nimport { isFrontendProductAnalyticsSink, type FrontendProductAnalyticsSink } from '@wildo-ai/saas-models/public-runtime';\nimport { useConsentBasedProviderActivations } from '~wildo-frontend-lib/core/external-providers/ConsentBasedProviderSdks';\n\n// ─── Context Value Interface ────────────────────────────────────\n\nexport interface AnalyticsContextValue {\n /** Track a custom event (app-custom usage) */\n track: (name: string, properties?: Record<string, unknown>) => void;\n /** Track a page view */\n page: (path: string, properties?: Record<string, unknown>) => void;\n /** Whether analytics is active (enabled + consent granted) */\n isActive: boolean;\n /** Session start timestamp (for TTFV computation) */\n sessionStartTimestamp: number;\n /** Set of achieved value moment identifiers (scope-aware, persisted) */\n achievedMoments: Set<string>;\n /** Mark a value moment as achieved (persists to localStorage + backend sync) */\n markMomentAchieved: (identifier: string) => boolean | Promise<boolean>;\n /**\n * Internal: ref for track() call interception (used by AnalyticsEventBridge).\n * The bridge registers a callback on mount to evaluate CUSTOM_EVENT and\n * FEATURE_ACCESS signals when track() is called.\n * @internal\n */\n _onTrackRef: React.MutableRefObject<((name: string, properties?: Record<string, unknown>) => void) | null>;\n}\n\n// ─── Context ────────────────────────────────────────────────────\n\n// Note: useAnalytics hook is in a separate file (useAnalytics.ts) for React Fast Refresh compatibility.\nexport const AnalyticsContext = createContext<AnalyticsContextValue | null>(null);\n\n/** Identity snapshots come from the mounted AppScope owner, never a decoded token or a late event. */\nexport interface AnalyticsIdentity {\n userId: string | null;\n organizationId: string | null;\n applicationId: string | null;\n anonymousUserId: string | null;\n}\nexport const AnalyticsIdentityPublisherContext = createContext<((identity: AnalyticsIdentity) => () => void) | null>(null);\n\n// ─── Provider Registry (singleton) ──────────────────────────────\n\nconst providerRegistry = new AnalyticsProviderRegistry();\n\n/** The event property carrying when a held sign-in happened, for destinations that stamp events themselves. */\nconst SIGNED_IN_AT_PROPERTY = 'signed_in_at';\n\n/**\n * A sign-in announced before this tab knows whether the person consented to analytics (#1977): when it\n * happened, whether the person's own preferences have decided it, and which kinds of destination it\n * is still owed to.\n */\ninterface HeldSignIn {\n readonly occurredAt: number;\n readonly decided: boolean;\n readonly owedToBuiltIns: boolean;\n readonly owedToVendorSinks: boolean;\n}\n\n// ─── Provider Component ─────────────────────────────────────────\n\nexport interface AnalyticsContextProviderProps {\n children: React.ReactNode;\n}\n\n/**\n * Two kinds of destination, and only ONE of them is a vendor (#1704).\n *\n * - The ENGINE's own destinations (`console`, `backend_proxy`), selected by `analytics.providers`. They send\n * nothing to a third party (the proxy posts to the application's own backend), and they keep the gate\n * below: `analytics.enabled`, then `analytics.requiresConsent` / the ANALYTICS grant.\n * - VENDORS (PostHog, …) arrive as `FRONTEND_PRODUCT_ANALYTICS` provider modules. They are started by the\n * consent-based activation consumer once the person grants what they rest on, and stopped on withdrawal\n * or sign-out; this context only dispatches to the sinks that are running. That replaced an\n * `analyticsProviders` / `customProviders` door which let an application pass a vendor client here,\n * behind a second consent gate and outside the CSP footprint — two gates for one decision.\n *\n * `analytics.enabled` stays the master switch for both: with it off, a `FRONTEND_PRODUCT_ANALYTICS` vendor is not\n * even loaded (the consent-based consumer skips it), and any sink that is running receives nothing.\n */\n/**\n * How long vendor calls made because of a write to the person's own preferences wait for the stored consent (#3928).\n * The re-read normally answers in a fraction of a second; past this the held calls are dropped, never sent.\n */\nconst OWN_PREFERENCES_WRITE_HOLD_MS = 10_000;\n\nexport const AnalyticsContextProvider: React.FC<AnalyticsContextProviderProps> = ({\n children,\n}) => {\n const appContext = useContext(ApplicationContext);\n const { on } = useEventBus();\n // Whether this consumer serves the progression-backed analytics routes at all (#1069).\n const momentsReachable = useResourceReachability(CoreResourceType.USER_PROGRESSION_STATE);\n const providersRef = useRef<IAnalyticsProvider[]>([]);\n const [isActive, setIsActive] = useState(false);\n\n // Session start: captured once at mount\n const sessionStartTimestamp = useRef(Date.now()).current;\n\n // Resolve analytics config from ApplicationContext\n const analyticsConfig = useMemo<AnalyticsConfig | undefined>(\n () => appContext?.appConfig?.analytics,\n [appContext?.appConfig?.analytics],\n );\n\n // ─── Consent gating ─────────────────────────────────────────\n\n /*\n * The purposes the signed-in person granted — a SET (#534). Starts EMPTY, never at a level: nothing\n * is known to be granted until the person's preferences arrive, and analytics that started on an\n * assumed consent would already have sent data by the time the real answer said otherwise.\n *\n * This used to hold one `DataProcessingConsent` and compare it against a module-private\n * `CONSENT_ORDER` with `>=`, which asserted that agreeing to marketing implied agreeing to analytics\n * — a claim nobody decided. Membership of ANALYTICS is the whole test now.\n */\n /*\n * ONE subject grants: the signed-in ACCOUNT.\n *\n * A second, VISITOR tier lived here briefly (#1258 Step 1d) and was removed on 2026-09-20 with the\n * pre-auth panel that fed it — see `PublicLayout_MainContainer` for why that panel went. Nothing\n * publishes a visitor decision to this provider any more, so a visitor tier here would be a state\n * nothing can ever set: the application's public pages run no consent-based analytics, which is the\n * behaviour they had before the panel existed and is the safe direction.\n *\n * `null` means \"nothing has been said\", which is not the same as granting nothing — an empty array\n * is a real, recorded withdrawal and must gate. That distinction is why this is not a bare array.\n */\n const [accountPurposes, setAccountPurposes] = useState<readonly ConsentPurpose[] | null>(null);\n const grantedPurposes = useMemo<readonly ConsentPurpose[]>(() => accountPurposes ?? [], [accountPurposes]);\n\n /*\n * A write to the person's own preferences can change their consent, so what a vendor receives because of it is\n * decided against the consent the write LEAVES, never the one the page held before it (#3928).\n *\n * Measured in a real browser with PostHog: a withdrawal on the Preferences page let the `resource_operation` event of\n * that very write reach PostHog 3 s later. The bridge captured it on `NOTIFY_RESOURCE_SUCCESS`, while the page still\n * held the grant; `UserOrgsProvider` re-reads the record on the write's `RESOURCE_OPERATION_EXECUTED` (#1973), and\n * the vendor's `deactivate` ran after its SDK had queued the event (posthog-js's opt-out does not empty its send\n * queue, and offers no public way to). So the write OPENS a hold: vendor calls queue while it is open, and the next\n * privacy-carrying `USER_PREFERENCES_CHANGED` (the re-read's) closes it, delivering them only while ANALYTICS is\n * still granted. A form emits the outcome before its success notification, so the hold is open before the bridge\n * captures. A sign-out (`privacy: null`) drops them, and a re-read that never lands drops them after the bound: an\n * event whose consent is unknown is not sent.\n *\n * Vendor sinks only: a built-in destination keeps what it buffered until it flushes, and a withdrawal already drops\n * that buffer (`discardUnsent` below).\n */\n const vendorHoldRef = useRef<{ held: Array<() => void>; timer: ReturnType<typeof setTimeout> } | null>(null);\n const releaseVendorHold = useCallback((deliver: boolean): void => {\n const hold = vendorHoldRef.current;\n if (hold === null) return;\n vendorHoldRef.current = null;\n clearTimeout(hold.timer);\n if (deliver) hold.held.forEach((call) => call());\n }, []);\n /** Open the hold, or restart its bound when it is already open (a second write before the first one's answer). */\n const openVendorHold = useCallback((): void => {\n const held = vendorHoldRef.current?.held ?? [];\n if (vendorHoldRef.current) clearTimeout(vendorHoldRef.current.timer);\n vendorHoldRef.current = { held, timer: setTimeout(() => releaseVendorHold(false), OWN_PREFERENCES_WRITE_HOLD_MS) };\n }, [releaseVendorHold]);\n /*\n * Two doors open it, because the two announcements of one write arrive in either order. A form's SECTION save announces\n * the outcome (`RESOURCE_OPERATION_EXECUTED`) before its success notification; its MAIN save notifies success first,\n * and the bridge captures `resource_operation` from that notification before the outcome is announced (measured in the\n * browser: the hold opened by the outcome alone missed the Preferences page's Save). So an analytics event ABOUT a\n * write to the person's own preferences opens the hold itself, in `track`, and the outcome opens it for whatever else\n * follows the write.\n */\n useEffect(() => on(\n FrontendEvents.RESOURCE_OPERATION_EXECUTED,\n () => openVendorHold(),\n (payload) => payload.resourceType === CoreResourceType.USER_SELF_PREFERENCES\n && !isReadShapedOperation(payload.operation ?? { operationIdentifier: payload.operationIdentifier }),\n ), [on, openVendorHold]);\n useEffect(() => () => releaseVendorHold(false), [releaseVendorHold]);\n\n useEffect(() => {\n return on(FrontendEvents.USER_PREFERENCES_CHANGED, (payload) => {\n /*\n * `privacy: null` is the CLEARED state — sign-out, or an identity with no preferences. It must\n * revoke: the old handler ignored it, so a signed-out browser kept the previous person's consent\n * and analytics kept running for whoever used it next.\n */\n /*\n * A withdrawal drops what the destinations buffered, before the gate below shuts them down: their\n * shutdown flushes, and events collected under the grant are not sent after it is withdrawn (#1977\n * review). A sign-out already sent its person's buffer, under their consent, on `USER_LOGOUT`.\n */\n const discardUnsent = (): void => {\n if (requiresConsentRef.current) providersRef.current.forEach(p => p.discard());\n };\n if (payload.privacy === null) {\n releaseVendorHold(false);\n discardUnsent();\n setAccountPurposes([]);\n return;\n }\n const purposes = payload.privacy?.consentedPurposes;\n // `undefined` means this event carried no privacy block; an EMPTY set is a real withdrawal and\n // must reach the gate below, which is why this does not test truthiness.\n if (purposes !== undefined) {\n const granted = normalizeConsentPurposes(purposes);\n const analyticsGranted = hasGrantedConsentPurposes(granted, [ConsentPurpose.ANALYTICS]);\n // Before the gate changes: what an own-preferences write held is decided by this, the stored consent.\n releaseVendorHold(analyticsGranted);\n if (!analyticsGranted) discardUnsent();\n setAccountPurposes(granted);\n }\n });\n }, [on, releaseVendorHold]);\n\n\n /*\n * The person `USER_LOGIN` announced, until `USER_LOGOUT` (#1977). Kept because the two arrive in the\n * wrong order for the built-in destinations: `UserOrgsProvider` announces the person once their\n * context has loaded, which is also when their preferences — and so their ANALYTICS grant — arrive,\n * and the destinations below are initialised asynchronously after that grant. An identify sent only\n * when the event fires would reach no destination, so each one is identified again as it starts.\n */\n const signedInUserIdRef = useRef<string | null>(null);\n const [builtInsStartedVersion, setBuiltInsStartedVersion] = useState(0);\n /** The latest `track`, for the departure listener, which must send while the grant still holds. */\n const lifecycleTrackRef = useRef<(name: string) => void>(() => {});\n\n // Initialize/teardown providers based on config + consent\n useEffect(() => {\n if (!analyticsConfig?.enabled) {\n setIsActive(false);\n return;\n }\n\n const hasConsent = analyticsConfig.requiresConsent === false\n || hasGrantedConsentPurposes(grantedPurposes, [ConsentPurpose.ANALYTICS]);\n\n if (!hasConsent) {\n providersRef.current.forEach(p => p.reset());\n setIsActive(false);\n return;\n }\n\n let aborted = false;\n\n const httpClient = getManualCallsHttpClient();\n const builtInProviders = providerRegistry.resolveFromConfig(\n analyticsConfig.providers ?? [],\n httpClient,\n );\n const allProviders = [...builtInProviders];\n\n Promise.all(\n allProviders.map(p =>\n p.initialize(analyticsConfig.providers?.find(c => c.providerType === p.name)?.config).catch(err => {\n console.warn(`[Analytics] Failed to initialize provider \"${p.name}\":`, err);\n })\n )\n ).then(() => {\n if (aborted) return;\n providersRef.current = allProviders;\n const signedInUserId = signedInUserIdRef.current;\n if (signedInUserId !== null) allProviders.forEach(p => p.identify({ userId: signedInUserId }));\n setIsActive(true);\n // `isActive` may already be true (a re-initialisation on a changed grant), so this is what tells a\n // held sign-in that a fresh set of destinations has started.\n setBuiltInsStartedVersion(version => version + 1);\n });\n\n return () => {\n aborted = true;\n allProviders.forEach(p => p.shutdown().catch(() => {}));\n providersRef.current = [];\n };\n }, [analyticsConfig, grantedPurposes]);\n\n // The vendor sinks currently running (#1704) — empty until the person grants ANALYTICS, emptied on\n // withdrawal or sign-out. Behind the same master switch as the built-in destinations.\n const consentBasedActivations = useConsentBasedProviderActivations();\n const vendorSinks = useMemo<readonly FrontendProductAnalyticsSink[]>(() => {\n if (!analyticsConfig?.enabled) return [];\n return consentBasedActivations\n .filter((running) => running.providerCapabilities.includes(BUILTIN_PROVIDER_CAPABILITY.FRONTEND_PRODUCT_ANALYTICS))\n .map((running) => running.activation.handle)\n .filter(isFrontendProductAnalyticsSink);\n }, [analyticsConfig?.enabled, consentBasedActivations]);\n const isDispatching = isActive || vendorSinks.length > 0;\n\n /*\n * The person's arrival and departure (#1977) — identity for every destination, and the sign-in /\n * sign-out analytics events (`autoInstrumentation.userLifecycle`).\n *\n * Handled HERE rather than in `AnalyticsEventBridge`, which is keyed on the published identity and is\n * therefore remounted by exactly the transitions these events announce, and which only listens while\n * analytics is already dispatching. Two consequences of the order things happen in:\n *\n * - A sign-in is announced when the person's context loads, and their ANALYTICS grant arrives with\n * their preferences a moment later; so the sign-in event is HELD, stamped with the instant it\n * happened. It is decided by the person's own preferences: if they carry the ANALYTICS grant (the\n * grant the person had already recorded before this sign-in, so the sign-in happened under it), the\n * event is sent to each kind of destination as that kind starts — the built-in destinations after\n * their asynchronous initialisation, the vendor sinks when the consent-based phase starts them. If\n * they do not, the event is DROPPED rather than sent after some later grant: an event that happened\n * while the person had not consented is not collected retroactively. A departure drops it too, and\n * a later withdrawal drops whatever has not been delivered yet. An application whose analytics does\n * not rest on consent (`requiresConsent: false`) needs no decision.\n * - A sign-out is announced BEFORE the sign-out publishes `privacy: null` (see `UserOrgsProvider`), so\n * the event is sent while the person's grant still holds, and only then is the identity reset —\n * `track` then `reset`, the order an analytics client expects.\n *\n * Only a sign-in in this tab and the person's own sign-out are COUNTED; a resumed session, a session\n * the backend ended, one ended in another tab and one replaced by another person are identity changes\n * only (see `SessionEstablishment` / `SessionEndReason`).\n */\n const userLifecycleTracking = analyticsConfig?.autoInstrumentation?.userLifecycle === true;\n const userLifecycleTrackingRef = useRef(userLifecycleTracking);\n userLifecycleTrackingRef.current = userLifecycleTracking;\n const requiresConsent = analyticsConfig?.requiresConsent !== false;\n const requiresConsentRef = useRef(requiresConsent);\n requiresConsentRef.current = requiresConsent;\n const heldSignInRef = useRef<HeldSignIn | null>(null);\n /** Re-runs the delivery effect below when a held sign-in is decided (a ref alone would not). */\n const [heldSignInVersion, setHeldSignInVersion] = useState(0);\n const holdSignIn = useCallback((next: HeldSignIn | null) => {\n heldSignInRef.current = next;\n setHeldSignInVersion(version => version + 1);\n }, []);\n useEffect(() => {\n return on(FrontendEvents.USER_LOGIN, (payload) => {\n signedInUserIdRef.current = payload.userId;\n providersRef.current.forEach(p =>\n p.identify({ userId: payload.userId })\n );\n if (payload.establishment === SessionEstablishment.SIGNED_IN) {\n holdSignIn({ occurredAt: Date.now(), decided: !requiresConsentRef.current, owedToBuiltIns: true, owedToVendorSinks: true });\n }\n });\n }, [on, holdSignIn]);\n\n useEffect(() => {\n return on(FrontendEvents.USER_PREFERENCES_CHANGED, (payload) => {\n const held = heldSignInRef.current;\n // `privacy: null` is a sign-out's clearing, not this person's decision; a departure already dropped the hold.\n if (held === null || !requiresConsentRef.current || !payload.privacy) return;\n const purposes = payload.privacy.consentedPurposes;\n if (purposes === undefined) return;\n holdSignIn(hasGrantedConsentPurposes(normalizeConsentPurposes(purposes), [ConsentPurpose.ANALYTICS]) ? { ...held, decided: true } : null);\n });\n }, [on, holdSignIn]);\n\n useEffect(() => {\n return on(FrontendEvents.USER_LOGOUT, (payload) => {\n if (payload.reason === SessionEndReason.SIGNED_OUT && userLifecycleTrackingRef.current) {\n lifecycleTrackRef.current(AnalyticsEventName.USER_LOGOUT);\n }\n holdSignIn(null);\n signedInUserIdRef.current = null;\n providersRef.current.forEach(p => p.reset());\n });\n }, [on, holdSignIn]);\n\n // ─── Achieved moments persistence ─────────────────────────────\n\n const [identity, setIdentity] = useState<AnalyticsIdentity | null>(null);\n const identityOwner = useRef<symbol | null>(null);\n const publishIdentity = useCallback((next: AnalyticsIdentity) => {\n const owner = Symbol();\n identityOwner.current = owner;\n setIdentity(next);\n return () => {\n if (identityOwner.current === owner) { identityOwner.current = null; setIdentity(null); }\n };\n }, []);\n const identityKey = JSON.stringify(identity);\n\n /*\n * Who a running vendor sink attributes events to (#1704): the person the mounted app scope publishes\n * (`publishIdentity`), which is the identity this provider already trusts for value moments. Keyed on the\n * user id and on WHICH sinks run, so a sink started later is identified on its first render, and a person\n * who leaves (identity lost) is forgotten by every sink still running. The published identity rather\n * than `USER_LOGIN` / `USER_LOGOUT` because a sink starts whenever the grant arrives, and the identity\n * is STATE a sink started later can read, where the announcement is a moment it would have missed.\n */\n const identifiedUserId = identity?.userId ?? null;\n useEffect(() => {\n if (vendorSinks.length === 0) return;\n if (identifiedUserId !== null) vendorSinks.forEach(sink => sink.identify({ userId: identifiedUserId }));\n else vendorSinks.forEach(sink => sink.reset());\n }, [vendorSinks, identifiedUserId]);\n const currentIdentityKey = useRef(identityKey);\n currentIdentityKey.current = identityKey;\n const momentProgress = useRef<AnalyticsMomentProgress>({ signals: new Map(), counts: new Map(), lastFired: new Map(), completed: new Set() });\n const userStorageKey = identity?.userId\n ? `${ANALYTICS_ACHIEVED_STORAGE_KEY_PREFIX}${JSON.stringify([identity.applicationId, ValueMomentScope.USER, identity.userId])}` : null;\n const organizationStorageKey = identity?.organizationId\n ? `${ANALYTICS_ACHIEVED_STORAGE_KEY_PREFIX}${JSON.stringify([identity.applicationId, ValueMomentScope.ORGANIZATION, identity.organizationId])}` : null;\n const storageKey = JSON.stringify([userStorageKey, organizationStorageKey]);\n const isOrganizationMoment = useCallback((id: string) =>\n analyticsConfig?.valueMoments?.find(moment => moment.identifier === id)?.scope === ValueMomentScope.ORGANIZATION,\n [analyticsConfig?.valueMoments]);\n const isPersistentMoment = useCallback((id: string) =>\n analyticsConfig?.valueMoments?.find(moment => moment.identifier === id)?.role !== ValueMomentRole.ANTI_PATTERN,\n [analyticsConfig?.valueMoments]);\n\n const [achievementState, setAchievementState] = useState<{key: string; moments: Set<string>}>({key: identityKey, moments: new Set()});\n const achievedMoments = useMemo(() => achievementState.key === identityKey ? achievementState.moments : new Set<string>(), [achievementState, identityKey]);\n const setAchievedMoments = useCallback((update: React.SetStateAction<Set<string>>) => {\n setAchievementState(previous => ({key: identityKey, moments: typeof update === 'function'\n ? update(previous.key === identityKey ? previous.moments : new Set()) : update}));\n }, [identityKey]);\n\n // Helper: persist to localStorage\n const persistToStorage = useCallback((moments: Set<string>) => {\n try {\n if (userStorageKey) localStorage.setItem(userStorageKey, JSON.stringify([...moments].filter(id => !isOrganizationMoment(id))));\n if (organizationStorageKey) localStorage.setItem(organizationStorageKey, JSON.stringify([...moments].filter(isOrganizationMoment)));\n } catch {\n /* quota exceeded — best effort */\n }\n }, [userStorageKey, organizationStorageKey, isOrganizationMoment]);\n\n // Load from localStorage on mount + fetch from backend if backendSync\n useEffect(() => {\n setAchievedMoments(new Set());\n if (!analyticsConfig?.enabled || !identity || (!identity.userId && !identity.organizationId)) return;\n\n // Load from localStorage\n try {\n const loaded = new Set<string>();\n for (const [key, organization] of [[userStorageKey, false], [organizationStorageKey, true]] as const) {\n if (!key) continue;\n const stored = localStorage.getItem(key);\n if (stored) for (const id of JSON.parse(stored) as string[]) {\n if (isPersistentMoment(id) && isOrganizationMoment(id) === organization) loaded.add(id);\n }\n }\n setAchievedMoments(loaded);\n } catch {\n /* corrupt storage — start fresh */\n }\n\n // Fetch from backend if backendSync enabled AND this consumer can reach the route (#1069, the\n // #268 rule): achieved moments are read from the progression store, which a consumer whose\n // registry excludes it does not serve. localStorage still loads above.\n if (analyticsConfig?.persistence?.backendSync && momentsReachable) {\n let aborted = false;\n getManualCallsHttpClient()\n .getAnalyticsMomentsAchieved()\n .then((response: unknown) => {\n if (aborted || currentIdentityKey.current !== identityKey) return;\n const res = response as { moments?: string[] };\n if (res.moments) {\n setAchievedMoments(prev => {\n const merged = new Set([...prev, ...res.moments!].filter(isPersistentMoment));\n persistToStorage(merged);\n return merged;\n });\n }\n })\n .catch(() => {\n /* Backend unavailable — use localStorage only */\n });\n\n return () => { aborted = true; };\n }\n }, [analyticsConfig?.enabled, analyticsConfig?.persistence?.backendSync, momentsReachable, storageKey, identityKey, persistToStorage, isPersistentMoment, isOrganizationMoment]);\n\n // Subscribe to ANALYTICS_MOMENT_ACHIEVED events (backend-pushed via WS)\n useEffect(() => {\n return on(FrontendEvents.ANALYTICS_MOMENT_ACHIEVED, (payload) => {\n if (!identity || payload.triggerSource === AnalyticsTriggerSource.FRONTEND || payload.role === ValueMomentRole.ANTI_PATTERN || !isPersistentMoment(payload.momentIdentifier)) return;\n setAchievedMoments(prev => {\n const next = new Set(prev);\n next.add(payload.momentIdentifier);\n persistToStorage(next);\n return next;\n });\n });\n }, [on, persistToStorage, identityKey, isPersistentMoment]);\n\n const markMomentAchieved = useCallback((identifier: string): boolean | Promise<boolean> => {\n if (!identity || !isPersistentMoment(identifier)) return false;\n const definition = analyticsConfig?.valueMoments?.find(moment => moment.identifier === identifier);\n if (definition?.requires?.some(id => !achievedMoments.has(id)) || definition?.beforeStage?.some(id => achievedMoments.has(id))) return false;\n const record = (): boolean => {\n if (currentIdentityKey.current !== identityKey) return false;\n setAchievedMoments(prev => {\n const next = new Set(prev); next.add(identifier); persistToStorage(next); return next;\n });\n return true;\n };\n if (!analyticsConfig?.persistence?.backendSync) return record();\n // A refused report is not an achievement. Network failures retain the documented best-effort\n // local behavior; explicit server refusals must never be merged back as local truth.\n return getManualCallsHttpClient().postAnalyticsMomentsAchieved({ momentIdentifier: identifier, scope: definition?.scope })\n .then(result => result.success === false ? false : record())\n .catch((error: unknown) => {\n const response = error as {httpStatus?: number; response?: {status?: number}};\n const status = response?.httpStatus ?? response?.response?.status;\n return status && status >= 400 && status < 500 ? false : record();\n });\n }, [analyticsConfig, persistToStorage, identityKey, isPersistentMoment, achievedMoments]);\n\n // ─── Track interceptor ref ────────────────────────────────────\n\n const onTrackRef = useRef<((name: string, properties?: Record<string, unknown>) => void) | null>(null);\n\n const track = useCallback((name: string, properties?: Record<string, unknown>) => {\n if (!isDispatching) return;\n const event: AnalyticsEvent = { name, properties, timestamp: Date.now() };\n if (isActive) providersRef.current.forEach(p => p.track(event));\n // An event about a write to the person's own preferences waits for the consent that write leaves (see the hold).\n if (name === AnalyticsEventName.RESOURCE_OPERATION && properties?.resourceType === CoreResourceType.USER_SELF_PREFERENCES) openVendorHold();\n const toVendors = (): void => vendorSinks.forEach(sink => sink.track({ name, properties }));\n if (vendorHoldRef.current) vendorHoldRef.current.held.push(toVendors);\n else toVendors();\n // Forward to bridge interceptor for CUSTOM_EVENT / FEATURE_ACCESS signal evaluation\n onTrackRef.current?.(name, properties);\n }, [isActive, isDispatching, vendorSinks, openVendorHold]);\n lifecycleTrackRef.current = track;\n\n // Deliver a decided sign-in to each kind of destination as that kind starts — see the block above.\n useEffect(() => {\n const held = heldSignInRef.current;\n if (held === null || !held.decided || !userLifecycleTracking) return;\n const event: AnalyticsEvent = { name: AnalyticsEventName.USER_LOGIN, timestamp: held.occurredAt };\n let owedToBuiltIns = held.owedToBuiltIns;\n let owedToVendorSinks = held.owedToVendorSinks;\n if (owedToBuiltIns && isActive && providersRef.current.length > 0) {\n providersRef.current.forEach(p => p.track(event));\n owedToBuiltIns = false;\n }\n if (owedToVendorSinks && vendorSinks.length > 0) {\n // A vendor sink's `track` takes no timestamp — the vendor stamps receipt — so when the sign-in\n // happened travels as a property, and the vendor-side time may be later than the sign-in.\n vendorSinks.forEach(sink => sink.track({ name: event.name, properties: { [SIGNED_IN_AT_PROPERTY]: new Date(held.occurredAt).toISOString() } }));\n owedToVendorSinks = false;\n }\n if (owedToBuiltIns !== held.owedToBuiltIns || owedToVendorSinks !== held.owedToVendorSinks) {\n heldSignInRef.current = owedToBuiltIns || owedToVendorSinks ? { ...held, owedToBuiltIns, owedToVendorSinks } : null;\n }\n }, [heldSignInVersion, builtInsStartedVersion, isActive, vendorSinks, userLifecycleTracking]);\n\n const page = useCallback((path: string, properties?: Record<string, unknown>) => {\n if (!isDispatching) return;\n if (isActive) providersRef.current.forEach(p => p.page(path, properties));\n const toVendors = (): void => vendorSinks.forEach(sink => sink.page(path, properties));\n if (vendorHoldRef.current) vendorHoldRef.current.held.push(toVendors);\n else toVendors();\n }, [isActive, isDispatching, vendorSinks]);\n\n // ─── Render ───────────────────────────────────────────────────\n\n const contextValue = useMemo<AnalyticsContextValue>(() => ({\n track,\n page,\n isActive: isDispatching,\n sessionStartTimestamp,\n achievedMoments,\n markMomentAchieved,\n _onTrackRef: onTrackRef,\n }), [track, page, isDispatching, sessionStartTimestamp, achievedMoments, markMomentAchieved]);\n\n return (\n <AnalyticsIdentityPublisherContext.Provider value={publishIdentity}>\n <AnalyticsContext.Provider value={contextValue}>\n {isDispatching && identity && analyticsConfig && (\n <AnalyticsEventBridge\n key={`${identityKey}:${JSON.stringify(analyticsConfig.valueMoments)}`}\n identity={identity}\n progress={momentProgress.current}\n config={analyticsConfig.autoInstrumentation}\n valueMoments={analyticsConfig.valueMoments} \n />\n )}\n {children}\n </AnalyticsContext.Provider>\n </AnalyticsIdentityPublisherContext.Provider>\n );\n};\n"]}
1
+ {"version":3,"file":"AnalyticsContext.js","sourceRoot":"","sources":["../../../../../src/core/monitoring/analytics/AnalyticsContext.tsx"],"names":[],"mappings":";AAAA;;;;;GAKG;AAEH,OAAc,EAAE,aAAa,EAAE,UAAU,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC5G,OAAO,EAAE,kBAAkB,EAAE,2BAA2B,EAAE,cAAc,EAAE,gBAAgB,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,eAAe,EAAE,gBAAgB,EAAE,sBAAsB,EAAwB,qCAAqC,EAAE,MAAM,uBAAuB,CAAC;AAEvS,OAAO,EAAE,yBAAyB,EAAE,MAAM,gDAAgD,CAAC;AAC3F,OAAO,EAAE,kBAAkB,EAAE,MAAM,4DAA4D,CAAC;AAChG,OAAO,EAAE,WAAW,EAAE,MAAM,6CAA6C,CAAC;AAC1E,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,yDAAyD,CAAC;AACjI,OAAO,EAAE,wBAAwB,EAAE,MAAM,mFAAmF,CAAC;AAC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C;QAC1E,MAAM,SAAS,GAAG,GAAS,EAAE,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC;QACvF,IAAI,aAAa,CAAC,OAAO;YAAE,aAAa,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;;YACjE,SAAS,EAAE,CAAC;IACnB,CAAC,EAAE,CAAC,QAAQ,EAAE,aAAa,EAAE,WAAW,CAAC,CAAC,CAAC;IAE3C,iEAAiE;IAEjE,MAAM,YAAY,GAAG,OAAO,CAAwB,GAAG,EAAE,CAAC,CAAC;QACzD,KAAK;QACL,IAAI;QACJ,QAAQ,EAAE,aAAa;QACvB,qBAAqB;QACrB,eAAe;QACf,kBAAkB;QAClB,WAAW,EAAE,UAAU;KACxB,CAAC,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,qBAAqB,EAAE,eAAe,EAAE,kBAAkB,CAAC,CAAC,CAAC;IAE9F,OAAO,CACL,KAAC,iCAAiC,CAAC,QAAQ,IAAC,KAAK,EAAE,eAAe,YAClE,MAAC,gBAAgB,CAAC,QAAQ,IAAC,KAAK,EAAE,YAAY,aAC3C,aAAa,IAAI,QAAQ,IAAI,eAAe,IAAI,CAC/C,KAAC,oBAAoB,IAEnB,QAAQ,EAAE,QAAQ,EAClB,QAAQ,EAAE,cAAc,CAAC,OAAO,EAChC,MAAM,EAAE,eAAe,CAAC,mBAAmB,EAC3C,YAAY,EAAE,eAAe,CAAC,YAAY,IAJrC,GAAG,WAAW,IAAI,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,YAAY,CAAC,EAAE,CAKrE,CACH,EACA,QAAQ,IACiB,GACiB,CAC9C,CAAC;AACJ,CAAC,CAAC","sourcesContent":["/**\n * Analytics Context Provider\n * \n * Provides analytics tracking, value moment achievement persistence,\n * consent gating, and provider lifecycle management.\n */\n\nimport React, { createContext, useContext, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { AnalyticsEventName, BUILTIN_PROVIDER_CAPABILITY, ConsentPurpose, CoreResourceType, hasGrantedConsentPurposes, normalizeConsentPurposes, ValueMomentRole, ValueMomentScope, AnalyticsTriggerSource, type AnalyticsConfig, ANALYTICS_ACHIEVED_STORAGE_KEY_PREFIX } from '@wildo-ai/saas-models';\nimport type { IAnalyticsProvider, AnalyticsEvent } from './analytics-provider.frontend.interface';\nimport { AnalyticsProviderRegistry } from './analytics-provider-registry.frontend.service';\nimport { ApplicationContext } from '~wildo-frontend-lib/core/runtime/ApplicationContext.shared';\nimport { useEventBus } from '~wildo-frontend-lib/core/events/useEventBus';\nimport { FrontendEvents, SessionEndReason, SessionEstablishment } from '~wildo-frontend-lib/core/events/events.frontend.schemas';\nimport { getManualCallsHttpClient } from '~wildo-frontend-lib/core/requests/wildo-http-client-manual-calls.frontend.service';\nimport { useResourceReachability } from '~wildo-frontend-lib/core/resources/useResourceRegistry';\nimport { AnalyticsEventBridge, type AnalyticsMomentProgress } from './AnalyticsEventBridge';\nimport { isFrontendProductAnalyticsSink, type FrontendProductAnalyticsSink } from '@wildo-ai/saas-models/public-runtime';\nimport { useConsentBasedProviderActivations } from '~wildo-frontend-lib/core/external-providers/ConsentBasedProviderSdks';\n\n// ─── Context Value Interface ────────────────────────────────────\n\nexport interface AnalyticsContextValue {\n /** Track a custom event (app-custom usage) */\n track: (name: string, properties?: Record<string, unknown>) => void;\n /** Track a page view */\n page: (path: string, properties?: Record<string, unknown>) => void;\n /** Whether analytics is active (enabled + consent granted) */\n isActive: boolean;\n /** Session start timestamp (for TTFV computation) */\n sessionStartTimestamp: number;\n /** Set of achieved value moment identifiers (scope-aware, persisted) */\n achievedMoments: Set<string>;\n /** Mark a value moment as achieved (persists to localStorage + backend sync) */\n markMomentAchieved: (identifier: string) => boolean | Promise<boolean>;\n /**\n * Internal: ref for track() call interception (used by AnalyticsEventBridge).\n * The bridge registers a callback on mount to evaluate CUSTOM_EVENT and\n * FEATURE_ACCESS signals when track() is called.\n * @internal\n */\n _onTrackRef: React.MutableRefObject<((name: string, properties?: Record<string, unknown>) => void) | null>;\n}\n\n// ─── Context ────────────────────────────────────────────────────\n\n// Note: useAnalytics hook is in a separate file (useAnalytics.ts) for React Fast Refresh compatibility.\nexport const AnalyticsContext = createContext<AnalyticsContextValue | null>(null);\n\n/** Identity snapshots come from the mounted AppScope owner, never a decoded token or a late event. */\nexport interface AnalyticsIdentity {\n userId: string | null;\n organizationId: string | null;\n applicationId: string | null;\n anonymousUserId: string | null;\n}\nexport const AnalyticsIdentityPublisherContext = createContext<((identity: AnalyticsIdentity) => () => void) | null>(null);\n\n// ─── Provider Registry (singleton) ──────────────────────────────\n\nconst providerRegistry = new AnalyticsProviderRegistry();\n\n/** The event property carrying when a held sign-in happened, for destinations that stamp events themselves. */\nconst SIGNED_IN_AT_PROPERTY = 'signed_in_at';\n\n/**\n * A sign-in announced before this tab knows whether the person consented to analytics (#1977): when it\n * happened, whether the person's own preferences have decided it, and which kinds of destination it\n * is still owed to.\n */\ninterface HeldSignIn {\n readonly occurredAt: number;\n readonly decided: boolean;\n readonly owedToBuiltIns: boolean;\n readonly owedToVendorSinks: boolean;\n}\n\n// ─── Provider Component ─────────────────────────────────────────\n\nexport interface AnalyticsContextProviderProps {\n children: React.ReactNode;\n}\n\n/**\n * Two kinds of destination, and only ONE of them is a vendor (#1704).\n *\n * - The ENGINE's own destinations (`console`, `backend_proxy`), selected by `analytics.providers`. They send\n * nothing to a third party (the proxy posts to the application's own backend), and they keep the gate\n * below: `analytics.enabled`, then `analytics.requiresConsent` / the ANALYTICS grant.\n * - VENDORS (PostHog, …) arrive as `FRONTEND_PRODUCT_ANALYTICS` provider modules. They are started by the\n * consent-based activation consumer once the person grants what they rest on, and stopped on withdrawal\n * or sign-out; this context only dispatches to the sinks that are running. That replaced an\n * `analyticsProviders` / `customProviders` door which let an application pass a vendor client here,\n * behind a second consent gate and outside the CSP footprint — two gates for one decision.\n *\n * `analytics.enabled` stays the master switch for both: with it off, a `FRONTEND_PRODUCT_ANALYTICS` vendor is not\n * even loaded (the consent-based consumer skips it), and any sink that is running receives nothing.\n */\n/**\n * How long vendor calls made because of a write to the person's own preferences wait for the stored consent (#3928).\n * The re-read normally answers in a fraction of a second; past this the held calls are dropped, never sent.\n */\nconst OWN_PREFERENCES_WRITE_HOLD_MS = 10_000;\n\nexport const AnalyticsContextProvider: React.FC<AnalyticsContextProviderProps> = ({\n children,\n}) => {\n const appContext = useContext(ApplicationContext);\n const { on } = useEventBus();\n // Whether this consumer serves the progression-backed analytics routes at all (#1069).\n const momentsReachable = useResourceReachability(CoreResourceType.USER_PROGRESSION_STATE);\n const providersRef = useRef<IAnalyticsProvider[]>([]);\n const [isActive, setIsActive] = useState(false);\n\n // Session start: captured once at mount\n const sessionStartTimestamp = useRef(Date.now()).current;\n\n // Resolve analytics config from ApplicationContext\n const analyticsConfig = useMemo<AnalyticsConfig | undefined>(\n () => appContext?.appConfig?.analytics,\n [appContext?.appConfig?.analytics],\n );\n\n // ─── Consent gating ─────────────────────────────────────────\n\n /*\n * The purposes the signed-in person granted — a SET (#534). Starts EMPTY, never at a level: nothing\n * is known to be granted until the person's preferences arrive, and analytics that started on an\n * assumed consent would already have sent data by the time the real answer said otherwise.\n *\n * This used to hold one `DataProcessingConsent` and compare it against a module-private\n * `CONSENT_ORDER` with `>=`, which asserted that agreeing to marketing implied agreeing to analytics\n * — a claim nobody decided. Membership of ANALYTICS is the whole test now.\n */\n /*\n * ONE subject grants: the signed-in ACCOUNT.\n *\n * A second, VISITOR tier lived here briefly (#1258 Step 1d) and was removed on 2026-09-20 with the\n * pre-auth panel that fed it — see `PublicLayout_MainContainer` for why that panel went. Nothing\n * publishes a visitor decision to this provider any more, so a visitor tier here would be a state\n * nothing can ever set: the application's public pages run no consent-based analytics, which is the\n * behaviour they had before the panel existed and is the safe direction.\n *\n * `null` means \"nothing has been said\", which is not the same as granting nothing — an empty array\n * is a real, recorded withdrawal and must gate. That distinction is why this is not a bare array.\n */\n const [accountPurposes, setAccountPurposes] = useState<readonly ConsentPurpose[] | null>(null);\n const grantedPurposes = useMemo<readonly ConsentPurpose[]>(() => accountPurposes ?? [], [accountPurposes]);\n\n /*\n * A write to the person's own preferences can change their consent, so what a vendor receives because of it is\n * decided against the consent the write LEAVES, never the one the page held before it (#3928).\n *\n * Measured in a real browser with PostHog: a withdrawal on the Preferences page let the `resource_operation` event of\n * that very write reach PostHog 3 s later. The bridge captured it on `NOTIFY_RESOURCE_SUCCESS`, while the page still\n * held the grant; `UserOrgsProvider` re-reads the record on the write's `RESOURCE_OPERATION_EXECUTED` (#1973), and\n * the vendor's `deactivate` ran after its SDK had queued the event (posthog-js's opt-out does not empty its send\n * queue, and offers no public way to). So the write OPENS a hold: vendor calls queue while it is open, and the answer\n * to the re-read the write started (`OWN_PREFERENCES_REREAD_SETTLED` with that read's number) closes it, delivering\n * them only while ANALYTICS is still granted. Nothing else closes it with a delivery: `UserOrgsProvider` re-announces\n * the PRE-write record whenever its organizations change, and an earlier write's re-read can land inside this one's\n * window, and either would have released the withdrawal's own event under the old grant (#3928 review). A sign-out\n * (`privacy: null`) drops them, and so does a re-read that fails or never lands (after the bound): an event whose\n * consent is unknown is not sent.\n *\n * Vendor sinks only: a built-in destination keeps what it buffered until it flushes, and a withdrawal already drops\n * that buffer (`discardUnsent` below).\n */\n /** `readId` is the re-read this hold waits for: `null` until one starts while the hold is open. */\n const vendorHoldRef = useRef<{ held: Array<() => void>; timer: ReturnType<typeof setTimeout>; readId: number | null } | null>(null);\n const releaseVendorHold = useCallback((deliver: boolean): void => {\n const hold = vendorHoldRef.current;\n if (hold === null) return;\n vendorHoldRef.current = null;\n clearTimeout(hold.timer);\n if (deliver) hold.held.forEach((call) => call());\n }, []);\n /** Open the hold, or restart its bound when it is already open (a second write before the first one's answer). */\n /**\n * The re-read started in the CURRENT synchronous turn, if any; cleared at the end of the turn. A write's success\n * notification, its outcome and the re-read it starts are emitted in ONE turn, in either order (`handleSubmit` →\n * `NOTIFY_RESOURCE_SUCCESS` → `onSuccess` → `announceOutcome` for a main save; outcome first for a section save), so a\n * network answer can never land between them. An event tracked about a write therefore belongs to the re-read started\n * in its turn, or to the next one; a re-read started in an earlier turn answers an earlier write.\n */\n const rereadStartedThisTurnRef = useRef<number | null>(null);\n /**\n * Open the hold, or restart its bound when it is already open. `readId`: the re-read that just started, which every\n * earlier write is also seen by. Without one (the `track` door), the hold waits for the re-read of this turn, or the next.\n */\n const openVendorHold = useCallback((readId?: number): void => {\n const previous = vendorHoldRef.current;\n if (previous) clearTimeout(previous.timer);\n vendorHoldRef.current = {\n held: previous?.held ?? [],\n timer: setTimeout(() => releaseVendorHold(false), OWN_PREFERENCES_WRITE_HOLD_MS),\n readId: readId ?? rereadStartedThisTurnRef.current,\n };\n }, [releaseVendorHold]);\n /*\n * Two doors open it, because the two announcements of one write arrive in either order. A form's SECTION save announces\n * the outcome (`RESOURCE_OPERATION_EXECUTED`) before its success notification; its MAIN save notifies success first,\n * and the bridge captures `resource_operation` from that notification before the outcome is announced (measured in the\n * browser: the hold opened by the outcome alone missed the Preferences page's Save). So an analytics event ABOUT a\n * write to the person's own preferences opens the hold itself, in `track`, and the re-read the write starts opens it\n * (or, if `track` opened it, names the read it waits for). The re-read rather than the outcome: it is the one thing\n * the hold waits on, so opening on it cannot miss it whichever provider hears the outcome first.\n */\n useEffect(() => on(FrontendEvents.OWN_PREFERENCES_REREAD_STARTED, ({ readId }) => {\n rereadStartedThisTurnRef.current = readId;\n queueMicrotask(() => { if (rereadStartedThisTurnRef.current === readId) rereadStartedThisTurnRef.current = null; });\n openVendorHold(readId);\n }), [on, openVendorHold]);\n useEffect(() => on(FrontendEvents.OWN_PREFERENCES_REREAD_SETTLED, ({ readId, privacy }) => {\n // Only the answer this hold waits for: an earlier read's answer, or none started yet, decides nothing about it.\n if (vendorHoldRef.current?.readId !== readId) return;\n releaseVendorHold(privacy !== null && hasGrantedConsentPurposes(normalizeConsentPurposes(privacy.consentedPurposes), [ConsentPurpose.ANALYTICS]));\n }), [on, releaseVendorHold]);\n useEffect(() => () => releaseVendorHold(false), [releaseVendorHold]);\n\n useEffect(() => {\n return on(FrontendEvents.USER_PREFERENCES_CHANGED, (payload) => {\n /*\n * `privacy: null` is the CLEARED state — sign-out, or an identity with no preferences. It must\n * revoke: the old handler ignored it, so a signed-out browser kept the previous person's consent\n * and analytics kept running for whoever used it next.\n */\n /*\n * A withdrawal drops what the destinations buffered, before the gate below shuts them down: their\n * shutdown flushes, and events collected under the grant are not sent after it is withdrawn (#1977\n * review). A sign-out already sent its person's buffer, under their consent, on `USER_LOGOUT`.\n */\n const discardUnsent = (): void => {\n if (requiresConsentRef.current) providersRef.current.forEach(p => p.discard());\n };\n if (payload.privacy === null) {\n releaseVendorHold(false);\n discardUnsent();\n setAccountPurposes([]);\n return;\n }\n const purposes = payload.privacy?.consentedPurposes;\n // `undefined` means this event carried no privacy block; an EMPTY set is a real withdrawal and\n // must reach the gate below, which is why this does not test truthiness.\n if (purposes !== undefined) {\n const granted = normalizeConsentPurposes(purposes);\n const analyticsGranted = hasGrantedConsentPurposes(granted, [ConsentPurpose.ANALYTICS]);\n // A held own-preferences write is NOT decided here: this announcement may carry the pre-write record (see the\n // hold above). Only a withdrawal acts on it, by dropping what was held, which can never send too much.\n if (!analyticsGranted) {\n releaseVendorHold(false);\n discardUnsent();\n }\n setAccountPurposes(granted);\n }\n });\n }, [on, releaseVendorHold]);\n\n\n /*\n * The person `USER_LOGIN` announced, until `USER_LOGOUT` (#1977). Kept because the two arrive in the\n * wrong order for the built-in destinations: `UserOrgsProvider` announces the person once their\n * context has loaded, which is also when their preferences — and so their ANALYTICS grant — arrive,\n * and the destinations below are initialised asynchronously after that grant. An identify sent only\n * when the event fires would reach no destination, so each one is identified again as it starts.\n */\n const signedInUserIdRef = useRef<string | null>(null);\n const [builtInsStartedVersion, setBuiltInsStartedVersion] = useState(0);\n /** The latest `track`, for the departure listener, which must send while the grant still holds. */\n const lifecycleTrackRef = useRef<(name: string) => void>(() => {});\n\n // Initialize/teardown providers based on config + consent\n useEffect(() => {\n if (!analyticsConfig?.enabled) {\n setIsActive(false);\n return;\n }\n\n const hasConsent = analyticsConfig.requiresConsent === false\n || hasGrantedConsentPurposes(grantedPurposes, [ConsentPurpose.ANALYTICS]);\n\n if (!hasConsent) {\n providersRef.current.forEach(p => p.reset());\n setIsActive(false);\n return;\n }\n\n let aborted = false;\n\n const httpClient = getManualCallsHttpClient();\n const builtInProviders = providerRegistry.resolveFromConfig(\n analyticsConfig.providers ?? [],\n httpClient,\n );\n const allProviders = [...builtInProviders];\n\n Promise.all(\n allProviders.map(p =>\n p.initialize(analyticsConfig.providers?.find(c => c.providerType === p.name)?.config).catch(err => {\n console.warn(`[Analytics] Failed to initialize provider \"${p.name}\":`, err);\n })\n )\n ).then(() => {\n if (aborted) return;\n providersRef.current = allProviders;\n const signedInUserId = signedInUserIdRef.current;\n if (signedInUserId !== null) allProviders.forEach(p => p.identify({ userId: signedInUserId }));\n setIsActive(true);\n // `isActive` may already be true (a re-initialisation on a changed grant), so this is what tells a\n // held sign-in that a fresh set of destinations has started.\n setBuiltInsStartedVersion(version => version + 1);\n });\n\n return () => {\n aborted = true;\n allProviders.forEach(p => p.shutdown().catch(() => {}));\n providersRef.current = [];\n };\n }, [analyticsConfig, grantedPurposes]);\n\n // The vendor sinks currently running (#1704) — empty until the person grants ANALYTICS, emptied on\n // withdrawal or sign-out. Behind the same master switch as the built-in destinations.\n const consentBasedActivations = useConsentBasedProviderActivations();\n const vendorSinks = useMemo<readonly FrontendProductAnalyticsSink[]>(() => {\n if (!analyticsConfig?.enabled) return [];\n return consentBasedActivations\n .filter((running) => running.providerCapabilities.includes(BUILTIN_PROVIDER_CAPABILITY.FRONTEND_PRODUCT_ANALYTICS))\n .map((running) => running.activation.handle)\n .filter(isFrontendProductAnalyticsSink);\n }, [analyticsConfig?.enabled, consentBasedActivations]);\n const isDispatching = isActive || vendorSinks.length > 0;\n\n /*\n * The person's arrival and departure (#1977) — identity for every destination, and the sign-in /\n * sign-out analytics events (`autoInstrumentation.userLifecycle`).\n *\n * Handled HERE rather than in `AnalyticsEventBridge`, which is keyed on the published identity and is\n * therefore remounted by exactly the transitions these events announce, and which only listens while\n * analytics is already dispatching. Two consequences of the order things happen in:\n *\n * - A sign-in is announced when the person's context loads, and their ANALYTICS grant arrives with\n * their preferences a moment later; so the sign-in event is HELD, stamped with the instant it\n * happened. It is decided by the person's own preferences: if they carry the ANALYTICS grant (the\n * grant the person had already recorded before this sign-in, so the sign-in happened under it), the\n * event is sent to each kind of destination as that kind starts — the built-in destinations after\n * their asynchronous initialisation, the vendor sinks when the consent-based phase starts them. If\n * they do not, the event is DROPPED rather than sent after some later grant: an event that happened\n * while the person had not consented is not collected retroactively. A departure drops it too, and\n * a later withdrawal drops whatever has not been delivered yet. An application whose analytics does\n * not rest on consent (`requiresConsent: false`) needs no decision.\n * - A sign-out is announced BEFORE the sign-out publishes `privacy: null` (see `UserOrgsProvider`), so\n * the event is sent while the person's grant still holds, and only then is the identity reset —\n * `track` then `reset`, the order an analytics client expects.\n *\n * Only a sign-in in this tab and the person's own sign-out are COUNTED; a resumed session, a session\n * the backend ended, one ended in another tab and one replaced by another person are identity changes\n * only (see `SessionEstablishment` / `SessionEndReason`).\n */\n const userLifecycleTracking = analyticsConfig?.autoInstrumentation?.userLifecycle === true;\n const userLifecycleTrackingRef = useRef(userLifecycleTracking);\n userLifecycleTrackingRef.current = userLifecycleTracking;\n const requiresConsent = analyticsConfig?.requiresConsent !== false;\n const requiresConsentRef = useRef(requiresConsent);\n requiresConsentRef.current = requiresConsent;\n const heldSignInRef = useRef<HeldSignIn | null>(null);\n /** Re-runs the delivery effect below when a held sign-in is decided (a ref alone would not). */\n const [heldSignInVersion, setHeldSignInVersion] = useState(0);\n const holdSignIn = useCallback((next: HeldSignIn | null) => {\n heldSignInRef.current = next;\n setHeldSignInVersion(version => version + 1);\n }, []);\n useEffect(() => {\n return on(FrontendEvents.USER_LOGIN, (payload) => {\n signedInUserIdRef.current = payload.userId;\n providersRef.current.forEach(p =>\n p.identify({ userId: payload.userId })\n );\n if (payload.establishment === SessionEstablishment.SIGNED_IN) {\n holdSignIn({ occurredAt: Date.now(), decided: !requiresConsentRef.current, owedToBuiltIns: true, owedToVendorSinks: true });\n }\n });\n }, [on, holdSignIn]);\n\n useEffect(() => {\n return on(FrontendEvents.USER_PREFERENCES_CHANGED, (payload) => {\n const held = heldSignInRef.current;\n // `privacy: null` is a sign-out's clearing, not this person's decision; a departure already dropped the hold.\n if (held === null || !requiresConsentRef.current || !payload.privacy) return;\n const purposes = payload.privacy.consentedPurposes;\n if (purposes === undefined) return;\n holdSignIn(hasGrantedConsentPurposes(normalizeConsentPurposes(purposes), [ConsentPurpose.ANALYTICS]) ? { ...held, decided: true } : null);\n });\n }, [on, holdSignIn]);\n\n useEffect(() => {\n return on(FrontendEvents.USER_LOGOUT, (payload) => {\n if (payload.reason === SessionEndReason.SIGNED_OUT && userLifecycleTrackingRef.current) {\n lifecycleTrackRef.current(AnalyticsEventName.USER_LOGOUT);\n }\n holdSignIn(null);\n signedInUserIdRef.current = null;\n providersRef.current.forEach(p => p.reset());\n });\n }, [on, holdSignIn]);\n\n // ─── Achieved moments persistence ─────────────────────────────\n\n const [identity, setIdentity] = useState<AnalyticsIdentity | null>(null);\n const identityOwner = useRef<symbol | null>(null);\n const publishIdentity = useCallback((next: AnalyticsIdentity) => {\n const owner = Symbol();\n identityOwner.current = owner;\n setIdentity(next);\n return () => {\n if (identityOwner.current === owner) { identityOwner.current = null; setIdentity(null); }\n };\n }, []);\n const identityKey = JSON.stringify(identity);\n\n /*\n * Who a running vendor sink attributes events to (#1704): the person the mounted app scope publishes\n * (`publishIdentity`), which is the identity this provider already trusts for value moments. Keyed on the\n * user id and on WHICH sinks run, so a sink started later is identified on its first render, and a person\n * who leaves (identity lost) is forgotten by every sink still running. The published identity rather\n * than `USER_LOGIN` / `USER_LOGOUT` because a sink starts whenever the grant arrives, and the identity\n * is STATE a sink started later can read, where the announcement is a moment it would have missed.\n */\n const identifiedUserId = identity?.userId ?? null;\n useEffect(() => {\n if (vendorSinks.length === 0) return;\n if (identifiedUserId !== null) vendorSinks.forEach(sink => sink.identify({ userId: identifiedUserId }));\n else vendorSinks.forEach(sink => sink.reset());\n }, [vendorSinks, identifiedUserId]);\n const currentIdentityKey = useRef(identityKey);\n currentIdentityKey.current = identityKey;\n const momentProgress = useRef<AnalyticsMomentProgress>({ signals: new Map(), counts: new Map(), lastFired: new Map(), completed: new Set() });\n const userStorageKey = identity?.userId\n ? `${ANALYTICS_ACHIEVED_STORAGE_KEY_PREFIX}${JSON.stringify([identity.applicationId, ValueMomentScope.USER, identity.userId])}` : null;\n const organizationStorageKey = identity?.organizationId\n ? `${ANALYTICS_ACHIEVED_STORAGE_KEY_PREFIX}${JSON.stringify([identity.applicationId, ValueMomentScope.ORGANIZATION, identity.organizationId])}` : null;\n const storageKey = JSON.stringify([userStorageKey, organizationStorageKey]);\n const isOrganizationMoment = useCallback((id: string) =>\n analyticsConfig?.valueMoments?.find(moment => moment.identifier === id)?.scope === ValueMomentScope.ORGANIZATION,\n [analyticsConfig?.valueMoments]);\n const isPersistentMoment = useCallback((id: string) =>\n analyticsConfig?.valueMoments?.find(moment => moment.identifier === id)?.role !== ValueMomentRole.ANTI_PATTERN,\n [analyticsConfig?.valueMoments]);\n\n const [achievementState, setAchievementState] = useState<{key: string; moments: Set<string>}>({key: identityKey, moments: new Set()});\n const achievedMoments = useMemo(() => achievementState.key === identityKey ? achievementState.moments : new Set<string>(), [achievementState, identityKey]);\n const setAchievedMoments = useCallback((update: React.SetStateAction<Set<string>>) => {\n setAchievementState(previous => ({key: identityKey, moments: typeof update === 'function'\n ? update(previous.key === identityKey ? previous.moments : new Set()) : update}));\n }, [identityKey]);\n\n // Helper: persist to localStorage\n const persistToStorage = useCallback((moments: Set<string>) => {\n try {\n if (userStorageKey) localStorage.setItem(userStorageKey, JSON.stringify([...moments].filter(id => !isOrganizationMoment(id))));\n if (organizationStorageKey) localStorage.setItem(organizationStorageKey, JSON.stringify([...moments].filter(isOrganizationMoment)));\n } catch {\n /* quota exceeded — best effort */\n }\n }, [userStorageKey, organizationStorageKey, isOrganizationMoment]);\n\n // Load from localStorage on mount + fetch from backend if backendSync\n useEffect(() => {\n setAchievedMoments(new Set());\n if (!analyticsConfig?.enabled || !identity || (!identity.userId && !identity.organizationId)) return;\n\n // Load from localStorage\n try {\n const loaded = new Set<string>();\n for (const [key, organization] of [[userStorageKey, false], [organizationStorageKey, true]] as const) {\n if (!key) continue;\n const stored = localStorage.getItem(key);\n if (stored) for (const id of JSON.parse(stored) as string[]) {\n if (isPersistentMoment(id) && isOrganizationMoment(id) === organization) loaded.add(id);\n }\n }\n setAchievedMoments(loaded);\n } catch {\n /* corrupt storage — start fresh */\n }\n\n // Fetch from backend if backendSync enabled AND this consumer can reach the route (#1069, the\n // #268 rule): achieved moments are read from the progression store, which a consumer whose\n // registry excludes it does not serve. localStorage still loads above.\n if (analyticsConfig?.persistence?.backendSync && momentsReachable) {\n let aborted = false;\n getManualCallsHttpClient()\n .getAnalyticsMomentsAchieved()\n .then((response: unknown) => {\n if (aborted || currentIdentityKey.current !== identityKey) return;\n const res = response as { moments?: string[] };\n if (res.moments) {\n setAchievedMoments(prev => {\n const merged = new Set([...prev, ...res.moments!].filter(isPersistentMoment));\n persistToStorage(merged);\n return merged;\n });\n }\n })\n .catch(() => {\n /* Backend unavailable — use localStorage only */\n });\n\n return () => { aborted = true; };\n }\n }, [analyticsConfig?.enabled, analyticsConfig?.persistence?.backendSync, momentsReachable, storageKey, identityKey, persistToStorage, isPersistentMoment, isOrganizationMoment]);\n\n // Subscribe to ANALYTICS_MOMENT_ACHIEVED events (backend-pushed via WS)\n useEffect(() => {\n return on(FrontendEvents.ANALYTICS_MOMENT_ACHIEVED, (payload) => {\n if (!identity || payload.triggerSource === AnalyticsTriggerSource.FRONTEND || payload.role === ValueMomentRole.ANTI_PATTERN || !isPersistentMoment(payload.momentIdentifier)) return;\n setAchievedMoments(prev => {\n const next = new Set(prev);\n next.add(payload.momentIdentifier);\n persistToStorage(next);\n return next;\n });\n });\n }, [on, persistToStorage, identityKey, isPersistentMoment]);\n\n const markMomentAchieved = useCallback((identifier: string): boolean | Promise<boolean> => {\n if (!identity || !isPersistentMoment(identifier)) return false;\n const definition = analyticsConfig?.valueMoments?.find(moment => moment.identifier === identifier);\n if (definition?.requires?.some(id => !achievedMoments.has(id)) || definition?.beforeStage?.some(id => achievedMoments.has(id))) return false;\n const record = (): boolean => {\n if (currentIdentityKey.current !== identityKey) return false;\n setAchievedMoments(prev => {\n const next = new Set(prev); next.add(identifier); persistToStorage(next); return next;\n });\n return true;\n };\n if (!analyticsConfig?.persistence?.backendSync) return record();\n // A refused report is not an achievement. Network failures retain the documented best-effort\n // local behavior; explicit server refusals must never be merged back as local truth.\n return getManualCallsHttpClient().postAnalyticsMomentsAchieved({ momentIdentifier: identifier, scope: definition?.scope })\n .then(result => result.success === false ? false : record())\n .catch((error: unknown) => {\n const response = error as {httpStatus?: number; response?: {status?: number}};\n const status = response?.httpStatus ?? response?.response?.status;\n return status && status >= 400 && status < 500 ? false : record();\n });\n }, [analyticsConfig, persistToStorage, identityKey, isPersistentMoment, achievedMoments]);\n\n // ─── Track interceptor ref ────────────────────────────────────\n\n const onTrackRef = useRef<((name: string, properties?: Record<string, unknown>) => void) | null>(null);\n\n const track = useCallback((name: string, properties?: Record<string, unknown>) => {\n if (!isDispatching) return;\n const event: AnalyticsEvent = { name, properties, timestamp: Date.now() };\n if (isActive) providersRef.current.forEach(p => p.track(event));\n // An event about a write to the person's own preferences waits for the consent that write leaves (see the hold).\n if (name === AnalyticsEventName.RESOURCE_OPERATION && properties?.resourceType === CoreResourceType.USER_SELF_PREFERENCES) openVendorHold();\n const toVendors = (): void => vendorSinks.forEach(sink => sink.track({ name, properties }));\n if (vendorHoldRef.current) vendorHoldRef.current.held.push(toVendors);\n else toVendors();\n // Forward to bridge interceptor for CUSTOM_EVENT / FEATURE_ACCESS signal evaluation\n onTrackRef.current?.(name, properties);\n }, [isActive, isDispatching, vendorSinks, openVendorHold]);\n lifecycleTrackRef.current = track;\n\n // Deliver a decided sign-in to each kind of destination as that kind starts — see the block above.\n useEffect(() => {\n const held = heldSignInRef.current;\n if (held === null || !held.decided || !userLifecycleTracking) return;\n const event: AnalyticsEvent = { name: AnalyticsEventName.USER_LOGIN, timestamp: held.occurredAt };\n let owedToBuiltIns = held.owedToBuiltIns;\n let owedToVendorSinks = held.owedToVendorSinks;\n if (owedToBuiltIns && isActive && providersRef.current.length > 0) {\n providersRef.current.forEach(p => p.track(event));\n owedToBuiltIns = false;\n }\n if (owedToVendorSinks && vendorSinks.length > 0) {\n // A vendor sink's `track` takes no timestamp — the vendor stamps receipt — so when the sign-in\n // happened travels as a property, and the vendor-side time may be later than the sign-in.\n vendorSinks.forEach(sink => sink.track({ name: event.name, properties: { [SIGNED_IN_AT_PROPERTY]: new Date(held.occurredAt).toISOString() } }));\n owedToVendorSinks = false;\n }\n if (owedToBuiltIns !== held.owedToBuiltIns || owedToVendorSinks !== held.owedToVendorSinks) {\n heldSignInRef.current = owedToBuiltIns || owedToVendorSinks ? { ...held, owedToBuiltIns, owedToVendorSinks } : null;\n }\n }, [heldSignInVersion, builtInsStartedVersion, isActive, vendorSinks, userLifecycleTracking]);\n\n const page = useCallback((path: string, properties?: Record<string, unknown>) => {\n if (!isDispatching) return;\n if (isActive) providersRef.current.forEach(p => p.page(path, properties));\n const toVendors = (): void => vendorSinks.forEach(sink => sink.page(path, properties));\n if (vendorHoldRef.current) vendorHoldRef.current.held.push(toVendors);\n else toVendors();\n }, [isActive, isDispatching, vendorSinks]);\n\n // ─── Render ───────────────────────────────────────────────────\n\n const contextValue = useMemo<AnalyticsContextValue>(() => ({\n track,\n page,\n isActive: isDispatching,\n sessionStartTimestamp,\n achievedMoments,\n markMomentAchieved,\n _onTrackRef: onTrackRef,\n }), [track, page, isDispatching, sessionStartTimestamp, achievedMoments, markMomentAchieved]);\n\n return (\n <AnalyticsIdentityPublisherContext.Provider value={publishIdentity}>\n <AnalyticsContext.Provider value={contextValue}>\n {isDispatching && identity && analyticsConfig && (\n <AnalyticsEventBridge\n key={`${identityKey}:${JSON.stringify(analyticsConfig.valueMoments)}`}\n identity={identity}\n progress={momentProgress.current}\n config={analyticsConfig.autoInstrumentation}\n valueMoments={analyticsConfig.valueMoments} \n />\n )}\n {children}\n </AnalyticsContext.Provider>\n </AnalyticsIdentityPublisherContext.Provider>\n );\n};\n"]}
@@ -161,7 +161,12 @@ export declare class ResourceReadCacheFrontendService {
161
161
  * without sorting the second phrasing of one question would always miss. Arrays keep their order,
162
162
  * because in a filter or a sort an array's order is part of the question.
163
163
  *
164
- * Returns `null` for anything that cannot be rendered — a cycle, a `BigInt`, a function in a filter —
164
+ * A `Date` renders as its instant. It has no own enumerable keys, so walked as a plain object it was `{}`, and every
165
+ * date window was one key: a calendar or timeline moving to another month was served the first month's rows from
166
+ * this cache, with no request (#3931). Any other object that is not a plain object or an array (a `Set`, a `Map`, a
167
+ * class instance) carries its identity somewhere its own keys do not, so it is refused rather than rendered as `{}`.
168
+ *
169
+ * Returns `null` for anything that cannot be rendered — a cycle, a `BigInt`, a function in a filter, such an object —
165
170
  * which every caller reads as "do not cache this", never as an error.
166
171
  */
167
172
  export declare function renderResourceReadCacheKey(operationPathKey: string, parameters: unknown): string | null;
@@ -1 +1 @@
1
- {"version":3,"file":"resource-read-cache.frontend.service.d.ts","sourceRoot":"","sources":["../../../../src/core/resources/resource-read-cache.frontend.service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAiBxE;;;;;;;;;GASG;AACH,MAAM,WAAW,6BAA6B;IAC5C;;;;;;OAMG;IACH,MAAM,CAAC,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,0BAA0B,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;;;;;;;;;GASG;AACH,wBAAgB,0BAA0B,CACxC,gBAAgB,EAAE,MAAM,EACxB,UAAU,EAAE,OAAO,GAClB,MAAM,GAAG,IAAI,CAuBf"}
1
+ {"version":3,"file":"resource-read-cache.frontend.service.d.ts","sourceRoot":"","sources":["../../../../src/core/resources/resource-read-cache.frontend.service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAiBxE;;;;;;;;;GASG;AACH,MAAM,WAAW,6BAA6B;IAC5C;;;;;;OAMG;IACH,MAAM,CAAC,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,0BAA0B,EAAE,GAAG,OAAO,CAAC;IAErF;;;OAGG;IACH,eAAe,CAAC,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,0BAA0B,EAAE,GAAG,IAAI,CAAC;CAC5F;AAUD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,qBAAa,gCAAgC;IAC3C,OAAO,CAAC,aAAa,CAAuB;IAC5C,OAAO,CAAC,cAAc,CAAuB;IAE7C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAiC;IACzD,OAAO,CAAC,SAAS,CAA8C;IAC/D,OAAO,CAAC,OAAO,CAAQ;IAEvB;;;;;;OAMG;IACH;;;;;;;;;;;;;OAaG;IACI,gBAAgB,CAAC,aAAa,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI;IAIpD,gBAAgB,IAAI,MAAM,GAAG,IAAI;IAIxC;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACI,iBAAiB,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI;IAItD,iBAAiB,IAAI,MAAM,GAAG,IAAI;IAIlC,oBAAoB,CAAC,SAAS,EAAE,6BAA6B,GAAG,IAAI,GAAG,IAAI;IAMlF;;;;;;;;;;;;OAYG;IACI,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI;IAKzC,IAAW,IAAI,IAAI,MAAM,CAExB;IAED;;;;;;OAMG;IACI,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,GAAG,SAAS;IAiB7C,sEAAsE;IAC/D,KAAK,CACV,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,OAAO,EACd,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,SAAS,0BAA0B,EAAE,GAC5C,IAAI;IAcP;;;;;;OAMG;IACI,sBAAsB,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI;IAWzD;;;;;;OAMG;IACI,KAAK,IAAI,IAAI;IAMpB,6EAA6E;IAC7E,OAAO,CAAC,mBAAmB;CAY5B;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,0BAA0B,CACxC,gBAAgB,EAAE,MAAM,EACxB,UAAU,EAAE,OAAO,GAClB,MAAM,GAAG,IAAI,CA0Bf"}
@@ -221,7 +221,12 @@ export class ResourceReadCacheFrontendService {
221
221
  * without sorting the second phrasing of one question would always miss. Arrays keep their order,
222
222
  * because in a filter or a sort an array's order is part of the question.
223
223
  *
224
- * Returns `null` for anything that cannot be rendered — a cycle, a `BigInt`, a function in a filter —
224
+ * A `Date` renders as its instant. It has no own enumerable keys, so walked as a plain object it was `{}`, and every
225
+ * date window was one key: a calendar or timeline moving to another month was served the first month's rows from
226
+ * this cache, with no request (#3931). Any other object that is not a plain object or an array (a `Set`, a `Map`, a
227
+ * class instance) carries its identity somewhere its own keys do not, so it is refused rather than rendered as `{}`.
228
+ *
229
+ * Returns `null` for anything that cannot be rendered — a cycle, a `BigInt`, a function in a filter, such an object —
225
230
  * which every caller reads as "do not cache this", never as an error.
226
231
  */
227
232
  export function renderResourceReadCacheKey(operationPathKey, parameters) {
@@ -237,11 +242,16 @@ export function renderResourceReadCacheKey(operationPathKey, parameters) {
237
242
  throw new Error('not renderable');
238
243
  if (typeof value !== 'object')
239
244
  return JSON.stringify(value) ?? 'u';
245
+ if (value instanceof Date)
246
+ return `D${value.getTime()}`;
240
247
  if (seen.has(value))
241
248
  throw new Error('not renderable');
242
249
  seen.add(value);
243
250
  if (Array.isArray(value))
244
251
  return `[${value.map(render).join(',')}]`;
252
+ const prototype = Object.getPrototypeOf(value);
253
+ if (prototype !== Object.prototype && prototype !== null)
254
+ throw new Error('not renderable');
245
255
  const entries = Object.entries(value)
246
256
  .filter(([, entryValue]) => entryValue !== undefined)
247
257
  .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
@@ -1 +1 @@
1
- {"version":3,"file":"resource-read-cache.frontend.service.js","sourceRoot":"","sources":["../../../../src/core/resources/resource-read-cache.frontend.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,6DAA6D,CAAC;AAEpG,MAAM,MAAM,GAAG,qBAAqB,CAAC,SAAS,EAAE,CAAC;AACjD,MAAM,QAAQ,GAAG,MAAM,CAAC,WAAW,CAAC,mBAAmB,CAAC,CAAC;AACzD,MAAM,CAAC,mBAAmB,CAAC,mBAAmB,EAAE,KAAK,CAAC,CAAC;AAEvD;;;;;;;GAOG;AACH,MAAM,oBAAoB,GAAG,GAAG,CAAC;AAqCjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAM,OAAO,gCAAgC;IACnC,aAAa,GAAkB,IAAI,CAAC;IACpC,cAAc,GAAkB,IAAI,CAAC;IAE5B,OAAO,GAAG,IAAI,GAAG,EAAsB,CAAC;IACjD,SAAS,GAAyC,IAAI,CAAC;IACvD,OAAO,GAAG,IAAI,CAAC;IAEvB;;;;;;OAMG;IACH;;;;;;;;;;;;;OAaG;IACI,gBAAgB,CAAC,aAA4B;QAClD,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACrC,CAAC;IAEM,gBAAgB;QACrB,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACI,iBAAiB,CAAC,cAA6B;QACpD,IAAI,CAAC,cAAc,GAAG,c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GAAG,CAAC,KAAe,CAAC,CAAC;QAC1B,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;YAAE,OAAO,IAAI,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;QACpE,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,KAAgC,CAAC;aAC7D,MAAM,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC,UAAU,KAAK,SAAS,CAAC;aACpD,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACzE,OAAO,IAAI,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;IAC7G,CAAC,CAAC;IAEF,IAAI,CAAC;QACH,OAAO,GAAG,gBAAgB,IAAI,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC;IACrD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import type { ResourceScopeRoomQualifier } from '@wildo-ai/saas-models';\nimport { LoggerFrontendService } from '~wildo-frontend-lib/core/monitoring/logger.frontend.service';\n\nconst logger = LoggerFrontendService.getLogger();\nconst logDebug = logger.debugByType('ResourceReadCache');\nlogger.setDebugTypeLogging('ResourceReadCache', false);\n\n/**\n * A ceiling on how many read results are held.\n *\n * Not a memory bound so much as a staleness bound: every entry is one more thing that has to be\n * invalidated correctly, and an unbounded map makes a missed invalidation permanent. 200 is the same\n * order as `RMM_REGISTRY_MAX_INSTANCES`, and eviction is least-recently-USED so an entry a surface\n * keeps reading survives while a page visited once does not.\n */\nconst MAXIMUM_CACHED_READS = 200;\n\n/**\n * Whether a cached read is currently covered by something that would tell us it went stale.\n *\n * This is the whole safety contract. A cached read may be SERVED only while an authority reports\n * that every room an invalidation for it would arrive through is joined — so a cache entry can never\n * outlive the subscription that keeps it honest.\n *\n * Implemented by the WebSocket layer. Absent — no provider mounted, socket down, subscription\n * refused — nothing is ever served from cache, and the tier degrades to exactly today's behaviour.\n */\nexport interface ResourceReadCoverageAuthority {\n /**\n * Whether an invalidation for this resource in these scopes would currently reach us.\n *\n * Must answer `false` when the transport is down, when any required room is not joined, and when\n * the scope set is EMPTY — a read that belongs to no room has no channel through which it could\n * ever be told it is stale, so it is not cacheable at all.\n */\n covers(resourceType: string, scopes: readonly ResourceScopeRoomQualifier[]): boolean;\n\n /**\n * Asked to start covering a resource in these scopes. Best-effort and asynchronous: the entry it\n * was requested for is not servable until a later `covers` returns `true`.\n */\n requestCoverage(resourceType: string, scopes: readonly ResourceScopeRoomQualifier[]): void;\n}\n\ninterface CachedRead {\n readonly value: unknown;\n readonly resourceType: string;\n readonly scopes: readonly ResourceScopeRoomQualifier[];\n readonly storedAt: number;\n lastReadAt: number;\n}\n\n/**\n * Holds resource READ results between navigations, so a surface that was visited before does not\n * re-fetch what nothing has changed.\n *\n * ## The problem, measured rather than assumed\n *\n * There is no cross-time read cache anywhere in the frontend today — `WildoBackendHttpClient` says\n * so at its in-flight map: *\"IN-FLIGHT sharing only … There is NO cross-time cache / TTL\"*. That\n * same comment records the cost: **one resource-detail mount fires ~9 GETs from 7 independent\n * consumers**, and navigating away and back pays all of them again.\n *\n * ## Why an entry is not servable unless something is watching it\n *\n * The obvious cache — store the response, serve it next time, invalidate on a WebSocket event — has\n * a hole that is silent rather than noisy. Resource events are delivered to ROOMS, and rooms are\n * joined by subscription. An entry whose room nobody has joined receives no invalidation, so it is\n * served confidently forever. Nothing errors, nothing retries; the data is simply wrong.\n *\n * So this tier inverts the default: a stored entry is a candidate, and only a\n * {@link ResourceReadCoverageAuthority} reporting live coverage makes it servable. With no authority\n * the tier stores and serves nothing, which is exactly today's behaviour — slow and correct.\n *\n * ## What it deliberately does NOT do\n *\n * - **No TTL.** A time bound would be a guess about how stale is acceptable, and it would let an\n * uncovered entry be served for the length of the guess. Coverage is a fact; a TTL is a hope.\n * - **No stale-while-revalidate.** Serving a known-stale value while refetching is a reasonable\n * pattern elsewhere; here it would silently reintroduce the wrong-data path this design exists to\n * close, and it cannot satisfy \"a repeat navigation issues no request\" anyway.\n * - **No mutation caching.** Only read-family operations are ever stored.\n */\nexport class ResourceReadCacheFrontendService {\n private applicationId: string | null = null;\n private organizationId: string | null = null;\n\n private readonly entries = new Map<string, CachedRead>();\n private authority: ResourceReadCoverageAuthority | null = null;\n private enabled = true;\n\n /**\n * Install the coverage authority. Called by the WebSocket layer once it can answer.\n *\n * Replacing an authority CLEARS the cache: the new one knows nothing about what the old one was\n * covering, so every held entry is of unknown freshness. Clearing costs a refetch and cannot be\n * wrong, which is the direction this tier always errs in.\n */\n /**\n * The application this session is reading, for the one scope an APPLICATION-scoped resource has.\n *\n * `deriveResourceScopeRoomQualifiers` yields the `app` room only when `applicationId` is present in\n * the context it is handed, and a read's context is built from the URL's contextual parameters —\n * which never carry one, because an application id is ambient rather than addressed. So without\n * this, an APPLICATION-scoped resource derives whatever incidental `org`/`user` rooms its\n * parameters imply and never its own, and a push addressed to `app` reaches nobody (issue #283,\n * measured: 0 frames on a surface whose companion had just published to it).\n *\n * Set by `ResourceReadCacheBridge`, which is a component and can read the app scope; the service is\n * plain and cannot. Null until it does, which is correct — before the scope is mounted there is no\n * application to name.\n */\n public setApplicationId(applicationId: string | null): void {\n this.applicationId = applicationId;\n }\n\n public getApplicationId(): string | null {\n return this.applicationId;\n }\n\n /**\n * The ambient ORGANIZATION id, for the window in which the route has not published one yet.\n *\n * The sibling above exists because an application id is NEVER addressed. This one exists for the\n * opposite reason: an organization id usually IS — `/organizations/:organizationId/...` — and the\n * gap is purely temporal. A read issued before the organization scope hydrates carries no\n * `organizationId` in its contextual parameters, so `deriveResourceScopeRoomQualifiers` emits only\n * the incidental `user` room the generic loop produces and never the resource's own `org` room.\n *\n * That entry is still STORED, because `store()` refuses only an EMPTY scope set — so it is served\n * from a room that no org-scoped invalidation is addressed to. A change another member of the same\n * tenant makes cannot reach it, and `covers()` keeps reporting it servable. Measured as a test\n * failure first (`browser-read-cache`, #1137: the client subscribed `resource:todos:user:<user>`\n * and never `resource:todos:org:<org>`), but the stale read is the part that matters.\n *\n * Refusing to cache instead was REJECTED, and not on taste: the same choice was made for\n * APPLICATION scope and recorded there as \"strictly worse… disabled the tier in exchange for\n * nothing\". Supplying the id the resource is scoped by keeps the tier on AND makes the entry\n * invalidatable, which refusing does not.\n *\n * Set by `ResourceReadCacheBridge`, which is a component and can read the app scope; the service is\n * plain and cannot. Null until it does.\n */\n public setOrganizationId(organizationId: string | null): void {\n this.organizationId = organizationId;\n }\n\n public getOrganizationId(): string | null {\n return this.organizationId;\n }\n\n public setCoverageAuthority(authority: ResourceReadCoverageAuthority | null): void {\n this.authority = authority;\n this.entries.clear();\n logDebug('coverage authority changed', { hasAuthority: authority !== null });\n }\n\n /**\n * Turn the tier off entirely.\n *\n * A door rather than a design. The blast radius here is every generated application on every\n * persistence adapter, so an operator who suspects the cache must be able to remove it from the\n * picture without a rebuild.\n *\n * **The handle is `VITE_RESOURCE_READ_CACHE=off`**, applied by `ResourceReadCacheBridge` — mirroring\n * `COMPANION_INTROSPECTION_CACHE=off` on the companion side, same word and same value so an\n * operator who has met one knows the other. Said explicitly because a door with no handle is worse\n * than no door: this method existed for a while with only a test calling it, while this comment\n * claimed an operator could reach it.\n */\n public setEnabled(enabled: boolean): void {\n this.enabled = enabled;\n if (!enabled) this.entries.clear();\n }\n\n public get size(): number {\n return this.entries.size;\n }\n\n /**\n * The cached value for a read, or `undefined` when there is none that may be served.\n *\n * Coverage is re-checked on every read rather than recorded at store time, because coverage is a\n * property of NOW: a socket that dropped since the entry was stored must stop the entry being\n * served, and only asking at read time can see that.\n */\n public read(key: string): unknown | undefined {\n if (!this.enabled) return undefined;\n const entry = this.entries.get(key);\n if (!entry) return undefined;\n\n if (!this.authority?.covers(entry.resourceType, entry.scopes)) {\n // Not an error and not necessarily stale — simply unprovable. Dropping it keeps the map from\n // filling with entries that can never be served.\n this.entries.delete(key);\n logDebug('entry dropped: no live coverage', { resourceType: entry.resourceType });\n return undefined;\n }\n\n entry.lastReadAt = Date.now();\n return entry.value;\n }\n\n /** Store a read result and ask the authority to start covering it. */\n public store(\n key: string,\n value: unknown,\n resourceType: string,\n scopes: readonly ResourceScopeRoomQualifier[],\n ): void {\n if (!this.enabled || !this.authority) return;\n // A read belonging to no scope has no room through which an invalidation could arrive. Storing\n // it would create an entry that can never be proven fresh — so it is refused at the door rather\n // than kept and never served.\n if (scopes.length === 0) return;\n\n this.authority.requestCoverage(resourceType, scopes);\n\n const now = Date.now();\n this.entries.set(key, { value, resourceType, scopes, storedAt: now, lastReadAt: now });\n this.evictIfOverCapacity();\n }\n\n /**\n * Drop every entry for a resource type.\n *\n * The invalidation the WebSocket layer calls. Deliberately coarse — per-row invalidation would\n * have to know which cached LISTS contain that row, which is a question the cache cannot answer\n * without parsing every stored payload against a shape it does not own.\n */\n public invalidateResourceType(resourceType: string): void {\n let dropped = 0;\n for (const [key, entry] of this.entries) {\n if (entry.resourceType === resourceType) {\n this.entries.delete(key);\n dropped += 1;\n }\n }\n if (dropped > 0) logDebug('invalidated by resource type', { resourceType, dropped });\n }\n\n /**\n * Drop everything.\n *\n * Called on the two transitions that change WHICH rows a read would return without changing the\n * request: an organization switch and a session change. Both happen without a page reload, so\n * nothing else would clear this.\n */\n public clear(): void {\n const dropped = this.entries.size;\n this.entries.clear();\n if (dropped > 0) logDebug('cleared', { dropped });\n }\n\n /** Least-recently-READ eviction, so a surface being used keeps its entry. */\n private evictIfOverCapacity(): void {\n if (this.entries.size <= MAXIMUM_CACHED_READS) return;\n let oldestKey: string | undefined;\n let oldestAt = Number.POSITIVE_INFINITY;\n for (const [key, entry] of this.entries) {\n if (entry.lastReadAt < oldestAt) {\n oldestAt = entry.lastReadAt;\n oldestKey = key;\n }\n }\n if (oldestKey !== undefined) this.entries.delete(oldestKey);\n }\n}\n\n/**\n * Render a read's identity so two structurally equal requests produce one key.\n *\n * Object keys are sorted at every depth: `{a:1,b:2}` and `{b:2,a:1}` are the same request, and\n * without sorting the second phrasing of one question would always miss. Arrays keep their order,\n * because in a filter or a sort an array's order is part of the question.\n *\n * Returns `null` for anything that cannot be rendered — a cycle, a `BigInt`, a function in a filter —\n * which every caller reads as \"do not cache this\", never as an error.\n */\nexport function renderResourceReadCacheKey(\n operationPathKey: string,\n parameters: unknown,\n): string | null {\n const seen = new WeakSet<object>();\n\n const render = (value: unknown): string => {\n if (value === undefined) return 'u';\n if (value === null) return 'n';\n if (typeof value === 'function') throw new Error('not renderable');\n if (typeof value === 'bigint') throw new Error('not renderable');\n if (typeof value !== 'object') return JSON.stringify(value) ?? 'u';\n if (seen.has(value as object)) throw new Error('not renderable');\n seen.add(value as object);\n if (Array.isArray(value)) return `[${value.map(render).join(',')}]`;\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, entryValue]) => entryValue !== undefined)\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n return `{${entries.map(([key, entryValue]) => `${JSON.stringify(key)}:${render(entryValue)}`).join(',')}}`;\n };\n\n try {\n return `${operationPathKey}\u0001${render(parameters)}`;\n } catch {\n return null;\n }\n}\n"]}
1
+ {"version":3,"file":"resource-read-cache.frontend.service.js","sourceRoot":"","sources":["../../../../src/core/resources/resource-read-cache.frontend.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,6DAA6D,CAAC;AAEpG,MAAM,MAAM,GA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,MAAM,CAAC,OAAO,CAAC,KAAgC,CAAC;aAC7D,MAAM,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC,UAAU,KAAK,SAAS,CAAC;aACpD,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACzE,OAAO,IAAI,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;IAC7G,CAAC,CAAC;IAEF,IAAI,CAAC;QACH,OAAO,GAAG,gBAAgB,IAAI,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC;IACrD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import type { ResourceScopeRoomQualifier } from '@wildo-ai/saas-models';\nimport { LoggerFrontendService } from '~wildo-frontend-lib/core/monitoring/logger.frontend.service';\n\nconst logger = LoggerFrontendService.getLogger();\nconst logDebug = logger.debugByType('ResourceReadCache');\nlogger.setDebugTypeLogging('ResourceReadCache', false);\n\n/**\n * A ceiling on how many read results are held.\n *\n * Not a memory bound so much as a staleness bound: every entry is one more thing that has to be\n * invalidated correctly, and an unbounded map makes a missed invalidation permanent. 200 is the same\n * order as `RMM_REGISTRY_MAX_INSTANCES`, and eviction is least-recently-USED so an entry a surface\n * keeps reading survives while a page visited once does not.\n */\nconst MAXIMUM_CACHED_READS = 200;\n\n/**\n * Whether a cached read is currently covered by something that would tell us it went stale.\n *\n * This is the whole safety contract. A cached read may be SERVED only while an authority reports\n * that every room an invalidation for it would arrive through is joined — so a cache entry can never\n * outlive the subscription that keeps it honest.\n *\n * Implemented by the WebSocket layer. Absent — no provider mounted, socket down, subscription\n * refused — nothing is ever served from cache, and the tier degrades to exactly today's behaviour.\n */\nexport interface ResourceReadCoverageAuthority {\n /**\n * Whether an invalidation for this resource in these scopes would currently reach us.\n *\n * Must answer `false` when the transport is down, when any required room is not joined, and when\n * the scope set is EMPTY — a read that belongs to no room has no channel through which it could\n * ever be told it is stale, so it is not cacheable at all.\n */\n covers(resourceType: string, scopes: readonly ResourceScopeRoomQualifier[]): boolean;\n\n /**\n * Asked to start covering a resource in these scopes. Best-effort and asynchronous: the entry it\n * was requested for is not servable until a later `covers` returns `true`.\n */\n requestCoverage(resourceType: string, scopes: readonly ResourceScopeRoomQualifier[]): void;\n}\n\ninterface CachedRead {\n readonly value: unknown;\n readonly resourceType: string;\n readonly scopes: readonly ResourceScopeRoomQualifier[];\n readonly storedAt: number;\n lastReadAt: number;\n}\n\n/**\n * Holds resource READ results between navigations, so a surface that was visited before does not\n * re-fetch what nothing has changed.\n *\n * ## The problem, measured rather than assumed\n *\n * There is no cross-time read cache anywhere in the frontend today — `WildoBackendHttpClient` says\n * so at its in-flight map: *\"IN-FLIGHT sharing only … There is NO cross-time cache / TTL\"*. That\n * same comment records the cost: **one resource-detail mount fires ~9 GETs from 7 independent\n * consumers**, and navigating away and back pays all of them again.\n *\n * ## Why an entry is not servable unless something is watching it\n *\n * The obvious cache — store the response, serve it next time, invalidate on a WebSocket event — has\n * a hole that is silent rather than noisy. Resource events are delivered to ROOMS, and rooms are\n * joined by subscription. An entry whose room nobody has joined receives no invalidation, so it is\n * served confidently forever. Nothing errors, nothing retries; the data is simply wrong.\n *\n * So this tier inverts the default: a stored entry is a candidate, and only a\n * {@link ResourceReadCoverageAuthority} reporting live coverage makes it servable. With no authority\n * the tier stores and serves nothing, which is exactly today's behaviour — slow and correct.\n *\n * ## What it deliberately does NOT do\n *\n * - **No TTL.** A time bound would be a guess about how stale is acceptable, and it would let an\n * uncovered entry be served for the length of the guess. Coverage is a fact; a TTL is a hope.\n * - **No stale-while-revalidate.** Serving a known-stale value while refetching is a reasonable\n * pattern elsewhere; here it would silently reintroduce the wrong-data path this design exists to\n * close, and it cannot satisfy \"a repeat navigation issues no request\" anyway.\n * - **No mutation caching.** Only read-family operations are ever stored.\n */\nexport class ResourceReadCacheFrontendService {\n private applicationId: string | null = null;\n private organizationId: string | null = null;\n\n private readonly entries = new Map<string, CachedRead>();\n private authority: ResourceReadCoverageAuthority | null = null;\n private enabled = true;\n\n /**\n * Install the coverage authority. Called by the WebSocket layer once it can answer.\n *\n * Replacing an authority CLEARS the cache: the new one knows nothing about what the old one was\n * covering, so every held entry is of unknown freshness. Clearing costs a refetch and cannot be\n * wrong, which is the direction this tier always errs in.\n */\n /**\n * The application this session is reading, for the one scope an APPLICATION-scoped resource has.\n *\n * `deriveResourceScopeRoomQualifiers` yields the `app` room only when `applicationId` is present in\n * the context it is handed, and a read's context is built from the URL's contextual parameters —\n * which never carry one, because an application id is ambient rather than addressed. So without\n * this, an APPLICATION-scoped resource derives whatever incidental `org`/`user` rooms its\n * parameters imply and never its own, and a push addressed to `app` reaches nobody (issue #283,\n * measured: 0 frames on a surface whose companion had just published to it).\n *\n * Set by `ResourceReadCacheBridge`, which is a component and can read the app scope; the service is\n * plain and cannot. Null until it does, which is correct — before the scope is mounted there is no\n * application to name.\n */\n public setApplicationId(applicationId: string | null): void {\n this.applicationId = applicationId;\n }\n\n public getApplicationId(): string | null {\n return this.applicationId;\n }\n\n /**\n * The ambient ORGANIZATION id, for the window in which the route has not published one yet.\n *\n * The sibling above exists because an application id is NEVER addressed. This one exists for the\n * opposite reason: an organization id usually IS — `/organizations/:organizationId/...` — and the\n * gap is purely temporal. A read issued before the organization scope hydrates carries no\n * `organizationId` in its contextual parameters, so `deriveResourceScopeRoomQualifiers` emits only\n * the incidental `user` room the generic loop produces and never the resource's own `org` room.\n *\n * That entry is still STORED, because `store()` refuses only an EMPTY scope set — so it is served\n * from a room that no org-scoped invalidation is addressed to. A change another member of the same\n * tenant makes cannot reach it, and `covers()` keeps reporting it servable. Measured as a test\n * failure first (`browser-read-cache`, #1137: the client subscribed `resource:todos:user:<user>`\n * and never `resource:todos:org:<org>`), but the stale read is the part that matters.\n *\n * Refusing to cache instead was REJECTED, and not on taste: the same choice was made for\n * APPLICATION scope and recorded there as \"strictly worse… disabled the tier in exchange for\n * nothing\". Supplying the id the resource is scoped by keeps the tier on AND makes the entry\n * invalidatable, which refusing does not.\n *\n * Set by `ResourceReadCacheBridge`, which is a component and can read the app scope; the service is\n * plain and cannot. Null until it does.\n */\n public setOrganizationId(organizationId: string | null): void {\n this.organizationId = organizationId;\n }\n\n public getOrganizationId(): string | null {\n return this.organizationId;\n }\n\n public setCoverageAuthority(authority: ResourceReadCoverageAuthority | null): void {\n this.authority = authority;\n this.entries.clear();\n logDebug('coverage authority changed', { hasAuthority: authority !== null });\n }\n\n /**\n * Turn the tier off entirely.\n *\n * A door rather than a design. The blast radius here is every generated application on every\n * persistence adapter, so an operator who suspects the cache must be able to remove it from the\n * picture without a rebuild.\n *\n * **The handle is `VITE_RESOURCE_READ_CACHE=off`**, applied by `ResourceReadCacheBridge` — mirroring\n * `COMPANION_INTROSPECTION_CACHE=off` on the companion side, same word and same value so an\n * operator who has met one knows the other. Said explicitly because a door with no handle is worse\n * than no door: this method existed for a while with only a test calling it, while this comment\n * claimed an operator could reach it.\n */\n public setEnabled(enabled: boolean): void {\n this.enabled = enabled;\n if (!enabled) this.entries.clear();\n }\n\n public get size(): number {\n return this.entries.size;\n }\n\n /**\n * The cached value for a read, or `undefined` when there is none that may be served.\n *\n * Coverage is re-checked on every read rather than recorded at store time, because coverage is a\n * property of NOW: a socket that dropped since the entry was stored must stop the entry being\n * served, and only asking at read time can see that.\n */\n public read(key: string): unknown | undefined {\n if (!this.enabled) return undefined;\n const entry = this.entries.get(key);\n if (!entry) return undefined;\n\n if (!this.authority?.covers(entry.resourceType, entry.scopes)) {\n // Not an error and not necessarily stale — simply unprovable. Dropping it keeps the map from\n // filling with entries that can never be served.\n this.entries.delete(key);\n logDebug('entry dropped: no live coverage', { resourceType: entry.resourceType });\n return undefined;\n }\n\n entry.lastReadAt = Date.now();\n return entry.value;\n }\n\n /** Store a read result and ask the authority to start covering it. */\n public store(\n key: string,\n value: unknown,\n resourceType: string,\n scopes: readonly ResourceScopeRoomQualifier[],\n ): void {\n if (!this.enabled || !this.authority) return;\n // A read belonging to no scope has no room through which an invalidation could arrive. Storing\n // it would create an entry that can never be proven fresh — so it is refused at the door rather\n // than kept and never served.\n if (scopes.length === 0) return;\n\n this.authority.requestCoverage(resourceType, scopes);\n\n const now = Date.now();\n this.entries.set(key, { value, resourceType, scopes, storedAt: now, lastReadAt: now });\n this.evictIfOverCapacity();\n }\n\n /**\n * Drop every entry for a resource type.\n *\n * The invalidation the WebSocket layer calls. Deliberately coarse — per-row invalidation would\n * have to know which cached LISTS contain that row, which is a question the cache cannot answer\n * without parsing every stored payload against a shape it does not own.\n */\n public invalidateResourceType(resourceType: string): void {\n let dropped = 0;\n for (const [key, entry] of this.entries) {\n if (entry.resourceType === resourceType) {\n this.entries.delete(key);\n dropped += 1;\n }\n }\n if (dropped > 0) logDebug('invalidated by resource type', { resourceType, dropped });\n }\n\n /**\n * Drop everything.\n *\n * Called on the two transitions that change WHICH rows a read would return without changing the\n * request: an organization switch and a session change. Both happen without a page reload, so\n * nothing else would clear this.\n */\n public clear(): void {\n const dropped = this.entries.size;\n this.entries.clear();\n if (dropped > 0) logDebug('cleared', { dropped });\n }\n\n /** Least-recently-READ eviction, so a surface being used keeps its entry. */\n private evictIfOverCapacity(): void {\n if (this.entries.size <= MAXIMUM_CACHED_READS) return;\n let oldestKey: string | undefined;\n let oldestAt = Number.POSITIVE_INFINITY;\n for (const [key, entry] of this.entries) {\n if (entry.lastReadAt < oldestAt) {\n oldestAt = entry.lastReadAt;\n oldestKey = key;\n }\n }\n if (oldestKey !== undefined) this.entries.delete(oldestKey);\n }\n}\n\n/**\n * Render a read's identity so two structurally equal requests produce one key.\n *\n * Object keys are sorted at every depth: `{a:1,b:2}` and `{b:2,a:1}` are the same request, and\n * without sorting the second phrasing of one question would always miss. Arrays keep their order,\n * because in a filter or a sort an array's order is part of the question.\n *\n * A `Date` renders as its instant. It has no own enumerable keys, so walked as a plain object it was `{}`, and every\n * date window was one key: a calendar or timeline moving to another month was served the first month's rows from\n * this cache, with no request (#3931). Any other object that is not a plain object or an array (a `Set`, a `Map`, a\n * class instance) carries its identity somewhere its own keys do not, so it is refused rather than rendered as `{}`.\n *\n * Returns `null` for anything that cannot be rendered — a cycle, a `BigInt`, a function in a filter, such an object —\n * which every caller reads as \"do not cache this\", never as an error.\n */\nexport function renderResourceReadCacheKey(\n operationPathKey: string,\n parameters: unknown,\n): string | null {\n const seen = new WeakSet<object>();\n\n const render = (value: unknown): string => {\n if (value === undefined) return 'u';\n if (value === null) return 'n';\n if (typeof value === 'function') throw new Error('not renderable');\n if (typeof value === 'bigint') throw new Error('not renderable');\n if (typeof value !== 'object') return JSON.stringify(value) ?? 'u';\n if (value instanceof Date) return `D${value.getTime()}`;\n if (seen.has(value as object)) throw new Error('not renderable');\n seen.add(value as object);\n if (Array.isArray(value)) return `[${value.map(render).join(',')}]`;\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) throw new Error('not renderable');\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, entryValue]) => entryValue !== undefined)\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n return `{${entries.map(([key, entryValue]) => `${JSON.stringify(key)}:${render(entryValue)}`).join(',')}}`;\n };\n\n try {\n return `${operationPathKey}\u0001${render(parameters)}`;\n } catch {\n return null;\n }\n}\n"]}
@@ -107,5 +107,5 @@ export interface ApplicationMainProviderOptions {
107
107
  export interface ApplicationMainProviderProps {
108
108
  options: ApplicationMainProviderOptions;
109
109
  }
110
- export declare function ApplicationMainProvider({ options, }: ApplicationMainProviderProps): React.ReactElement;
110
+ export declare function ApplicationMainProvider(props: ApplicationMainProviderProps): React.ReactElement;
111
111
  //# sourceMappingURL=ApplicationMainContext.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ApplicationMainContext.d.ts","sourceRoot":"","sources":["../../../../src/core/runtime/ApplicationMainContext.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,6BAA6B,EAAmB,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAC5H,OAAO,EAOL,2CAA2C,EAC3C,oBAAoB,EAEpB,KAAK,+BAA+B,EACpC,KAAK,2BAA2B,EAChC,KAAK,kBAAkB,EAExB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,oEAAoE,CAAC;AACpH,OAAO,KAA4D,MAAM,OAAO,CAAC;AA6BjF,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,0CAA0C,CAAC;AAU5F,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,6CAA6C,CAAC;AAC3F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,+DAA+D,CAAC;AA+BxG;;;GAGG;AAGH,MAAM,MAAM,wCAAwC,GAAG;KACpD,CAAC,IAAI,qBAAqB,GAAG,6BAA6B,CAAC,CAAC,CAAC,EAAE;CACjE,CAAC;AAEF,MAAM,WAAW,+BAA+B;IAC9C,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,8BAA8B;IAC7C,uFAAuF;IACvF,uBAAuB,CAAC,EAAE,2BAA2B,CAAC;IACtD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;IAExC;;;OAGG;IACH,8CAA8C,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,2CA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IAEvD;;;;;;;OAOG;IACH,WAAW,EAAE,kBAAkB,GAAG,SAAS,CAAC;IAE5C,yDAAyD;IACzD,kBAAkB,CAAC,EAAE,OAAO,uBAAuB,EAAE,iBAAiB,EAAE,CAAC;IAEzE;;;;;;;;;;OAUG;IACH,kBAAkB,CAAC,EAAE,kBAAkB,CAAC;IAExC;;;;OAIG;IACH,4BAA4B,CAAC,EAAE,2BAA2B,EAAE,CAAC;IAE7D;;;;;;;;;;OAUG;IACH,eAAe,CAAC,EAAE,SAAS,KAAK,CAAC,aAAa,EAAE,CAAC;IAEjD;;;OAGG;IACH,kBAAkB,EAAE,yBAAyB,CAAC;IAE9C,0EAA0E;IAC1E,uBAAuB,CAAC,EAAE,uBAAuB,CAAC;IAElD,yFAAyF;IACzF,eAAe,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CACtC;AAED,MAAM,WAAW,4BAA4B;IAE3C,OAAO,EAAE,8BAA8B,CAAC;CACzC;AAkWD,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,4BAA4B,GAAG,KAAK,CAAC,YAAY,CAO/F"}
@@ -1,7 +1,7 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { withPageApiBaseUrl } from '../../core/runtime/page-api-base-url.frontend.js';
3
3
  import { CorePresetNames, FrontendComponentType } from '@wildo-ai/presets-components-models';
4
- import { mergeFeatureConfigurations, } from '@wildo-ai/saas-models';
4
+ import { mergeFeatureConfigurations, SIGNING_RETURN_PAGE_PATH, } from '@wildo-ai/saas-models';
5
5
  import { useCallback, useEffect, useState, useRef, useMemo } from 'react';
6
6
  import { createBrowserRouter } from 'react-router';
7
7
  // The DOM `RouterProvider` wires `react-dom`'s `flushSync` in; React Router 7 publishes it from the `/dom` subpath.
@@ -311,7 +311,16 @@ function formatInitializationError(rawError, startupAppName) {
311
311
  };
312
312
  }
313
313
  // ApplicationMainProvider component - exported directly for Fast Refresh compatibility
314
- export function ApplicationMainProvider({
314
+ export function ApplicationMainProvider(props) {
315
+ // Embedded signing: the vendor sends a signing frame back to this page once the person is done, and the frame that
316
+ // loaded it only needs to see it arrive. The application must not boot inside that frame: a second instance would
317
+ // restore the session, refresh its tokens (a rotated refresh token the parent then reuses revokes the session) and
318
+ // open a WebSocket, all in a frame about to be removed. So the page renders nothing, before any provider mounts.
319
+ if (window.location.pathname === SIGNING_RETURN_PAGE_PATH)
320
+ return _jsx(_Fragment, {});
321
+ return _jsx(ApplicationMainProviderRoot, { ...props });
322
+ }
323
+ function ApplicationMainProviderRoot({
315
324
  // children,
316
325
  options, }) {
317
326
  const mergedFeatureConfiguration = useMemo(() => mergeFeatureConfigurations(options.featureConfiguration), [options.featureConfiguration]);