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

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 (101) hide show
  1. package/dist/esm/components/data-display/DisplayValueDispatcher.d.ts.map +1 -1
  2. package/dist/esm/components/data-display/DisplayValueDispatcher.js +17 -1
  3. package/dist/esm/components/data-display/DisplayValueDispatcher.js.map +1 -1
  4. package/dist/esm/components/data-display/external-data-provenance/external-data-provenance.frontend.d.ts.map +1 -1
  5. package/dist/esm/components/data-display/external-data-provenance/external-data-provenance.frontend.js +5 -2
  6. package/dist/esm/components/data-display/external-data-provenance/external-data-provenance.frontend.js.map +1 -1
  7. package/dist/esm/components/form/automated/ResourceAutomatedForm.d.ts.map +1 -1
  8. package/dist/esm/components/form/automated/ResourceAutomatedForm.js +20 -1
  9. package/dist/esm/components/form/automated/ResourceAutomatedForm.js.map +1 -1
  10. package/dist/esm/components/form/chromes/FormFieldChrome.js +1 -1
  11. package/dist/esm/components/form/chromes/FormFieldChrome.js.map +1 -1
  12. package/dist/esm/components/form/chromes/field-control-aria.d.ts +8 -1
  13. package/dist/esm/components/form/chromes/field-control-aria.d.ts.map +1 -1
  14. package/dist/esm/components/form/chromes/field-control-aria.js +19 -2
  15. package/dist/esm/components/form/chromes/field-control-aria.js.map +1 -1
  16. package/dist/esm/components/form/validation-errors/validate-field-url.frontend.d.ts +5 -0
  17. package/dist/esm/components/form/validation-errors/validate-field-url.frontend.d.ts.map +1 -1
  18. package/dist/esm/components/form/validation-errors/validate-field-url.frontend.js +6 -2
  19. package/dist/esm/components/form/validation-errors/validate-field-url.frontend.js.map +1 -1
  20. package/dist/esm/components/resources/ResourceCollectionBody_Table.d.ts.map +1 -1
  21. package/dist/esm/components/resources/ResourceCollectionBody_Table.js +8 -1
  22. package/dist/esm/components/resources/ResourceCollectionBody_Table.js.map +1 -1
  23. package/dist/esm/components/resources/ResourceLayout_DangerZone.d.ts.map +1 -1
  24. package/dist/esm/components/resources/ResourceLayout_DangerZone.js +2 -2
  25. package/dist/esm/components/resources/ResourceLayout_DangerZone.js.map +1 -1
  26. package/dist/esm/components/resources/ResourceLayout_RecordSharing.js +2 -2
  27. package/dist/esm/components/resources/ResourceLayout_RecordSharing.js.map +1 -1
  28. package/dist/esm/components/resources/ResourceListItemRenderer.d.ts.map +1 -1
  29. package/dist/esm/components/resources/ResourceListItemRenderer.js +6 -1
  30. package/dist/esm/components/resources/ResourceListItemRenderer.js.map +1 -1
  31. package/dist/esm/components/resources/skeleton/DisplayLayout.js +2 -2
  32. package/dist/esm/components/resources/skeleton/DisplayLayout.js.map +1 -1
  33. package/dist/esm/components/resources-fields/_presets/resource-reference/ResourceFieldDisplayPreset_ResourceReference_Default.d.ts.map +1 -1
  34. package/dist/esm/components/resources-fields/_presets/resource-reference/ResourceFieldDisplayPreset_ResourceReference_Default.js +71 -16
  35. package/dist/esm/components/resources-fields/_presets/resource-reference/ResourceFieldDisplayPreset_ResourceReference_Default.js.map +1 -1
  36. package/dist/esm/components/sections/surface.d.ts +12 -0
  37. package/dist/esm/components/sections/surface.d.ts.map +1 -1
  38. package/dist/esm/components/sections/surface.js +14 -0
  39. package/dist/esm/components/sections/surface.js.map +1 -1
  40. package/dist/esm/core/app-shell/shell-motion/shell-motion-origins.d.ts.map +1 -1
  41. package/dist/esm/core/app-shell/shell-motion/shell-motion-origins.js +3 -2
  42. package/dist/esm/core/app-shell/shell-motion/shell-motion-origins.js.map +1 -1
  43. package/dist/esm/core/app-shell/shell-motion/shell-motion-vocabulary.d.ts +15 -0
  44. package/dist/esm/core/app-shell/shell-motion/shell-motion-vocabulary.d.ts.map +1 -1
  45. package/dist/esm/core/app-shell/shell-motion/shell-motion-vocabulary.js +29 -0
  46. package/dist/esm/core/app-shell/shell-motion/shell-motion-vocabulary.js.map +1 -1
  47. package/dist/esm/core/app-shell/shell-motion/use-shell-motion.d.ts.map +1 -1
  48. package/dist/esm/core/app-shell/shell-motion/use-shell-motion.js +2 -2
  49. package/dist/esm/core/app-shell/shell-motion/use-shell-motion.js.map +1 -1
  50. package/dist/esm/core/branding/useBrandPresentation.d.ts.map +1 -1
  51. package/dist/esm/core/branding/useBrandPresentation.js +17 -6
  52. package/dist/esm/core/branding/useBrandPresentation.js.map +1 -1
  53. package/dist/esm/core/execution/useExecutionResourceOperationContextBuilder.d.ts.map +1 -1
  54. package/dist/esm/core/execution/useExecutionResourceOperationContextBuilder.js +11 -1
  55. package/dist/esm/core/execution/useExecutionResourceOperationContextBuilder.js.map +1 -1
  56. package/dist/esm/core/i18n/I18nContext.d.ts.map +1 -1
  57. package/dist/esm/core/i18n/I18nContext.js +8 -2
  58. package/dist/esm/core/i18n/I18nContext.js.map +1 -1
  59. package/dist/esm/core/i18n/component-label-resolution.utils.d.ts.map +1 -1
  60. package/dist/esm/core/i18n/component-label-resolution.utils.js +6 -1
  61. package/dist/esm/core/i18n/component-label-resolution.utils.js.map +1 -1
  62. package/dist/esm/core/monitoring/analytics/AnalyticsContext.d.ts +0 -15
  63. package/dist/esm/core/monitoring/analytics/AnalyticsContext.d.ts.map +1 -1
  64. package/dist/esm/core/monitoring/analytics/AnalyticsContext.js +71 -6
  65. package/dist/esm/core/monitoring/analytics/AnalyticsContext.js.map +1 -1
  66. package/dist/esm/core/monitoring/analytics/AnalyticsEventBridge.d.ts.map +1 -1
  67. package/dist/esm/core/monitoring/analytics/AnalyticsEventBridge.js +12 -3
  68. package/dist/esm/core/monitoring/analytics/AnalyticsEventBridge.js.map +1 -1
  69. package/dist/esm/core/navigation/NavigationContext.d.ts.map +1 -1
  70. package/dist/esm/core/navigation/NavigationContext.js +60 -17
  71. package/dist/esm/core/navigation/NavigationContext.js.map +1 -1
  72. package/dist/esm/core/navigation/launcher-resolution.d.ts +29 -0
  73. package/dist/esm/core/navigation/launcher-resolution.d.ts.map +1 -1
  74. package/dist/esm/core/navigation/launcher-resolution.js +31 -0
  75. package/dist/esm/core/navigation/launcher-resolution.js.map +1 -1
  76. package/dist/esm/core/navigation/navigation-controller-internals.d.ts +48 -0
  77. package/dist/esm/core/navigation/navigation-controller-internals.d.ts.map +1 -1
  78. package/dist/esm/core/navigation/navigation-controller-internals.js +56 -3
  79. package/dist/esm/core/navigation/navigation-controller-internals.js.map +1 -1
  80. package/dist/esm/core/navigation/useNavigationRouterSync.d.ts.map +1 -1
  81. package/dist/esm/core/navigation/useNavigationRouterSync.js +30 -2
  82. package/dist/esm/core/navigation/useNavigationRouterSync.js.map +1 -1
  83. package/dist/esm/core/resources/route-parent-relocation.frontend.utils.d.ts +44 -0
  84. package/dist/esm/core/resources/route-parent-relocation.frontend.utils.d.ts.map +1 -0
  85. package/dist/esm/core/resources/route-parent-relocation.frontend.utils.js +63 -0
  86. package/dist/esm/core/resources/route-parent-relocation.frontend.utils.js.map +1 -0
  87. package/dist/esm/core/resources/useOperationDirectExecution.d.ts.map +1 -1
  88. package/dist/esm/core/resources/useOperationDirectExecution.js +45 -6
  89. package/dist/esm/core/resources/useOperationDirectExecution.js.map +1 -1
  90. package/dist/esm/core/runtime/AppRouter.d.ts.map +1 -1
  91. package/dist/esm/core/runtime/AppRouter.js +18 -1
  92. package/dist/esm/core/runtime/AppRouter.js.map +1 -1
  93. package/dist/esm/core/security/UserOrgsContext.d.ts.map +1 -1
  94. package/dist/esm/core/security/UserOrgsContext.js +61 -8
  95. package/dist/esm/core/security/UserOrgsContext.js.map +1 -1
  96. package/dist/esm/core/ui/inner-control-activation.utils.d.ts +16 -0
  97. package/dist/esm/core/ui/inner-control-activation.utils.d.ts.map +1 -0
  98. package/dist/esm/core/ui/inner-control-activation.utils.js +44 -0
  99. package/dist/esm/core/ui/inner-control-activation.utils.js.map +1 -0
  100. package/dist/tsconfig.build.tsbuildinfo +1 -1
  101. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"file":"UserOrgsContext.js","sourceRoot":"","sources":["../../../../src/core/security/UserOrgsContext.tsx"],"names":[],"mappings":";AAAA,OAAc,EAAE,aAAa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BAAsB;QACtB,uBAAuB;QACvB,sBAAsB;QACtB,oBAAoB;QACpB,UAAU;QACV,qBAAqB;KACtB,CAAC,CAAC;IAEH,OAAO,KAAC,eAAe,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,YAAG,QAAQ,GAA4B,CAAC;AACvF,CAAC,CAAC","sourcesContent":["import React, { createContext, useState, ReactNode, useMemo, useEffect, useCallback, useRef, useContext } from 'react';\nimport {\n UserContext,\n OrganizationContext,\n CoreResourceType,\n ResourcesConfig_OperationPathUtils,\n CoreResourceOperation,\n ResourceOperationVariantType,\n OPERATION_VARIANT_KEY,\n ExecutionContext_InitiatorIds,\n UserPrivacy,\n UserPreferences,\n SessionType,\n normalizeConsentPurposes,\n UserSelf_Operations,\n type ConsentPurpose,\n type UserSelfAccessProfile,\n} from '@wildo-ai/saas-models';\nimport { useResourceRegistry } from '~wildo-frontend-lib/core/resources/useResourceRegistry';\nimport { LoggerFrontendService } from '~wildo-frontend-lib/core/monitoring/logger.frontend.service';\nimport { useEventBus } from '~wildo-frontend-lib/core/events/useEventBus';\nimport { FrontendEvents, SessionEndReason } from '~wildo-frontend-lib/core/events/events.frontend.schemas';\nimport {\n EffectivePermissions,\n} from './security.frontend.schemas';\nimport { useAuthSession } from './useAuthSession';\nimport { AuthSessionUtils } from './auth-session.utils';\nimport { accessProfileConfersOrganization, membershipRolesFromAccessProfile } from './effective-permissions.frontend.utils';\nimport { isTransientBackendFailure, sessionEndReasonForRefusal } from '~wildo-frontend-lib/core/requests/auth-refresh-resilience.frontend';\nimport { decodeJwtPayload } from './jwt.frontend.utils';\nimport { useAppScope } from '~wildo-frontend-lib/core/scope/useAppScope';\nimport { useAppScopeInternal } from '~wildo-frontend-lib/core/scope/AppScopeContext';\nimport { ScopeUtilsService } from '~wildo-frontend-lib/core/scope/scope.utils.frontend.service';\nimport { findDefaultApiReadOperation, hasActiveMembershipInOrganization } from './route-organization-access.frontend.utils';\nimport { ScopeChangeInitiator } from '~wildo-frontend-lib/core/scope/scope.frontend.schemas';\nimport { deriveRegionalReaderStanding } from '~wildo-frontend-lib/core/i18n/regional-preference-resolution.frontend.utils';\nimport { RegionalReaderStandingPublisherContext } from '~wildo-frontend-lib/core/i18n/I18nContext';\n\nconst logger: LoggerFrontendService = LoggerFrontendService.getLogger();\nconst logDebug: (message: string, context?: Record<string, unknown>) => void = logger.debugByType('UserOrgsContext');\nlogger.setDebugTypeLogging('UserOrgsContext', false);\n\n/**\n * Session-restore retry backoff bounds (transient backend failures only).\n *\n * On RELOAD, a backend that is recompiling/restarting (dev) or briefly\n * unavailable (prod) makes the session-restore fetch fail transiently. Rather\n * than force a logout — which clears the shared `__wildo_refresh` cookie and\n * drops the user to the login screen — restore preserves the session and\n * retries with exponential backoff until the backend returns. Genuine auth/authz\n * and non-network errors do NOT retry (see `restoreSession`). Backoff caps so a\n * sustained outage settles at one attempt per {@link RESTORE_RETRY_MAX_DELAY_MS}.\n */\nconst RESTORE_RETRY_BASE_DELAY_MS = 1_000;\nconst RESTORE_RETRY_MAX_DELAY_MS = 30_000;\n\n/**\n * User Organizations Context\n * Manages user data, organizations, permissions, and preferences\n * Consumes AuthSessionContext for authentication state\n */\n\nexport interface UserOrgsContextType {\n // Re-exported from AuthSession for backward compatibility\n auth: ReturnType<typeof useAuthSession>['auth'];\n identifyByEmail: ReturnType<typeof useAuthSession>['identifyByEmail'];\n authenticateWithPassword: ReturnType<typeof useAuthSession>['authenticateWithPassword'];\n authenticate: ReturnType<typeof useAuthSession>['authenticate'];\n getSessionState: ReturnType<typeof useAuthSession>['getSessionState'];\n isAuthenticated: ReturnType<typeof useAuthSession>['isAuthenticated'];\n logout: () => void;\n restoreSession: () => Promise<boolean>;\n\n // OAuth2 + cross-frontend-handoff methods (delegated from AuthSession)\n initiateOAuth2Login: ReturnType<typeof useAuthSession>['initiateOAuth2Login'];\n handleAuthCodeExchange: ReturnType<typeof useAuthSession>['handleAuthCodeExchange'];\n\n // User data\n user: UserContext | null;\n\n // Organization data\n organizations: OrganizationContext[];\n currentOrganizationId: string | null;\n permissions: EffectivePermissions | null;\n primaryScopeInitiatorIds: ExecutionContext_InitiatorIds | null;\n\n // Privacy (only preference managed here, others are in their respective contexts)\n privacy: UserPrivacy | null;\n\n // Organization management\n /**\n * The person's own choice of organization (the organization switcher). An organization this session loaded, or one\n * the backend's access profile confers entries in, which the switcher found by search past the user context's first\n * 20 memberships (#2452); that one is loaded on demand. Anything else is refused (logged, nothing changes).\n */\n setCurrentOrganization: (organizationId: string) => void;\n /**\n * Make the organization the current route names the session's current one (#2247). See\n * `RouteOrganizationFollow` for why the route is the authority. Refuses (returns `false`, changes nothing) unless\n * the session can be IN it: an ACTIVE membership the client vouches for (the predicate the route's access verdict\n * uses), or an organization this session loaded (what the switcher offers). Refuses in a one-off session too,\n * whose token the server bound to one organization. Called by `AppLayout_AuthenticatedRoute`.\n */\n followRouteOrganization: (organizationId: string) => boolean;\n getCurrentOrganization: () => OrganizationContext | null;\n refreshOrganizations: () => Promise<void>;\n\n // Privacy getter\n getPrivacy: () => UserPrivacy | null;\n\n /**\n * Record the signed-in person's consent decision: exactly the purposes they granted (#534).\n *\n * The argument is the WHOLE granted set, never a delta — a purpose left out is a purpose not granted,\n * so an unticked box is a withdrawal rather than \"no change\". The write always carries a decision\n * claim, which is what lets \"grant nothing\" be recorded as a decision instead of reading as a person\n * who was never asked; the recorded instant is the server's (`buildConsentDecisionPatch`).\n *\n * Resolves with the stored privacy block once it is in state, so a caller gating on consent (the\n * consent gate) sees the new decision on the next render. Rejects when the application mounts no\n * self-preferences UPDATE door or the write fails — a consent surface must say it could not save,\n * never behave as though it had.\n */\n recordConsentDecision: (grantedPurposes: readonly ConsentPurpose[]) => Promise<UserPrivacy>;\n}\n\n/**\n * UserOrgs Context\n * Exported for use in separate hook file (Fast Refresh compatibility)\n * @internal - Use useUserOrgs() hook instead of accessing this directly\n */\nexport const UserOrgsContext: React.Context<UserOrgsContextType | undefined> = createContext<UserOrgsContextType | undefined>(undefined);\n\nexport const UserOrgsProvider: React.FC<{ children: ReactNode }> = ({ children }) => {\n const { doOperation, registry } = useResourceRegistry();\n const { emit } = useEventBus();\n\n // Consume auth session context\n const authSession = useAuthSession();\n const {\n auth,\n tokenStorage,\n identifyByEmail,\n authenticateWithPassword,\n authenticate,\n getSessionState,\n isAuthenticated,\n logout: authLogout,\n endSession,\n getSessionEstablishment,\n getSessionEndReason,\n initiateOAuth2Login,\n handleAuthCodeExchange,\n markSessionRestored,\n setSessionRestoring,\n connectWebSocket,\n } = authSession;\n const appScope = useAppScope();\n const { commitOrganizationScopeValue } = useAppScopeInternal();\n const currentOrganizationId = appScope.currentOrganizationId;\n // Read by `loadOrganizations` at the moment it settles, not when it was created: it awaits network reads.\n const currentOrganizationIdRef = useRef(currentOrganizationId);\n currentOrganizationIdRef.current = currentOrganizationId;\n\n const hasInitializedRef = useRef(false);\n const previousTokenRef = useRef<string | null>(null);\n // Restore-retry lifecycle: `restoreAbortRef` flips true on unmount so an\n // in-flight backoff loop bails instead of touching state on a dead component;\n // `restoreRetryTimerRef` holds the pending backoff timer for cleanup.\n const restoreAbortRef = useRef(false);\n const restoreRetryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const [user, setUser] = useState<UserContext | null>(null);\n // The person loaded now, read by work that settles after an await (an organization loaded on demand, #2275).\n const loadedUserIdRef = useRef<string | null>(null);\n loadedUserIdRef.current = user?._id ?? null;\n\n const [organizations, setOrganizations] = useState<OrganizationContext[]>([]);\n\n const [permissions, setPermissions] = useState<EffectivePermissions | null>(null);\n\n const [privacy, setPrivacy] = useState<UserPrivacy | null>(null);\n\n type PreferencesPayload = Pick<UserPreferences, 'languagePreferences' | 'regional' | 'ui' | 'notifications' | 'privacy'>;\n\n /**\n * The TENANT's half of the payload, derived from its preferences record rather than passed\n * alongside it (#410).\n *\n * The organization contributes two things to `I18nContext` — its language policy and its regional\n * defaults — and they are forwarded together because they come from one record. An earlier shape\n * took the language block as its own argument, and when the regional half was added every call\n * site would have had to remember to forward a second one: three sites, one obligation each, and\n * a fourth site tomorrow that forwards neither. Passing the record makes forgetting impossible.\n */\n const organizationPreferencesPayload = (\n organizationPreferences: OrganizationContext['preferences'] | null | undefined,\n ): Record<string, unknown> => {\n if (organizationPreferences === undefined) {\n return {};\n }\n if (organizationPreferences === null) {\n return { organizationLanguagePreferences: null, organizationRegionalPreferences: null };\n }\n return {\n organizationLanguagePreferences: organizationPreferences.languagePreferences ?? null,\n organizationRegionalPreferences: {\n timezone: organizationPreferences.timezone,\n locale: organizationPreferences.locale,\n dateFormat: organizationPreferences.dateFormat,\n timeFormat: organizationPreferences.timeFormat,\n },\n };\n };\n\n const emitPreferencesChanged = useCallback((\n preferences: PreferencesPayload | null | undefined,\n organizationPreferences?: OrganizationContext['preferences'] | null,\n ): void => {\n if (preferences === null) {\n emit(FrontendEvents.USER_PREFERENCES_CHANGED, {\n languagePreferences: null,\n organizationLanguagePreferences: null,\n regionalPreferences: null,\n organizationRegionalPreferences: null,\n notificationsPreferences: null,\n uiPreferences: null,\n privacy: null,\n });\n return;\n }\n\n emit(FrontendEvents.USER_PREFERENCES_CHANGED, {\n ...(preferences?.languagePreferences !== undefined ? { languagePreferences: preferences.languagePreferences } : {}),\n ...organizationPreferencesPayload(organizationPreferences),\n ...(preferences?.regional !== undefined ? { regionalPreferences: preferences.regional } : {}),\n ...(preferences?.notifications !== undefined ? { notificationsPreferences: preferences.notifications } : {}),\n ...(preferences?.ui !== undefined ? { uiPreferences: preferences.ui } : {}),\n ...(preferences?.privacy !== undefined ? { privacy: preferences.privacy } : {}),\n });\n }, [emit]);\n\n /*\n * `USER_LOGIN` / `USER_LOGOUT` — announced HERE, once per transition of the known person (#1977).\n *\n * Nothing emitted them before, so every listener — error-report attribution, analytics identify and\n * reset, the sign-in and sign-out analytics events — was dead code that read as if sign-in were\n * observed. This is the one place every sign-in method and every way a session ends converge: each\n * authentication stores a token, the auto-load effect below restores the user from it, and every\n * sign-out, refused refresh, failed restore and cross-tab sign-out clears the token, which clears the\n * user. Emitting at each auth method instead would be a dozen call sites, and the next method added\n * would be the one that forgot. Declared BEFORE the preferences effect, because effects run in\n * declaration order and a person's arrival must precede their preferences.\n *\n * The id last announced is the guard, so a re-render, a preferences write that replaces the user\n * object, or StrictMode re-running an effect announces nothing, and a direct switch from one person to\n * another announces the first one's departure before the second one's arrival. HOW the session began\n * and WHY it ended are recorded by `AuthSessionProvider`, the only code that knows, and read at the\n * moment of announcing.\n *\n * A DEPARTURE is announced by the two places that clear the user, BEFORE they publish `privacy: null`:\n * a listener that must act while the person's consent still holds (the sign-out analytics event, sent\n * before the destinations are reset) needs the announcement first, and the consent-based providers\n * stop on the `privacy: null` that follows. The effect announces ARRIVALS, and a departure only as a\n * backstop for a path that cleared the user without announcing. An unmount announces nothing: the\n * provider going away is not the person signing out.\n */\n const announcedUserIdRef = useRef<string | null>(null);\n const announceDeparture = useCallback((reason: SessionEndReason): void => {\n const departedUserId = announcedUserIdRef.current;\n if (departedUserId === null) return;\n announcedUserIdRef.current = null;\n emit(FrontendEvents.USER_LOGOUT, { userId: departedUserId, reason });\n }, [emit]);\n const knownUserId = user?._id ?? null;\n useEffect(() => {\n const previousUserId = announcedUserIdRef.current;\n if (previousUserId === knownUserId) return;\n if (previousUserId !== null && knownUserId !== null) {\n /*\n * One person REPLACED by another with no sign-out between them. Believed unreachable today: a sign-in\n * while someone is loaded sets `isRestoringSession` with `hasInitializedRef` already true, so the\n * auto-load effect below skips it, and `restoreSession` returns early while a user is loaded. Handled\n * anyway, because the consequence of getting it wrong is the next person's analytics running under\n * the previous person's consent: the departure is followed by the same `privacy: null` a sign-out\n * publishes, BEFORE the arrival, so the next person is judged on their own preferences, which the\n * preferences effect below publishes after this one.\n */\n announceDeparture(SessionEndReason.REPLACED);\n setPrivacy(null);\n emitPreferencesChanged(null);\n } else if (previousUserId !== null) {\n announceDeparture(getSessionEndReason());\n }\n if (knownUserId !== null) {\n announcedUserIdRef.current = knownUserId;\n emit(FrontendEvents.USER_LOGIN, { userId: knownUserId, establishment: getSessionEstablishment() });\n }\n }, [knownUserId, emit, announceDeparture, emitPreferencesChanged, getSessionEndReason, getSessionEstablishment]);\n\n const primaryScopeInitiatorIds = useMemo<ExecutionContext_InitiatorIds | null>(() => {\n return ScopeUtilsService.buildInitiatorIds({\n userId: appScope.currentUserId,\n organizationId: appScope.currentOrganizationId,\n applicationId: appScope.currentApplicationId,\n anonymousUserId: appScope.currentAnonymousUserId,\n });\n }, [\n appScope.currentApplicationId,\n appScope.currentAnonymousUserId,\n appScope.currentOrganizationId,\n appScope.currentUserId,\n ]);\n\n /**\n * Extract and store user preferences from context\n * Stores preferences in state for other contexts to read and apply\n */\n const storePreferences = useCallback((\n preferences: PreferencesPayload,\n organizationPreferences?: OrganizationContext['preferences'] | null,\n ): void => {\n // Store privacy preferences in state\n if (preferences.privacy) {\n setPrivacy(preferences.privacy);\n }\n\n const currentOrganizationPreferences = organizationPreferences !== undefined\n ? organizationPreferences\n : currentOrganizationId\n ? organizations.find((organization) => organization._id === currentOrganizationId)?.preferences\n : undefined;\n\n // Emit preference change event to notify parent contexts\n emitPreferencesChanged(\n preferences,\n currentOrganizationPreferences,\n );\n }, [currentOrganizationId, emitPreferencesChanged, organizations]);\n\n /**\n * The caller's access profile (`user-self | access_profile`, #2381) — the role entries the backend authorizes this\n * person with, unit and relationship grants included, and which resources narrow by unit. The shell's\n * visibility decisions read it (`viewerMayPerformOperation`). `null` when the operation is absent or the read fails.\n *\n * The route names no user: the backend answers from the request's own execution context, so it can only ever describe\n * the person asking (`GET /user-self/access-profile/count`).\n */\n const loadAccessProfile = async (): Promise<UserSelfAccessProfile | null> => {\n const userSelfConfig = registry.resourceConfigurations[CoreResourceType.USER_SELF];\n const accessProfileOperation = userSelfConfig?.operations.find((op: any) =>\n op.operationIdentifier === UserSelf_Operations.ACCESS_PROFILE &&\n op.variantType === ResourceOperationVariantType.API_CALL &&\n op.isBulkOperation !== true\n );\n if (!accessProfileOperation) return null;\n try {\n const operationPath = ResourcesConfig_OperationPathUtils.buildOperationPathKeyFromOperation(accessProfileOperation);\n return (await doOperation<UserSelfAccessProfile>(operationPath, { contextualParameters: {} })) ?? null;\n } catch (error) {\n logger.warn('Access profile could not be loaded; entries reached only through an organization-unit grant stay hidden', { error });\n return null;\n }\n };\n\n /**\n * Compute effective permissions from user's app roles and organization roles\n * This is a basic implementation - can be enhanced based on role hierarchy\n */\n const computeEffectivePermissions = (\n userContext: UserContext,\n organizationsList: OrganizationContext[]\n ): EffectivePermissions | null => {\n // App-level permissions from user's app roles\n const appLevel = (userContext.appRoles || []) as string[];\n\n // Per-organization permissions from organization membership roles\n // Use new field name from relationship-based context\n const organizationsPermissions: Record<string, string[]> = {};\n const memberships = userContext.organizationMembers || [];\n\n for (const membership of memberships) {\n organizationsPermissions[membership.organizationId] = (membership.roles || []) as string[];\n }\n\n return {\n appLevel,\n organizations: organizationsPermissions,\n accessProfile: null,\n };\n };\n\n /**\n * One of the person's own organizations, as the session holds it: the organization READ and, beside it, the tenant's\n * preference record. `null` when the organization cannot be read (a refusal, a transient failure, no READ mounted).\n *\n * Shared by `loadOrganizations` (the memberships the user context carries) and by the organizations loaded ON\n * DEMAND (#2275): a membership past the user context's cap that the session follows or starts in. Both must hold\n * the organization the same way, or the switcher and the i18n preferences would differ by how it arrived.\n */\n const fetchOwnOrganization = useCallback(async (organizationId: string): Promise<OrganizationContext | null> => {\n const organizationsConfig = registry.resourceConfigurations[CoreResourceType.ORGANIZATIONS];\n if (!organizationsConfig) {\n logger.warn('ORGANIZATIONS resource not available');\n return null;\n }\n // Shared with the route organization-access probe, which must address the same READ.\n const orgsReadOp = findDefaultApiReadOperation(organizationsConfig);\n if (!orgsReadOp) {\n logger.warn('ORGANIZATIONS READ operation not found');\n return null;\n }\n const organizationsOperationPath = ResourcesConfig_OperationPathUtils.buildOperationPathKeyFromOperation(orgsReadOp);\n\n /**\n * The tenant's preference record is fetched SEPARATELY, and that is a decision rather than an\n * omission (#563).\n *\n * `OrganizationContextSchema` declares `preferences`, and `doOperation<OrganizationContext>`\n * is a CAST — nothing validates the response against it — so the field read as available\n * while no producer existed: the ORGANIZATIONS **default** READ returns a plain\n * `Organization`, and the organisation's regional block therefore never reached\n * `I18nContext`. Every date and number in every generated application formatted at the\n * framework floor as a result.\n *\n * The rejected alternative was to switch this call to the ORGANIZATIONS **context** variant,\n * which does populate the child. Measured against the running stack on 2026-09-10, that\n * response carries every context-enabled child of an organisation — `auditLogs`, `todos`,\n * `tasks`, `knowledgeDocuments`, `organizationMembers`, … — so session restore would pull an\n * unbounded page of tenant data per membership to obtain four regional fields. (#583 has since\n * taken the audit and delivery logs off the context surface and capped every 1:many child at\n * `contextPolicy.limit`, 20 by default. The page is bounded now, but it is still a page of tenant\n * data per membership, so the reasoning stands.) The\n * preference record has its own default READ (`GET /organizations/{id}/organization-preference`,\n * reachable by an ordinary `ORG_MEMBER`), which is one small request with a stable shape.\n *\n * Best-effort by construction: a tenant whose preferences cannot be read still yields a\n * usable organisation, and `organizationPreferencesPayload(undefined)` then contributes\n * nothing to the i18n event rather than clearing the member's own settings.\n */\n const organizationPreferencesReadOp = findDefaultApiReadOperation(registry.resourceConfigurations[CoreResourceType.ORGANIZATION_PREFERENCES]);\n const fetchOrganizationPreferences = async (): Promise<OrganizationContext['preferences'] | undefined> => {\n // Absent READ: reported once per list load by `loadOrganizations`, not once per organization.\n if (!organizationPreferencesReadOp) return undefined;\n try {\n return await doOperation<NonNullable<OrganizationContext['preferences']>>(\n ResourcesConfig_OperationPathUtils.buildOperationPathKeyFromOperation(organizationPreferencesReadOp),\n { contextualParameters: { organizationId } },\n ) ?? undefined;\n } catch (error) {\n logger.warn('Failed to fetch organization preferences', { organizationId, error });\n return undefined;\n }\n };\n\n try {\n const [org, preferences] = await Promise.all([\n doOperation<OrganizationContext>(organizationsOperationPath, { contextualParameters: { organizationId } }),\n fetchOrganizationPreferences(),\n ]);\n if (!org) return null;\n // OMIT the key when the read failed rather than attaching `null`. The payload builder\n // reads the two differently: `undefined`/absent contributes nothing to the i18n event,\n // while `null` means \"the tenant has cleared its preferences\" and actively resets the\n // organisation half — which would silently downgrade a member to the framework floor\n // because one request failed.\n return preferences ? { ...org, preferences } : org;\n } catch (error) {\n logger.warn('Failed to fetch organization', { organizationId, error });\n return null;\n }\n }, [doOperation, registry]);\n\n /**\n * Load one of the person's own organizations the session does not hold yet, and add it to `organizations` (#2275,\n * #2452): one followed by route, or one the switcher found by search past the user context's first 20 memberships.\n * One path for both, so an organization arrives the same way whichever door admitted it. A sign-out or another\n * person's sign-in while the read was in flight must not receive this person's organization.\n */\n const loadOrganizationOnDemand = useCallback((organizationId: string): void => {\n const requestingUserId = loadedUserIdRef.current;\n void fetchOwnOrganization(organizationId).then((organization) => {\n if (!organization || loadedUserIdRef.current !== requestingUserId) return;\n setOrganizations((previous) => previous.some((existing) => existing._id === organization._id) ? previous : [...previous, organization]);\n });\n }, [fetchOwnOrganization]);\n\n /**\n * Load organizations independently (can be called separately from authentication)\n */\n const loadOrganizations = useCallback(async (userContext: UserContext): Promise<{\n organizationsList: OrganizationContext[];\n selectedOrgId: string | null;\n }> => {\n // The backend's own account of this person's access (#2381), fetched beside the organizations rather than after\n // them. Best-effort: a failure leaves the shell deciding on membership roles alone (unit-granted entries hidden).\n const accessProfilePromise = loadAccessProfile();\n const allMemberships = userContext.organizationMembers || [];\n\n // W7.3b: For one-off sessions, restrict to the scoped organization only\n const scopedOrgId = auth.sessionType === SessionType.ONE_OFF\n ? tokenStorage.getOrganizationId()\n : null;\n\n const memberships = scopedOrgId\n ? allMemberships.filter((m: any) => m.organizationId === scopedOrgId)\n : allMemberships;\n\n logDebug('Loading organizations', {\n userId: userContext._id,\n membershipCount: memberships.length,\n isOneOff: auth.sessionType === SessionType.ONE_OFF,\n });\n\n if (!findDefaultApiReadOperation(registry.resourceConfigurations[CoreResourceType.ORGANIZATION_PREFERENCES])) {\n logger.warn('ORGANIZATION_PREFERENCES READ operation not found — tenant regional defaults will not be applied');\n }\n const organizationsList: OrganizationContext[] = [];\n const membershipOrganizationResults = await Promise.all(\n memberships.map((membership: any) => fetchOwnOrganization(String(membership.organizationId))),\n );\n organizationsList.push(...membershipOrganizationResults.filter((org): org is OrganizationContext => org !== null));\n\n // Keep the organization this tab is IN when it is still one of the person's (#2247): a reload of the list\n // (`refreshOrganizations`, e.g. after accepting an invitation) must not move the tab. The stored value is\n // shared by every tab and follows each tab's route, so reading it here would pull this tab into whatever\n // organization another tab last opened, and the switch would send it home. The stored value is the default a\n // session STARTS from (during restore AppScope exposes no organization yet, so it is the one used), then the\n // first organization.\n const tabOrgId = currentOrganizationIdRef.current;\n const storedOrgId = tokenStorage.getOrganizationId();\n const isLoaded = (organizationId: string | null): organizationId is string =>\n !!organizationId && organizationsList.some(o => o._id === organizationId);\n const accessProfile = await accessProfilePromise;\n\n // The organization the tab is in, or the session starts from, may be one the user context does not carry: its\n // `organizationMembers` holds only the newest 20 memberships (#2275), and since #2247 the tab's and the stored\n // organization follow the route, so they are often one past that cap. When the backend's access profile confers\n // entries there, it is one of the person's own and is loaded on demand like the others; without that, a reload\n // of the list would move the tab out of the organization its page names, and a new session would never start\n // where the person last was. In a one-off session only the organization its token is bound to is ever loaded.\n const preferredOrgId = tabOrgId ?? storedOrgId;\n if (\n preferredOrgId\n && !isLoaded(preferredOrgId)\n && (!scopedOrgId || preferredOrgId === scopedOrgId)\n && accessProfileConfersOrganization(accessProfile, preferredOrgId)\n ) {\n const preferredOrganization = await fetchOwnOrganization(preferredOrgId);\n if (preferredOrganization) organizationsList.push(preferredOrganization);\n }\n\n const selectedOrgId = isLoaded(tabOrgId)\n ? tabOrgId\n : isLoaded(storedOrgId)\n ? storedOrgId\n : organizationsList[0]?._id || null;\n\n // Compute effective permissions. With the backend's access profile, the roles are the ones the backend confers\n // (`membershipRolesFromAccessProfile`); without it, the membership rows decide, as before.\n const membershipPermissions = computeEffectivePermissions(userContext, organizationsList);\n const computedPermissions = membershipPermissions\n ? { ...membershipPermissions, ...(accessProfile ? membershipRolesFromAccessProfile(accessProfile) : {}), accessProfile }\n : null;\n\n setOrganizations(organizationsList);\n commitOrganizationScopeValue(selectedOrgId);\n setPermissions(computedPermissions);\n\n logDebug('Organizations loaded', { organizationCount: organizationsList.length, currentOrganizationId: selectedOrgId });\n return { organizationsList, selectedOrgId };\n }, [commitOrganizationScopeValue, fetchOwnOrganization, registry, tokenStorage, auth.sessionType]);\n\n /**\n * Restore regular user session\n */\n const restoreUserSession = useCallback(async (accessToken: string): Promise<boolean> => {\n logDebug('Restoring user session');\n\n // Check if USER_SELF is available\n const availableResources = Object.keys(registry.resourceConfigurations);\n const hasUserSelf = availableResources.includes(CoreResourceType.USER_SELF);\n\n if (!hasUserSelf) {\n logger.warn('USER_SELF resource not available for session restoration');\n return false;\n }\n\n // Get USER_SELF resource config\n const userSelfConfig = registry.resourceConfigurations[CoreResourceType.USER_SELF];\n\n const readOperation = findDefaultApiReadOperation(userSelfConfig);\n\n if (!readOperation) {\n logger.warn('USER_SELF READ operation not found');\n return false;\n }\n\n // Find context variant (auto-generated with relationship population)\n const readContextOp = userSelfConfig.operations.find((op: any) =>\n op.operationIdentifier === CoreResourceOperation.READ &&\n op.isBulkOperation !== true &&\n op.variantType === ResourceOperationVariantType.API_CALL &&\n op.variantKey === OPERATION_VARIANT_KEY.CONTEXT\n );\n\n if (!readContextOp) {\n logger.warn('USER_SELF context variant not found');\n return false;\n }\n\n const initiatorInfo = readOperation.initiatorInfos?.[0];\n const requiresUserId = initiatorInfo?.parameters?.some((p: any) => p.fieldIdentifier === 'userId');\n\n const contextualParameters: Record<string, string> = {};\n\n if (requiresUserId && accessToken) {\n try {\n const payload = decodeJwtPayload<{ userId?: string }>(accessToken);\n if (payload.userId) {\n contextualParameters.userId = payload.userId;\n }\n } catch (e) {\n logDebug('Failed to decode JWT for userId extraction', { error: e });\n }\n }\n\n // Build operation path and fetch user context\n const contextPath = ResourcesConfig_OperationPathUtils.buildOperationPathKeyFromOperation(readContextOp);\n const userContext = await doOperation<UserContext>(contextPath, { contextualParameters });\n\n if (!userContext) {\n logger.warn('Failed to fetch user context during session restoration');\n return false;\n }\n\n // Use new field name from relationship-based context\n const membershipsCount = (userContext.organizationMembers || []).length;\n logDebug('User context restored', { userId: userContext._id, organizationCount: membershipsCount });\n\n // Update user state\n setUser(userContext);\n\n // Load organizations separately\n // If this fails, session restoration still succeeds (user context is restored)\n const { organizationsList, selectedOrgId } = await loadOrganizations(userContext);\n\n // Store preferences after organization loading so i18n receives user and\n // active-organization language policy in the same event.\n const preferences = userContext.userSelfPreferences;\n if (preferences) {\n const currentOrganization = selectedOrgId\n ? organizationsList.find((organization) => organization._id === selectedOrgId)\n : null;\n storePreferences(preferences, currentOrganization?.preferences);\n }\n\n logger.info('Session restored successfully', {\n userId: userContext._id,\n organizationCount: membershipsCount\n });\n\n return true;\n }, [doOperation, registry, loadOrganizations, storePreferences]);\n\n // Stop any pending restore-retry backoff when the provider unmounts, so the\n // loop in `restoreSession` bails instead of calling setState on a dead tree.\n useEffect(() => {\n restoreAbortRef.current = false;\n return () => {\n restoreAbortRef.current = true;\n if (restoreRetryTimerRef.current) {\n clearTimeout(restoreRetryTimerRef.current);\n restoreRetryTimerRef.current = null;\n }\n };\n }, []);\n\n /**\n * Restore session from stored JWT token\n * Fetches user context using USER_SELF resource (userId comes from JWT)\n * Then fetches full organization details for each organization membership\n *\n * Resilience: a TRANSIENT backend failure (unreachable / 5xx / timeout, or a\n * 401 whose in-flight renewal failed transiently) does NOT log out — restore\n * preserves the session and retries with capped exponential backoff until the\n * backend returns. Genuine authentication (401), authorization (403), and\n * non-network errors terminate immediately (no retry on a dead-or-buggy path).\n */\n const runSessionRestore = useCallback(async (): Promise<boolean> => {\n logDebug('Restoring session from stored token');\n\n // Check if session is already restored to avoid duplicate restoration attempts\n if (auth.sessionRestored && auth.accessToken && user) {\n logDebug('Session already restored, skipping restoration');\n return true;\n }\n\n // Read token from auth state\n const accessToken = auth.accessToken;\n\n if (!accessToken) {\n logDebug('No access token available');\n return false;\n }\n\n setSessionRestoring(true);\n\n let attempt = 0;\n // Single backoff loop: the invoking effect won't re-enter while\n // `isRestoringSession` is true, so this is the sole restore in flight.\n while (true) {\n try {\n const restored = await restoreUserSession(accessToken);\n\n if (restored) {\n markSessionRestored();\n\n // W7.3b: One-off sessions already connected WebSocket in handleOneOffTokenExchange\n // (with consumableToken). Reconnecting here would lose the consumable token.\n if (auth.sessionType !== SessionType.ONE_OFF) {\n // Connect with the FRESHEST token, read live from storage — NOT the\n // `accessToken` captured at the top of `restoreSession`. During the\n // awaited `restoreUserSession` above, the HTTP interceptor may have\n // hit a `401 OUTDATED_AUTH_JWT` and rotated the token via\n // `tokenRenewalHandler` (which writes the new token to storage AND\n // seeds the WS `authStateRef` synchronously). The captured\n // `accessToken` is then stale/expired; passing it into `connect()`\n // reseeds the WS credential source-of-truth back to the expired token\n // (clobbering the fresh one the refresh just stored), and the Socket.IO\n // handshake gets rejected with \"Authentication failed\". `getAccessToken()`\n // returns the live, post-refresh value (falling back to the captured\n // token only if storage is somehow empty).\n const freshestAccessToken = tokenStorage.getAccessToken() ?? accessToken;\n connectWebSocket(freshestAccessToken, tokenStorage.getOrganizationId());\n }\n } else {\n logger.warn('Session restoration could not build a valid authenticated context; logging out to avoid a half-restored state');\n endSession(SessionEndReason.SESSION_ENDED);\n }\n\n return restored;\n\n } catch (error: any) {\n // Authorization (403 / scope) is checked FIRST and is non-destructive: a\n // permission denial must NEVER destroy a valid session. Authentication\n // (401 / session-invalid) is the only branch that force-logs-out.\n // `isAuthenticationError` already excludes authorization errors (see\n // `AuthSessionUtils`), so these are mutually exclusive — the explicit\n // ordering here is defense-in-depth so the non-destructive path wins even\n // if that guard is ever loosened.\n const isAuthorizationError = AuthSessionUtils.isAuthorizationError(error);\n\n if (isAuthorizationError) {\n const errorMessage = error?.message || 'Session restoration blocked by authorization';\n logger.warn('Session restoration encountered authorization/scope error', {\n error: errorMessage,\n errorType: error?.wildoError?.type || error?.response?.data?.error?.type,\n status: error?.response?.status,\n });\n setSessionRestoring(false);\n markSessionRestored();\n return false;\n }\n\n // TRANSIENT backend failure (checked BEFORE the authentication branch so\n // a 401 whose renewal failed transiently is retried, not logged out):\n // preserve the session, back off, and retry. Bail if the component\n // unmounted or the session was cleared (logout elsewhere) while waiting.\n if (isTransientBackendFailure(error)) {\n attempt += 1;\n const delay = Math.min(\n RESTORE_RETRY_BASE_DELAY_MS * 2 ** (attempt - 1),\n RESTORE_RETRY_MAX_DELAY_MS,\n );\n logger.warn('Session restoration hit a transient backend failure; preserving session and retrying', {\n attempt,\n retryInMs: delay,\n status: error?.response?.status,\n code: error?.code,\n });\n await new Promise<void>((resolve) => {\n restoreRetryTimerRef.current = setTimeout(resolve, delay);\n });\n if (restoreAbortRef.current || !tokenStorage.getAccessToken()) {\n setSessionRestoring(false);\n return false;\n }\n continue;\n }\n\n if (AuthSessionUtils.isAuthenticationError(error)) {\n logDebug('Session restoration failed due to authentication error', {\n errorType: error?.wildoError?.type || error?.response?.data?.error?.type,\n status: error?.response?.status,\n });\n // Usually the refresh already ended it, naming why; when restore is first, it reads the refusal itself.\n endSession(sessionEndReasonForRefusal(error));\n return false;\n }\n\n // Fail closed on unexpected NON-transient errors. A partially restored\n // authenticated shell is less safe than dropping back to a clean login.\n const errorMessage = error?.message || 'Session restoration failed';\n logger.warn('Session restoration encountered a non-transient error; logging out', {\n error: errorMessage,\n errorType: error?.wildoError?.type,\n });\n\n endSession(SessionEndReason.SESSION_ENDED);\n return false;\n }\n }\n }, [\n restoreUserSession,\n auth.sessionRestored,\n auth.sessionType,\n auth.accessToken,\n user,\n endSession,\n markSessionRestored,\n setSessionRestoring,\n connectWebSocket,\n tokenStorage\n ]);\n\n /**\n * The access token the last restore CONCLUDED for, whatever its outcome (#2242).\n *\n * \"A token and no user\" is two different states, and the reader standing must tell them apart: before a\n * restore has run for this token (every returning visitor's first render, and a one-off session, which\n * starts with `sessionRestored: true` and no user) it is UNSETTLED; after a restore concluded without a\n * user (the authorization-error branch keeps the token) it is settled with no person. Neither\n * `isRestoringSession` nor `sessionRestored` says which — so the restore records it. Keyed by the token\n * LIVE at the end, since a restore may rotate it mid-flight.\n */\n const [restoreConcludedForToken, setRestoreConcludedForToken] = useState<string | null>(null);\n const restoreSession = useCallback(async (): Promise<boolean> => {\n try {\n return await runSessionRestore();\n } finally {\n const settledToken = tokenStorage.getAccessToken();\n if (settledToken) setRestoreConcludedForToken(settledToken);\n }\n }, [runSessionRestore, tokenStorage]);\n\n /**\n * Refresh organizations data (e.g., after organization update)\n */\n const refreshOrganizations = useCallback(async (): Promise<void> => {\n // Use new field name from relationship-based context\n const memberships = user?.organizationMembers || [];\n\n if (memberships.length === 0) {\n logDebug('No organizations membership to refresh');\n return;\n }\n\n logDebug('Refreshing organizations', { membershipCount: memberships.length });\n\n // Use loadOrganizations to refresh\n await loadOrganizations(user!);\n }, [user, loadOrganizations]);\n\n useEffect(() => {\n if (!user?.userSelfPreferences) {\n return;\n }\n\n const currentOrganization = currentOrganizationId\n ? organizations.find((organization) => organization._id === currentOrganizationId)\n : null;\n\n emitPreferencesChanged(\n user.userSelfPreferences,\n currentOrganization?.preferences,\n );\n }, [currentOrganizationId, emitPreferencesChanged, organizations, user]);\n\n /*\n * Whether anybody is reading, published to `I18nContext` (#2242). It mounts above this provider, so a null\n * member and a null organization are all it can see — the same for an anonymous visitor as for a member\n * being restored, and only the first should have the browser stand in for their preferences.\n *\n * Through `RegionalReaderStandingPublisherContext`, never the bus: `I18nProvider` is our ancestor, so its\n * bus subscription is made AFTER our mount effect runs, and an emission there is lost (see the context's\n * JSDoc). ONE effect, deriving from the session rather than riding each preference emission above: every\n * way a session starts or ends changes one of these inputs, so none can forget to say it. Declared AFTER\n * the preferences effect so a member's SIGNED_IN follows their preferences in the same commit; the restore\n * path stores them before `isRestoringSession` clears, so it is ordered by the derivation itself.\n */\n const publishRegionalReaderStanding = useContext(RegionalReaderStandingPublisherContext);\n const regionalReaderStanding = deriveRegionalReaderStanding({\n isRestoringSession: auth.isRestoringSession,\n hasUser: user !== null,\n hasAccessToken: Boolean(auth.accessToken),\n restoreConcludedForAccessToken: Boolean(auth.accessToken) && restoreConcludedForToken === auth.accessToken,\n });\n useEffect(() => {\n publishRegionalReaderStanding?.(regionalReaderStanding);\n }, [publishRegionalReaderStanding, regionalReaderStanding]);\n\n /**\n * Set the current active organization\n */\n const setCurrentOrganization = useCallback((organizationId: string): void => {\n const org = organizations.find(o => o._id === organizationId);\n // An organization the switcher FOUND by search rather than one it loaded (#2452): past the user context's first\n // 20 memberships. Admitted on the same fact `followRouteOrganization` admits it on — the backend's access profile\n // confers entries there — and loaded on demand like a followed one, so the switcher and the tenant's preferences\n // hold it the same way. Never in a one-off session, whose token the server bound to one organization.\n const conferred = !org\n && auth.sessionType !== SessionType.ONE_OFF\n && accessProfileConfersOrganization(permissions?.accessProfile, organizationId);\n if (!org && !conferred) {\n logger.warn('Attempted to set invalid organization', { organizationId, availableOrganizations: organizations.map(o => o._id) });\n return;\n }\n if (conferred) loadOrganizationOnDemand(organizationId);\n\n const previousOrganizationId = currentOrganizationId;\n\n // Skip if the organization hasn't changed\n if (previousOrganizationId === organizationId) {\n return;\n }\n\n logDebug('Setting current organization', { organizationId, organizationName: org?.name, previousOrganizationId, loadedOnDemand: conferred });\n commitOrganizationScopeValue(organizationId, ScopeChangeInitiator.USER_SELECTION);\n }, [auth.sessionType, organizations, permissions, currentOrganizationId, commitOrganizationScopeValue, loadOrganizationOnDemand]);\n\n /**\n * Follow the organization the route names (#2247).\n *\n * Three facts admit it, matching the route verdicts the follow acts on. An ACTIVE membership the client vouches for\n * is what `ACTIVE_MEMBERSHIP` rests on, so the two cannot disagree. An organization in `organizations` is one this\n * session loaded from its own memberships and offers in the switcher; it is what admits a representative member\n * (#1597), whose membership the client deliberately never vouches for and the server `ADMITTED`. An organization the\n * backend's access profile confers entries in is a membership past the user context's cap of 20 (#2275), which the\n * server also `ADMITTED`: it is loaded on demand, so the switcher and the tenant's preferences hold the organization\n * the person is in. Anything else — a platform operator's crossing, a foreign organization — is refused.\n *\n * The commit does not wait for that load. The roles the page is judged by come from the access profile, which is\n * already held, and holding the route's content until a second read lands would only delay a page that can render.\n */\n const followRouteOrganization = useCallback((organizationId: string): boolean => {\n if (auth.sessionType === SessionType.ONE_OFF) {\n return false;\n }\n const loaded = organizations.some((organization) => organization._id === organizationId);\n const conferred = accessProfileConfersOrganization(permissions?.accessProfile, organizationId);\n const sessionCanBeIn = hasActiveMembershipInOrganization(user?.organizationMembers, organizationId) || loaded || conferred;\n if (!sessionCanBeIn) {\n logger.warn('Refused to follow a route organization this session cannot be in', { organizationId });\n return false;\n }\n if (!loaded) loadOrganizationOnDemand(organizationId);\n if (currentOrganizationId !== organizationId) {\n logDebug('Following the route organization', { organizationId, previousOrganizationId: currentOrganizationId });\n commitOrganizationScopeValue(organizationId, ScopeChangeInitiator.ROUTER);\n }\n return true;\n }, [auth.sessionType, user, organizations, permissions, currentOrganizationId, commitOrganizationScopeValue, loadOrganizationOnDemand]);\n\n /**\n * Get the current active organization\n */\n const getCurrentOrganization = useCallback((): OrganizationContext | null => {\n if (!currentOrganizationId) {\n return null;\n }\n return organizations.find(o => o._id === currentOrganizationId) || null;\n }, [currentOrganizationId, organizations]);\n\n /**\n * Get privacy preferences\n */\n const getPrivacy = useCallback((): UserPrivacy | null => {\n return privacy;\n }, [privacy]);\n\n // Depend on the builder alone: the whole AppScope value changes with every custom scope value, and through\n // this callback it would re-render every `useUserOrgs` consumer.\n const buildScopeContextualParameters = appScope.buildContextualParameters;\n const recordConsentDecision = useCallback(async (grantedPurposes: readonly ConsentPurpose[]): Promise<UserPrivacy> => {\n const operation = registry.resourceConfigurations[CoreResourceType.USER_SELF_PREFERENCES]?.operations.find(\n (candidate) => candidate.operationIdentifier === CoreResourceOperation.UPDATE\n && candidate.isOperationDefault === true\n && candidate.isBulkOperation !== true\n && (\n candidate.variantType === ResourceOperationVariantType.API_CALL\n ),\n );\n if (!operation) {\n throw new Error('Cannot record a consent decision: this application mounts no user self-preferences UPDATE operation');\n }\n\n const updated = await doOperation<UserPreferences>(\n ResourcesConfig_OperationPathUtils.buildOperationPathKeyFromOperation(operation),\n {\n // This provider sits ABOVE `ScopedResourceRegistryProvider`, so the `doOperation` it holds injects\n // no scope: the user id the self-preferences route is addressed by has to be supplied here. With an\n // empty set the client could not build the URL and every decision failed before a request left\n // (`frontend_resource_no_endpoint_available`, #977 — found by driving the prompt in a browser).\n contextualParameters: buildScopeContextualParameters(),\n requestData: {\n // The client instant is only a CLAIM that this write is a decision; the server replaces it.\n privacy: { consentedPurposes: normalizeConsentPurposes(grantedPurposes), consentDecidedAt: new Date() },\n },\n },\n );\n const storedPrivacy = updated?.privacy;\n if (!storedPrivacy) {\n throw new Error('Consent decision was written but the response carried no privacy block');\n }\n\n setPrivacy(storedPrivacy);\n // Updating the user's preferences record re-emits USER_PREFERENCES_CHANGED through the effect\n // above, which is how the analytics provider learns the new set without a second channel.\n setUser((previous) => previous\n ? { ...previous, userSelfPreferences: { ...(previous.userSelfPreferences ?? {}), privacy: storedPrivacy } as UserContext['userSelfPreferences'] }\n : previous);\n // While a required purpose was missing the backend refused this person's organization reads, so\n // session restore may have loaded none (#534 re-review N1). Re-load them now that the decision is\n // stored; a failure leaves the decision recorded and is retried on the next restore.\n if (organizations.length === 0) {\n await refreshOrganizations().catch((error: unknown) => {\n logger.warn('Organizations could not be re-loaded after a consent decision', { error });\n });\n }\n return storedPrivacy;\n }, [buildScopeContextualParameters, doOperation, registry, organizations.length, refreshOrganizations]);\n\n /**\n * Logout wrapper that also clears user/org data\n */\n const logout = useCallback((): void => {\n logDebug('Logging out user', { userId: user?._id, organizationId: currentOrganizationId });\n\n // Announced first, while the person's consent still holds — see the block above (#1977).\n announceDeparture(SessionEndReason.SIGNED_OUT);\n\n // Clear user/org data first\n setUser(null);\n setOrganizations([]);\n commitOrganizationScopeValue(null);\n setPermissions(null);\n setPrivacy(null);\n emitPreferencesChanged(null);\n\n // Reset initialization flag\n hasInitializedRef.current = false;\n previousTokenRef.current = null;\n\n // Call auth logout (clears tokens, disconnects WebSocket)\n authLogout();\n }, [user?._id, currentOrganizationId, authLogout, announceDeparture, commitOrganizationScopeValue, emitPreferencesChanged]);\n\n // Auto-load user/org data when token becomes available\n useEffect(() => {\n const accessToken = auth.accessToken;\n\n // Skip if no token or token hasn't changed\n if (!accessToken || accessToken === previousTokenRef.current) {\n return;\n }\n\n // Skip if session is already restored with this token\n if (auth.sessionRestored && user) {\n previousTokenRef.current = accessToken;\n return;\n }\n\n // Skip if already initializing\n if (hasInitializedRef.current && auth.isRestoringSession) {\n return;\n }\n\n logDebug('Token changed, initiating session restoration', {\n hasToken: !!accessToken,\n previousToken: !!previousTokenRef.current\n });\n\n previousTokenRef.current = accessToken;\n hasInitializedRef.current = true;\n\n // Restore session (will fetch user/org data)\n restoreSession().catch((error) => {\n logger.error('Session restoration failed', { error });\n });\n }, [auth.accessToken, auth.sessionRestored, auth.isRestoringSession, user, restoreSession]);\n\n // Clear data when token is removed (logged out)\n useEffect(() => {\n if (!auth.accessToken && previousTokenRef.current) {\n logDebug('Token removed, clearing user/org data');\n // Announced before `privacy: null`, with the reason the auth session recorded (#1977).\n announceDeparture(getSessionEndReason());\n setUser(null);\n setOrganizations([]);\n commitOrganizationScopeValue(null);\n setPermissions(null);\n setPrivacy(null);\n emitPreferencesChanged(null);\n previousTokenRef.current = null;\n hasInitializedRef.current = false;\n }\n }, [auth.accessToken, announceDeparture, commitOrganizationScopeValue, emitPreferencesChanged, getSessionEndReason]);\n\n const value = useMemo<UserOrgsContextType>(() => ({\n // Re-exported from AuthSession for backward compatibility\n auth,\n identifyByEmail,\n authenticateWithPassword,\n authenticate,\n getSessionState,\n isAuthenticated,\n logout,\n restoreSession,\n\n // OAuth2 + cross-frontend-handoff methods (delegated from AuthSession)\n initiateOAuth2Login,\n handleAuthCodeExchange,\n\n // User data\n user,\n\n // Organization data\n organizations,\n currentOrganizationId,\n permissions,\n primaryScopeInitiatorIds,\n\n // Privacy (only preference managed here)\n privacy,\n\n // Organization management\n setCurrentOrganization,\n followRouteOrganization,\n getCurrentOrganization,\n refreshOrganizations,\n\n // Privacy getter\n getPrivacy,\n recordConsentDecision,\n }), [\n auth,\n identifyByEmail,\n authenticateWithPassword,\n authenticate,\n getSessionState,\n isAuthenticated,\n logout,\n restoreSession,\n initiateOAuth2Login,\n handleAuthCodeExchange,\n user,\n organizations,\n currentOrganizationId,\n permissions,\n primaryScopeInitiatorIds,\n privacy,\n setCurrentOrganization,\n followRouteOrganization,\n getCurrentOrganization,\n refreshOrganizations,\n getPrivacy,\n recordConsentDecision,\n ]);\n\n return <UserOrgsContext.Provider value={value}>{children}</UserOrgsContext.Provider>;\n};\n\n// useUserOrgs hook is now in separate file: ./useUserOrgs.ts\n// This separation is required for React Fast Refresh compatibility\n"]}
1
+ {"version":3,"file":"UserOrgsContext.js","sourceRoot":"","sources":["../../../../src/core/security/UserOrgsContext.tsx"],"names":[],"mappings":";AAAA,OAAc,EAAE,aAAa,EAAE,QAAQ,EAAa,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC;AACvH,OAAO,EAGL,gBAAgB,EAChB,kCAAkC,EAClC,qBAAqB,EACrB,4BAA4B,EAC5B,qBAAqB,EAIrB,WAAW,EACX,wBAAwB,EACxB,qBAAqB,EACrB,mBAAmB,GAGpB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,mBAAmB,EAAE,MAAM,wDAAwD,CAAC;AAC7F,OAAO,EAAE,qBAAqB,EAAE,MAAM,6DAA6D,CAAC;AACpG,OAAO,EAAE,WAAW,EAAE,MAAM,6CAA6C,CAAC;AAC1E,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,yDAAyD,CAAC;AAI3G,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACx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uB;QACvB,sBAAsB;QACtB,oBAAoB;QACpB,UAAU;QACV,qBAAqB;KACtB,CAAC,CAAC;IAEH,OAAO,KAAC,eAAe,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,YAAG,QAAQ,GAA4B,CAAC;AACvF,CAAC,CAAC","sourcesContent":["import React, { createContext, useState, ReactNode, useMemo, useEffect, useCallback, useRef, useContext } from 'react';\nimport {\n UserContext,\n OrganizationContext,\n CoreResourceType,\n ResourcesConfig_OperationPathUtils,\n CoreResourceOperation,\n ResourceOperationVariantType,\n OPERATION_VARIANT_KEY,\n ExecutionContext_InitiatorIds,\n UserPrivacy,\n UserPreferences,\n SessionType,\n normalizeConsentPurposes,\n isReadShapedOperation,\n UserSelf_Operations,\n type ConsentPurpose,\n type UserSelfAccessProfile,\n} from '@wildo-ai/saas-models';\nimport { useResourceRegistry } from '~wildo-frontend-lib/core/resources/useResourceRegistry';\nimport { LoggerFrontendService } from '~wildo-frontend-lib/core/monitoring/logger.frontend.service';\nimport { useEventBus } from '~wildo-frontend-lib/core/events/useEventBus';\nimport { FrontendEvents, SessionEndReason } from '~wildo-frontend-lib/core/events/events.frontend.schemas';\nimport {\n EffectivePermissions,\n} from './security.frontend.schemas';\nimport { useAuthSession } from './useAuthSession';\nimport { AuthSessionUtils } from './auth-session.utils';\nimport { accessProfileConfersOrganization, membershipRolesFromAccessProfile } from './effective-permissions.frontend.utils';\nimport { isTransientBackendFailure, sessionEndReasonForRefusal } from '~wildo-frontend-lib/core/requests/auth-refresh-resilience.frontend';\nimport { decodeJwtPayload } from './jwt.frontend.utils';\nimport { useAppScope } from '~wildo-frontend-lib/core/scope/useAppScope';\nimport { useAppScopeInternal } from '~wildo-frontend-lib/core/scope/AppScopeContext';\nimport { ScopeUtilsService } from '~wildo-frontend-lib/core/scope/scope.utils.frontend.service';\nimport { findDefaultApiReadOperation, hasActiveMembershipInOrganization } from './route-organization-access.frontend.utils';\nimport { ScopeChangeInitiator } from '~wildo-frontend-lib/core/scope/scope.frontend.schemas';\nimport { deriveRegionalReaderStanding } from '~wildo-frontend-lib/core/i18n/regional-preference-resolution.frontend.utils';\nimport { RegionalReaderStandingPublisherContext } from '~wildo-frontend-lib/core/i18n/I18nContext';\n\nconst logger: LoggerFrontendService = LoggerFrontendService.getLogger();\nconst logDebug: (message: string, context?: Record<string, unknown>) => void = logger.debugByType('UserOrgsContext');\nlogger.setDebugTypeLogging('UserOrgsContext', false);\n\n/**\n * Session-restore retry backoff bounds (transient backend failures only).\n *\n * On RELOAD, a backend that is recompiling/restarting (dev) or briefly\n * unavailable (prod) makes the session-restore fetch fail transiently. Rather\n * than force a logout — which clears the shared `__wildo_refresh` cookie and\n * drops the user to the login screen — restore preserves the session and\n * retries with exponential backoff until the backend returns. Genuine auth/authz\n * and non-network errors do NOT retry (see `restoreSession`). Backoff caps so a\n * sustained outage settles at one attempt per {@link RESTORE_RETRY_MAX_DELAY_MS}.\n */\nconst RESTORE_RETRY_BASE_DELAY_MS = 1_000;\nconst RESTORE_RETRY_MAX_DELAY_MS = 30_000;\n\n/**\n * User Organizations Context\n * Manages user data, organizations, permissions, and preferences\n * Consumes AuthSessionContext for authentication state\n */\n\nexport interface UserOrgsContextType {\n // Re-exported from AuthSession for backward compatibility\n auth: ReturnType<typeof useAuthSession>['auth'];\n identifyByEmail: ReturnType<typeof useAuthSession>['identifyByEmail'];\n authenticateWithPassword: ReturnType<typeof useAuthSession>['authenticateWithPassword'];\n authenticate: ReturnType<typeof useAuthSession>['authenticate'];\n getSessionState: ReturnType<typeof useAuthSession>['getSessionState'];\n isAuthenticated: ReturnType<typeof useAuthSession>['isAuthenticated'];\n logout: () => void;\n restoreSession: () => Promise<boolean>;\n\n // OAuth2 + cross-frontend-handoff methods (delegated from AuthSession)\n initiateOAuth2Login: ReturnType<typeof useAuthSession>['initiateOAuth2Login'];\n handleAuthCodeExchange: ReturnType<typeof useAuthSession>['handleAuthCodeExchange'];\n\n // User data\n user: UserContext | null;\n\n // Organization data\n organizations: OrganizationContext[];\n currentOrganizationId: string | null;\n permissions: EffectivePermissions | null;\n primaryScopeInitiatorIds: ExecutionContext_InitiatorIds | null;\n\n // Privacy (only preference managed here, others are in their respective contexts)\n privacy: UserPrivacy | null;\n\n // Organization management\n /**\n * The person's own choice of organization (the organization switcher). An organization this session loaded, or one\n * the backend's access profile confers entries in, which the switcher found by search past the user context's first\n * 20 memberships (#2452); that one is loaded on demand. Anything else is refused (logged, nothing changes).\n */\n setCurrentOrganization: (organizationId: string) => void;\n /**\n * Make the organization the current route names the session's current one (#2247). See\n * `RouteOrganizationFollow` for why the route is the authority. Refuses (returns `false`, changes nothing) unless\n * the session can be IN it: an ACTIVE membership the client vouches for (the predicate the route's access verdict\n * uses), or an organization this session loaded (what the switcher offers). Refuses in a one-off session too,\n * whose token the server bound to one organization. Called by `AppLayout_AuthenticatedRoute`.\n */\n followRouteOrganization: (organizationId: string) => boolean;\n getCurrentOrganization: () => OrganizationContext | null;\n refreshOrganizations: () => Promise<void>;\n\n // Privacy getter\n getPrivacy: () => UserPrivacy | null;\n\n /**\n * Record the signed-in person's consent decision: exactly the purposes they granted (#534).\n *\n * The argument is the WHOLE granted set, never a delta — a purpose left out is a purpose not granted,\n * so an unticked box is a withdrawal rather than \"no change\". The write always carries a decision\n * claim, which is what lets \"grant nothing\" be recorded as a decision instead of reading as a person\n * who was never asked; the recorded instant is the server's (`buildConsentDecisionPatch`).\n *\n * Resolves with the stored privacy block once it is in state, so a caller gating on consent (the\n * consent gate) sees the new decision on the next render. Rejects when the application mounts no\n * self-preferences UPDATE door or the write fails — a consent surface must say it could not save,\n * never behave as though it had.\n */\n recordConsentDecision: (grantedPurposes: readonly ConsentPurpose[]) => Promise<UserPrivacy>;\n}\n\n/**\n * UserOrgs Context\n * Exported for use in separate hook file (Fast Refresh compatibility)\n * @internal - Use useUserOrgs() hook instead of accessing this directly\n */\nexport const UserOrgsContext: React.Context<UserOrgsContextType | undefined> = createContext<UserOrgsContextType | undefined>(undefined);\n\nexport const UserOrgsProvider: React.FC<{ children: ReactNode }> = ({ children }) => {\n const { doOperation, registry } = useResourceRegistry();\n const { emit, on } = useEventBus();\n\n // Consume auth session context\n const authSession = useAuthSession();\n const {\n auth,\n tokenStorage,\n identifyByEmail,\n authenticateWithPassword,\n authenticate,\n getSessionState,\n isAuthenticated,\n logout: authLogout,\n endSession,\n getSessionEstablishment,\n getSessionEndReason,\n initiateOAuth2Login,\n handleAuthCodeExchange,\n markSessionRestored,\n setSessionRestoring,\n connectWebSocket,\n } = authSession;\n const appScope = useAppScope();\n const { commitOrganizationScopeValue } = useAppScopeInternal();\n const currentOrganizationId = appScope.currentOrganizationId;\n // Read by `loadOrganizations` at the moment it settles, not when it was created: it awaits network reads.\n const currentOrganizationIdRef = useRef(currentOrganizationId);\n currentOrganizationIdRef.current = currentOrganizationId;\n\n const hasInitializedRef = useRef(false);\n const previousTokenRef = useRef<string | null>(null);\n // Restore-retry lifecycle: `restoreAbortRef` flips true on unmount so an\n // in-flight backoff loop bails instead of touching state on a dead component;\n // `restoreRetryTimerRef` holds the pending backoff timer for cleanup.\n const restoreAbortRef = useRef(false);\n const restoreRetryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const [user, setUser] = useState<UserContext | null>(null);\n // The person loaded now, read by work that settles after an await (an organization loaded on demand, #2275).\n const loadedUserIdRef = useRef<string | null>(null);\n loadedUserIdRef.current = user?._id ?? null;\n\n const [organizations, setOrganizations] = useState<OrganizationContext[]>([]);\n\n const [permissions, setPermissions] = useState<EffectivePermissions | null>(null);\n\n const [privacy, setPrivacy] = useState<UserPrivacy | null>(null);\n /**\n * The latest request that may set the person's preferences in state: `recordConsentDecision`'s write and\n * `refreshOwnPreferences`' read each take a number, and only the latest one applies its answer (#1973 review). Two\n * requests resolving in the reverse order would otherwise let an older grant land after a newer withdrawal and start a\n * consent-based provider again, which is the open direction for a consent control.\n */\n const preferencesRequestRef = useRef(0);\n\n type PreferencesPayload = Pick<UserPreferences, 'languagePreferences' | 'regional' | 'ui' | 'notifications' | 'privacy'>;\n\n /**\n * The TENANT's half of the payload, derived from its preferences record rather than passed\n * alongside it (#410).\n *\n * The organization contributes two things to `I18nContext` — its language policy and its regional\n * defaults — and they are forwarded together because they come from one record. An earlier shape\n * took the language block as its own argument, and when the regional half was added every call\n * site would have had to remember to forward a second one: three sites, one obligation each, and\n * a fourth site tomorrow that forwards neither. Passing the record makes forgetting impossible.\n */\n const organizationPreferencesPayload = (\n organizationPreferences: OrganizationContext['preferences'] | null | undefined,\n ): Record<string, unknown> => {\n if (organizationPreferences === undefined) {\n return {};\n }\n if (organizationPreferences === null) {\n return { organizationLanguagePreferences: null, organizationRegionalPreferences: null };\n }\n return {\n organizationLanguagePreferences: organizationPreferences.languagePreferences ?? null,\n organizationRegionalPreferences: {\n timezone: organizationPreferences.timezone,\n locale: organizationPreferences.locale,\n dateFormat: organizationPreferences.dateFormat,\n timeFormat: organizationPreferences.timeFormat,\n },\n };\n };\n\n const emitPreferencesChanged = useCallback((\n preferences: PreferencesPayload | null | undefined,\n organizationPreferences?: OrganizationContext['preferences'] | null,\n ): void => {\n if (preferences === null) {\n emit(FrontendEvents.USER_PREFERENCES_CHANGED, {\n languagePreferences: null,\n organizationLanguagePreferences: null,\n regionalPreferences: null,\n organizationRegionalPreferences: null,\n notificationsPreferences: null,\n uiPreferences: null,\n privacy: null,\n });\n return;\n }\n\n emit(FrontendEvents.USER_PREFERENCES_CHANGED, {\n ...(preferences?.languagePreferences !== undefined ? { languagePreferences: preferences.languagePreferences } : {}),\n ...organizationPreferencesPayload(organizationPreferences),\n ...(preferences?.regional !== undefined ? { regionalPreferences: preferences.regional } : {}),\n ...(preferences?.notifications !== undefined ? { notificationsPreferences: preferences.notifications } : {}),\n ...(preferences?.ui !== undefined ? { uiPreferences: preferences.ui } : {}),\n ...(preferences?.privacy !== undefined ? { privacy: preferences.privacy } : {}),\n });\n }, [emit]);\n\n /*\n * `USER_LOGIN` / `USER_LOGOUT` — announced HERE, once per transition of the known person (#1977).\n *\n * Nothing emitted them before, so every listener — error-report attribution, analytics identify and\n * reset, the sign-in and sign-out analytics events — was dead code that read as if sign-in were\n * observed. This is the one place every sign-in method and every way a session ends converge: each\n * authentication stores a token, the auto-load effect below restores the user from it, and every\n * sign-out, refused refresh, failed restore and cross-tab sign-out clears the token, which clears the\n * user. Emitting at each auth method instead would be a dozen call sites, and the next method added\n * would be the one that forgot. Declared BEFORE the preferences effect, because effects run in\n * declaration order and a person's arrival must precede their preferences.\n *\n * The id last announced is the guard, so a re-render, a preferences write that replaces the user\n * object, or StrictMode re-running an effect announces nothing, and a direct switch from one person to\n * another announces the first one's departure before the second one's arrival. HOW the session began\n * and WHY it ended are recorded by `AuthSessionProvider`, the only code that knows, and read at the\n * moment of announcing.\n *\n * A DEPARTURE is announced by the two places that clear the user, BEFORE they publish `privacy: null`:\n * a listener that must act while the person's consent still holds (the sign-out analytics event, sent\n * before the destinations are reset) needs the announcement first, and the consent-based providers\n * stop on the `privacy: null` that follows. The effect announces ARRIVALS, and a departure only as a\n * backstop for a path that cleared the user without announcing. An unmount announces nothing: the\n * provider going away is not the person signing out.\n */\n const announcedUserIdRef = useRef<string | null>(null);\n const announceDeparture = useCallback((reason: SessionEndReason): void => {\n const departedUserId = announcedUserIdRef.current;\n if (departedUserId === null) return;\n announcedUserIdRef.current = null;\n emit(FrontendEvents.USER_LOGOUT, { userId: departedUserId, reason });\n }, [emit]);\n const knownUserId = user?._id ?? null;\n useEffect(() => {\n const previousUserId = announcedUserIdRef.current;\n if (previousUserId === knownUserId) return;\n if (previousUserId !== null && knownUserId !== null) {\n /*\n * One person REPLACED by another with no sign-out between them. Believed unreachable today: a sign-in\n * while someone is loaded sets `isRestoringSession` with `hasInitializedRef` already true, so the\n * auto-load effect below skips it, and `restoreSession` returns early while a user is loaded. Handled\n * anyway, because the consequence of getting it wrong is the next person's analytics running under\n * the previous person's consent: the departure is followed by the same `privacy: null` a sign-out\n * publishes, BEFORE the arrival, so the next person is judged on their own preferences, which the\n * preferences effect below publishes after this one.\n */\n announceDeparture(SessionEndReason.REPLACED);\n setPrivacy(null);\n emitPreferencesChanged(null);\n } else if (previousUserId !== null) {\n announceDeparture(getSessionEndReason());\n }\n if (knownUserId !== null) {\n announcedUserIdRef.current = knownUserId;\n emit(FrontendEvents.USER_LOGIN, { userId: knownUserId, establishment: getSessionEstablishment() });\n }\n }, [knownUserId, emit, announceDeparture, emitPreferencesChanged, getSessionEndReason, getSessionEstablishment]);\n\n const primaryScopeInitiatorIds = useMemo<ExecutionContext_InitiatorIds | null>(() => {\n return ScopeUtilsService.buildInitiatorIds({\n userId: appScope.currentUserId,\n organizationId: appScope.currentOrganizationId,\n applicationId: appScope.currentApplicationId,\n anonymousUserId: appScope.currentAnonymousUserId,\n });\n }, [\n appScope.currentApplicationId,\n appScope.currentAnonymousUserId,\n appScope.currentOrganizationId,\n appScope.currentUserId,\n ]);\n\n /**\n * Extract and store user preferences from context\n * Stores preferences in state for other contexts to read and apply\n */\n const storePreferences = useCallback((\n preferences: PreferencesPayload,\n organizationPreferences?: OrganizationContext['preferences'] | null,\n ): void => {\n // Store privacy preferences in state\n if (preferences.privacy) {\n setPrivacy(preferences.privacy);\n }\n\n const currentOrganizationPreferences = organizationPreferences !== undefined\n ? organizationPreferences\n : currentOrganizationId\n ? organizations.find((organization) => organization._id === currentOrganizationId)?.preferences\n : undefined;\n\n // Emit preference change event to notify parent contexts\n emitPreferencesChanged(\n preferences,\n currentOrganizationPreferences,\n );\n }, [currentOrganizationId, emitPreferencesChanged, organizations]);\n\n /**\n * The caller's access profile (`user-self | access_profile`, #2381) — the role entries the backend authorizes this\n * person with, unit and relationship grants included, and which resources narrow by unit. The shell's\n * visibility decisions read it (`viewerMayPerformOperation`). `null` when the operation is absent or the read fails.\n *\n * The route names no user: the backend answers from the request's own execution context, so it can only ever describe\n * the person asking (`GET /user-self/access-profile/count`).\n */\n const loadAccessProfile = async (): Promise<UserSelfAccessProfile | null> => {\n const userSelfConfig = registry.resourceConfigurations[CoreResourceType.USER_SELF];\n const accessProfileOperation = userSelfConfig?.operations.find((op: any) =>\n op.operationIdentifier === UserSelf_Operations.ACCESS_PROFILE &&\n op.variantType === ResourceOperationVariantType.API_CALL &&\n op.isBulkOperation !== true\n );\n if (!accessProfileOperation) return null;\n try {\n const operationPath = ResourcesConfig_OperationPathUtils.buildOperationPathKeyFromOperation(accessProfileOperation);\n return (await doOperation<UserSelfAccessProfile>(operationPath, { contextualParameters: {} })) ?? null;\n } catch (error) {\n logger.warn('Access profile could not be loaded; entries reached only through an organization-unit grant stay hidden', { error });\n return null;\n }\n };\n\n /**\n * Compute effective permissions from user's app roles and organization roles\n * This is a basic implementation - can be enhanced based on role hierarchy\n */\n const computeEffectivePermissions = (\n userContext: UserContext,\n organizationsList: OrganizationContext[]\n ): EffectivePermissions | null => {\n // App-level permissions from user's app roles\n const appLevel = (userContext.appRoles || []) as string[];\n\n // Per-organization permissions from organization membership roles\n // Use new field name from relationship-based context\n const organizationsPermissions: Record<string, string[]> = {};\n const memberships = userContext.organizationMembers || [];\n\n for (const membership of memberships) {\n organizationsPermissions[membership.organizationId] = (membership.roles || []) as string[];\n }\n\n return {\n appLevel,\n organizations: organizationsPermissions,\n accessProfile: null,\n };\n };\n\n /**\n * One of the person's own organizations, as the session holds it: the organization READ and, beside it, the tenant's\n * preference record. `null` when the organization cannot be read (a refusal, a transient failure, no READ mounted).\n *\n * Shared by `loadOrganizations` (the memberships the user context carries) and by the organizations loaded ON\n * DEMAND (#2275): a membership past the user context's cap that the session follows or starts in. Both must hold\n * the organization the same way, or the switcher and the i18n preferences would differ by how it arrived.\n */\n const fetchOwnOrganization = useCallback(async (organizationId: string): Promise<OrganizationContext | null> => {\n const organizationsConfig = registry.resourceConfigurations[CoreResourceType.ORGANIZATIONS];\n if (!organizationsConfig) {\n logger.warn('ORGANIZATIONS resource not available');\n return null;\n }\n // Shared with the route organization-access probe, which must address the same READ.\n const orgsReadOp = findDefaultApiReadOperation(organizationsConfig);\n if (!orgsReadOp) {\n logger.warn('ORGANIZATIONS READ operation not found');\n return null;\n }\n const organizationsOperationPath = ResourcesConfig_OperationPathUtils.buildOperationPathKeyFromOperation(orgsReadOp);\n\n /**\n * The tenant's preference record is fetched SEPARATELY, and that is a decision rather than an\n * omission (#563).\n *\n * `OrganizationContextSchema` declares `preferences`, and `doOperation<OrganizationContext>`\n * is a CAST — nothing validates the response against it — so the field read as available\n * while no producer existed: the ORGANIZATIONS **default** READ returns a plain\n * `Organization`, and the organisation's regional block therefore never reached\n * `I18nContext`. Every date and number in every generated application formatted at the\n * framework floor as a result.\n *\n * The rejected alternative was to switch this call to the ORGANIZATIONS **context** variant,\n * which does populate the child. Measured against the running stack on 2026-09-10, that\n * response carries every context-enabled child of an organisation — `auditLogs`, `todos`,\n * `tasks`, `knowledgeDocuments`, `organizationMembers`, … — so session restore would pull an\n * unbounded page of tenant data per membership to obtain four regional fields. (#583 has since\n * taken the audit and delivery logs off the context surface and capped every 1:many child at\n * `contextPolicy.limit`, 20 by default. The page is bounded now, but it is still a page of tenant\n * data per membership, so the reasoning stands.) The\n * preference record has its own default READ (`GET /organizations/{id}/organization-preference`,\n * reachable by an ordinary `ORG_MEMBER`), which is one small request with a stable shape.\n *\n * Best-effort by construction: a tenant whose preferences cannot be read still yields a\n * usable organisation, and `organizationPreferencesPayload(undefined)` then contributes\n * nothing to the i18n event rather than clearing the member's own settings.\n */\n const organizationPreferencesReadOp = findDefaultApiReadOperation(registry.resourceConfigurations[CoreResourceType.ORGANIZATION_PREFERENCES]);\n const fetchOrganizationPreferences = async (): Promise<OrganizationContext['preferences'] | undefined> => {\n // Absent READ: reported once per list load by `loadOrganizations`, not once per organization.\n if (!organizationPreferencesReadOp) return undefined;\n try {\n return await doOperation<NonNullable<OrganizationContext['preferences']>>(\n ResourcesConfig_OperationPathUtils.buildOperationPathKeyFromOperation(organizationPreferencesReadOp),\n { contextualParameters: { organizationId } },\n ) ?? undefined;\n } catch (error) {\n logger.warn('Failed to fetch organization preferences', { organizationId, error });\n return undefined;\n }\n };\n\n try {\n const [org, preferences] = await Promise.all([\n doOperation<OrganizationContext>(organizationsOperationPath, { contextualParameters: { organizationId } }),\n fetchOrganizationPreferences(),\n ]);\n if (!org) return null;\n // OMIT the key when the read failed rather than attaching `null`. The payload builder\n // reads the two differently: `undefined`/absent contributes nothing to the i18n event,\n // while `null` means \"the tenant has cleared its preferences\" and actively resets the\n // organisation half — which would silently downgrade a member to the framework floor\n // because one request failed.\n return preferences ? { ...org, preferences } : org;\n } catch (error) {\n logger.warn('Failed to fetch organization', { organizationId, error });\n return null;\n }\n }, [doOperation, registry]);\n\n /**\n * Load one of the person's own organizations the session does not hold yet, and add it to `organizations` (#2275,\n * #2452): one followed by route, or one the switcher found by search past the user context's first 20 memberships.\n * One path for both, so an organization arrives the same way whichever door admitted it. A sign-out or another\n * person's sign-in while the read was in flight must not receive this person's organization.\n */\n const loadOrganizationOnDemand = useCallback((organizationId: string): void => {\n const requestingUserId = loadedUserIdRef.current;\n void fetchOwnOrganization(organizationId).then((organization) => {\n if (!organization || loadedUserIdRef.current !== requestingUserId) return;\n setOrganizations((previous) => previous.some((existing) => existing._id === organization._id) ? previous : [...previous, organization]);\n });\n }, [fetchOwnOrganization]);\n\n /**\n * Load organizations independently (can be called separately from authentication)\n */\n const loadOrganizations = useCallback(async (userContext: UserContext): Promise<{\n organizationsList: OrganizationContext[];\n selectedOrgId: string | null;\n }> => {\n // The backend's own account of this person's access (#2381), fetched beside the organizations rather than after\n // them. Best-effort: a failure leaves the shell deciding on membership roles alone (unit-granted entries hidden).\n const accessProfilePromise = loadAccessProfile();\n const allMemberships = userContext.organizationMembers || [];\n\n // W7.3b: For one-off sessions, restrict to the scoped organization only\n const scopedOrgId = auth.sessionType === SessionType.ONE_OFF\n ? tokenStorage.getOrganizationId()\n : null;\n\n const memberships = scopedOrgId\n ? allMemberships.filter((m: any) => m.organizationId === scopedOrgId)\n : allMemberships;\n\n logDebug('Loading organizations', {\n userId: userContext._id,\n membershipCount: memberships.length,\n isOneOff: auth.sessionType === SessionType.ONE_OFF,\n });\n\n if (!findDefaultApiReadOperation(registry.resourceConfigurations[CoreResourceType.ORGANIZATION_PREFERENCES])) {\n logger.warn('ORGANIZATION_PREFERENCES READ operation not found — tenant regional defaults will not be applied');\n }\n const organizationsList: OrganizationContext[] = [];\n const membershipOrganizationResults = await Promise.all(\n memberships.map((membership: any) => fetchOwnOrganization(String(membership.organizationId))),\n );\n organizationsList.push(...membershipOrganizationResults.filter((org): org is OrganizationContext => org !== null));\n\n // Keep the organization this tab is IN when it is still one of the person's (#2247): a reload of the list\n // (`refreshOrganizations`, e.g. after accepting an invitation) must not move the tab. The stored value is\n // shared by every tab and follows each tab's route, so reading it here would pull this tab into whatever\n // organization another tab last opened, and the switch would send it home. The stored value is the default a\n // session STARTS from (during restore AppScope exposes no organization yet, so it is the one used), then the\n // first organization.\n const tabOrgId = currentOrganizationIdRef.current;\n const storedOrgId = tokenStorage.getOrganizationId();\n const isLoaded = (organizationId: string | null): organizationId is string =>\n !!organizationId && organizationsList.some(o => o._id === organizationId);\n const accessProfile = await accessProfilePromise;\n\n // The organization the tab is in, or the session starts from, may be one the user context does not carry: its\n // `organizationMembers` holds only the newest 20 memberships (#2275), and since #2247 the tab's and the stored\n // organization follow the route, so they are often one past that cap. When the backend's access profile confers\n // entries there, it is one of the person's own and is loaded on demand like the others; without that, a reload\n // of the list would move the tab out of the organization its page names, and a new session would never start\n // where the person last was. In a one-off session only the organization its token is bound to is ever loaded.\n const preferredOrgId = tabOrgId ?? storedOrgId;\n if (\n preferredOrgId\n && !isLoaded(preferredOrgId)\n && (!scopedOrgId || preferredOrgId === scopedOrgId)\n && accessProfileConfersOrganization(accessProfile, preferredOrgId)\n ) {\n const preferredOrganization = await fetchOwnOrganization(preferredOrgId);\n if (preferredOrganization) organizationsList.push(preferredOrganization);\n }\n\n const selectedOrgId = isLoaded(tabOrgId)\n ? tabOrgId\n : isLoaded(storedOrgId)\n ? storedOrgId\n : organizationsList[0]?._id || null;\n\n // Compute effective permissions. With the backend's access profile, the roles are the ones the backend confers\n // (`membershipRolesFromAccessProfile`); without it, the membership rows decide, as before.\n const membershipPermissions = computeEffectivePermissions(userContext, organizationsList);\n const computedPermissions = membershipPermissions\n ? { ...membershipPermissions, ...(accessProfile ? membershipRolesFromAccessProfile(accessProfile) : {}), accessProfile }\n : null;\n\n setOrganizations(organizationsList);\n commitOrganizationScopeValue(selectedOrgId);\n setPermissions(computedPermissions);\n\n logDebug('Organizations loaded', { organizationCount: organizationsList.length, currentOrganizationId: selectedOrgId });\n return { organizationsList, selectedOrgId };\n }, [commitOrganizationScopeValue, fetchOwnOrganization, registry, tokenStorage, auth.sessionType]);\n\n /**\n * Restore regular user session\n */\n const restoreUserSession = useCallback(async (accessToken: string): Promise<boolean> => {\n logDebug('Restoring user session');\n\n // Check if USER_SELF is available\n const availableResources = Object.keys(registry.resourceConfigurations);\n const hasUserSelf = availableResources.includes(CoreResourceType.USER_SELF);\n\n if (!hasUserSelf) {\n logger.warn('USER_SELF resource not available for session restoration');\n return false;\n }\n\n // Get USER_SELF resource config\n const userSelfConfig = registry.resourceConfigurations[CoreResourceType.USER_SELF];\n\n const readOperation = findDefaultApiReadOperation(userSelfConfig);\n\n if (!readOperation) {\n logger.warn('USER_SELF READ operation not found');\n return false;\n }\n\n // Find context variant (auto-generated with relationship population)\n const readContextOp = userSelfConfig.operations.find((op: any) =>\n op.operationIdentifier === CoreResourceOperation.READ &&\n op.isBulkOperation !== true &&\n op.variantType === ResourceOperationVariantType.API_CALL &&\n op.variantKey === OPERATION_VARIANT_KEY.CONTEXT\n );\n\n if (!readContextOp) {\n logger.warn('USER_SELF context variant not found');\n return false;\n }\n\n const initiatorInfo = readOperation.initiatorInfos?.[0];\n const requiresUserId = initiatorInfo?.parameters?.some((p: any) => p.fieldIdentifier === 'userId');\n\n const contextualParameters: Record<string, string> = {};\n\n if (requiresUserId && accessToken) {\n try {\n const payload = decodeJwtPayload<{ userId?: string }>(accessToken);\n if (payload.userId) {\n contextualParameters.userId = payload.userId;\n }\n } catch (e) {\n logDebug('Failed to decode JWT for userId extraction', { error: e });\n }\n }\n\n // Build operation path and fetch user context\n const contextPath = ResourcesConfig_OperationPathUtils.buildOperationPathKeyFromOperation(readContextOp);\n const userContext = await doOperation<UserContext>(contextPath, { contextualParameters });\n\n if (!userContext) {\n logger.warn('Failed to fetch user context during session restoration');\n return false;\n }\n\n // Use new field name from relationship-based context\n const membershipsCount = (userContext.organizationMembers || []).length;\n logDebug('User context restored', { userId: userContext._id, organizationCount: membershipsCount });\n\n // Update user state\n setUser(userContext);\n\n // Load organizations separately\n // If this fails, session restoration still succeeds (user context is restored)\n const { organizationsList, selectedOrgId } = await loadOrganizations(userContext);\n\n // Store preferences after organization loading so i18n receives user and\n // active-organization language policy in the same event.\n const preferences = userContext.userSelfPreferences;\n if (preferences) {\n const currentOrganization = selectedOrgId\n ? organizationsList.find((organization) => organization._id === selectedOrgId)\n : null;\n storePreferences(preferences, currentOrganization?.preferences);\n }\n\n logger.info('Session restored successfully', {\n userId: userContext._id,\n organizationCount: membershipsCount\n });\n\n return true;\n }, [doOperation, registry, loadOrganizations, storePreferences]);\n\n // Stop any pending restore-retry backoff when the provider unmounts, so the\n // loop in `restoreSession` bails instead of calling setState on a dead tree.\n useEffect(() => {\n restoreAbortRef.current = false;\n return () => {\n restoreAbortRef.current = true;\n if (restoreRetryTimerRef.current) {\n clearTimeout(restoreRetryTimerRef.current);\n restoreRetryTimerRef.current = null;\n }\n };\n }, []);\n\n /**\n * Restore session from stored JWT token\n * Fetches user context using USER_SELF resource (userId comes from JWT)\n * Then fetches full organization details for each organization membership\n *\n * Resilience: a TRANSIENT backend failure (unreachable / 5xx / timeout, or a\n * 401 whose in-flight renewal failed transiently) does NOT log out — restore\n * preserves the session and retries with capped exponential backoff until the\n * backend returns. Genuine authentication (401), authorization (403), and\n * non-network errors terminate immediately (no retry on a dead-or-buggy path).\n */\n const runSessionRestore = useCallback(async (): Promise<boolean> => {\n logDebug('Restoring session from stored token');\n\n // Check if session is already restored to avoid duplicate restoration attempts\n if (auth.sessionRestored && auth.accessToken && user) {\n logDebug('Session already restored, skipping restoration');\n return true;\n }\n\n // Read token from auth state\n const accessToken = auth.accessToken;\n\n if (!accessToken) {\n logDebug('No access token available');\n return false;\n }\n\n setSessionRestoring(true);\n\n let attempt = 0;\n // Single backoff loop: the invoking effect won't re-enter while\n // `isRestoringSession` is true, so this is the sole restore in flight.\n while (true) {\n try {\n const restored = await restoreUserSession(accessToken);\n\n if (restored) {\n markSessionRestored();\n\n // W7.3b: One-off sessions already connected WebSocket in handleOneOffTokenExchange\n // (with consumableToken). Reconnecting here would lose the consumable token.\n if (auth.sessionType !== SessionType.ONE_OFF) {\n // Connect with the FRESHEST token, read live from storage — NOT the\n // `accessToken` captured at the top of `restoreSession`. During the\n // awaited `restoreUserSession` above, the HTTP interceptor may have\n // hit a `401 OUTDATED_AUTH_JWT` and rotated the token via\n // `tokenRenewalHandler` (which writes the new token to storage AND\n // seeds the WS `authStateRef` synchronously). The captured\n // `accessToken` is then stale/expired; passing it into `connect()`\n // reseeds the WS credential source-of-truth back to the expired token\n // (clobbering the fresh one the refresh just stored), and the Socket.IO\n // handshake gets rejected with \"Authentication failed\". `getAccessToken()`\n // returns the live, post-refresh value (falling back to the captured\n // token only if storage is somehow empty).\n const freshestAccessToken = tokenStorage.getAccessToken() ?? accessToken;\n connectWebSocket(freshestAccessToken, tokenStorage.getOrganizationId());\n }\n } else {\n logger.warn('Session restoration could not build a valid authenticated context; logging out to avoid a half-restored state');\n endSession(SessionEndReason.SESSION_ENDED);\n }\n\n return restored;\n\n } catch (error: any) {\n // Authorization (403 / scope) is checked FIRST and is non-destructive: a\n // permission denial must NEVER destroy a valid session. Authentication\n // (401 / session-invalid) is the only branch that force-logs-out.\n // `isAuthenticationError` already excludes authorization errors (see\n // `AuthSessionUtils`), so these are mutually exclusive — the explicit\n // ordering here is defense-in-depth so the non-destructive path wins even\n // if that guard is ever loosened.\n const isAuthorizationError = AuthSessionUtils.isAuthorizationError(error);\n\n if (isAuthorizationError) {\n const errorMessage = error?.message || 'Session restoration blocked by authorization';\n logger.warn('Session restoration encountered authorization/scope error', {\n error: errorMessage,\n errorType: error?.wildoError?.type || error?.response?.data?.error?.type,\n status: error?.response?.status,\n });\n setSessionRestoring(false);\n markSessionRestored();\n return false;\n }\n\n // TRANSIENT backend failure (checked BEFORE the authentication branch so\n // a 401 whose renewal failed transiently is retried, not logged out):\n // preserve the session, back off, and retry. Bail if the component\n // unmounted or the session was cleared (logout elsewhere) while waiting.\n if (isTransientBackendFailure(error)) {\n attempt += 1;\n const delay = Math.min(\n RESTORE_RETRY_BASE_DELAY_MS * 2 ** (attempt - 1),\n RESTORE_RETRY_MAX_DELAY_MS,\n );\n logger.warn('Session restoration hit a transient backend failure; preserving session and retrying', {\n attempt,\n retryInMs: delay,\n status: error?.response?.status,\n code: error?.code,\n });\n await new Promise<void>((resolve) => {\n restoreRetryTimerRef.current = setTimeout(resolve, delay);\n });\n if (restoreAbortRef.current || !tokenStorage.getAccessToken()) {\n setSessionRestoring(false);\n return false;\n }\n continue;\n }\n\n if (AuthSessionUtils.isAuthenticationError(error)) {\n logDebug('Session restoration failed due to authentication error', {\n errorType: error?.wildoError?.type || error?.response?.data?.error?.type,\n status: error?.response?.status,\n });\n // Usually the refresh already ended it, naming why; when restore is first, it reads the refusal itself.\n endSession(sessionEndReasonForRefusal(error));\n return false;\n }\n\n // Fail closed on unexpected NON-transient errors. A partially restored\n // authenticated shell is less safe than dropping back to a clean login.\n const errorMessage = error?.message || 'Session restoration failed';\n logger.warn('Session restoration encountered a non-transient error; logging out', {\n error: errorMessage,\n errorType: error?.wildoError?.type,\n });\n\n endSession(SessionEndReason.SESSION_ENDED);\n return false;\n }\n }\n }, [\n restoreUserSession,\n auth.sessionRestored,\n auth.sessionType,\n auth.accessToken,\n user,\n endSession,\n markSessionRestored,\n setSessionRestoring,\n connectWebSocket,\n tokenStorage\n ]);\n\n /**\n * The access token the last restore CONCLUDED for, whatever its outcome (#2242).\n *\n * \"A token and no user\" is two different states, and the reader standing must tell them apart: before a\n * restore has run for this token (every returning visitor's first render, and a one-off session, which\n * starts with `sessionRestored: true` and no user) it is UNSETTLED; after a restore concluded without a\n * user (the authorization-error branch keeps the token) it is settled with no person. Neither\n * `isRestoringSession` nor `sessionRestored` says which — so the restore records it. Keyed by the token\n * LIVE at the end, since a restore may rotate it mid-flight.\n */\n const [restoreConcludedForToken, setRestoreConcludedForToken] = useState<string | null>(null);\n const restoreSession = useCallback(async (): Promise<boolean> => {\n try {\n return await runSessionRestore();\n } finally {\n const settledToken = tokenStorage.getAccessToken();\n if (settledToken) setRestoreConcludedForToken(settledToken);\n }\n }, [runSessionRestore, tokenStorage]);\n\n /**\n * Refresh organizations data (e.g., after organization update)\n */\n const refreshOrganizations = useCallback(async (): Promise<void> => {\n // Use new field name from relationship-based context\n const memberships = user?.organizationMembers || [];\n\n if (memberships.length === 0) {\n logDebug('No organizations membership to refresh');\n return;\n }\n\n logDebug('Refreshing organizations', { membershipCount: memberships.length });\n\n // Use loadOrganizations to refresh\n await loadOrganizations(user!);\n }, [user, loadOrganizations]);\n\n useEffect(() => {\n if (!user?.userSelfPreferences) {\n return;\n }\n\n const currentOrganization = currentOrganizationId\n ? organizations.find((organization) => organization._id === currentOrganizationId)\n : null;\n\n emitPreferencesChanged(\n user.userSelfPreferences,\n currentOrganization?.preferences,\n );\n }, [currentOrganizationId, emitPreferencesChanged, organizations, user]);\n\n /*\n * Whether anybody is reading, published to `I18nContext` (#2242). It mounts above this provider, so a null\n * member and a null organization are all it can see — the same for an anonymous visitor as for a member\n * being restored, and only the first should have the browser stand in for their preferences.\n *\n * Through `RegionalReaderStandingPublisherContext`, never the bus: `I18nProvider` is our ancestor, so its\n * bus subscription is made AFTER our mount effect runs, and an emission there is lost (see the context's\n * JSDoc). ONE effect, deriving from the session rather than riding each preference emission above: every\n * way a session starts or ends changes one of these inputs, so none can forget to say it. Declared AFTER\n * the preferences effect so a member's SIGNED_IN follows their preferences in the same commit; the restore\n * path stores them before `isRestoringSession` clears, so it is ordered by the derivation itself.\n */\n const publishRegionalReaderStanding = useContext(RegionalReaderStandingPublisherContext);\n const regionalReaderStanding = deriveRegionalReaderStanding({\n isRestoringSession: auth.isRestoringSession,\n hasUser: user !== null,\n hasAccessToken: Boolean(auth.accessToken),\n restoreConcludedForAccessToken: Boolean(auth.accessToken) && restoreConcludedForToken === auth.accessToken,\n });\n useEffect(() => {\n publishRegionalReaderStanding?.(regionalReaderStanding);\n }, [publishRegionalReaderStanding, regionalReaderStanding]);\n\n /**\n * Set the current active organization\n */\n const setCurrentOrganization = useCallback((organizationId: string): void => {\n const org = organizations.find(o => o._id === organizationId);\n // An organization the switcher FOUND by search rather than one it loaded (#2452): past the user context's first\n // 20 memberships. Admitted on the same fact `followRouteOrganization` admits it on — the backend's access profile\n // confers entries there — and loaded on demand like a followed one, so the switcher and the tenant's preferences\n // hold it the same way. Never in a one-off session, whose token the server bound to one organization.\n const conferred = !org\n && auth.sessionType !== SessionType.ONE_OFF\n && accessProfileConfersOrganization(permissions?.accessProfile, organizationId);\n if (!org && !conferred) {\n logger.warn('Attempted to set invalid organization', { organizationId, availableOrganizations: organizations.map(o => o._id) });\n return;\n }\n if (conferred) loadOrganizationOnDemand(organizationId);\n\n const previousOrganizationId = currentOrganizationId;\n\n // Skip if the organization hasn't changed\n if (previousOrganizationId === organizationId) {\n return;\n }\n\n logDebug('Setting current organization', { organizationId, organizationName: org?.name, previousOrganizationId, loadedOnDemand: conferred });\n commitOrganizationScopeValue(organizationId, ScopeChangeInitiator.USER_SELECTION);\n }, [auth.sessionType, organizations, permissions, currentOrganizationId, commitOrganizationScopeValue, loadOrganizationOnDemand]);\n\n /**\n * Follow the organization the route names (#2247).\n *\n * Three facts admit it, matching the route verdicts the follow acts on. An ACTIVE membership the client vouches for\n * is what `ACTIVE_MEMBERSHIP` rests on, so the two cannot disagree. An organization in `organizations` is one this\n * session loaded from its own memberships and offers in the switcher; it is what admits a representative member\n * (#1597), whose membership the client deliberately never vouches for and the server `ADMITTED`. An organization the\n * backend's access profile confers entries in is a membership past the user context's cap of 20 (#2275), which the\n * server also `ADMITTED`: it is loaded on demand, so the switcher and the tenant's preferences hold the organization\n * the person is in. Anything else — a platform operator's crossing, a foreign organization — is refused.\n *\n * The commit does not wait for that load. The roles the page is judged by come from the access profile, which is\n * already held, and holding the route's content until a second read lands would only delay a page that can render.\n */\n const followRouteOrganization = useCallback((organizationId: string): boolean => {\n if (auth.sessionType === SessionType.ONE_OFF) {\n return false;\n }\n const loaded = organizations.some((organization) => organization._id === organizationId);\n const conferred = accessProfileConfersOrganization(permissions?.accessProfile, organizationId);\n const sessionCanBeIn = hasActiveMembershipInOrganization(user?.organizationMembers, organizationId) || loaded || conferred;\n if (!sessionCanBeIn) {\n logger.warn('Refused to follow a route organization this session cannot be in', { organizationId });\n return false;\n }\n if (!loaded) loadOrganizationOnDemand(organizationId);\n if (currentOrganizationId !== organizationId) {\n logDebug('Following the route organization', { organizationId, previousOrganizationId: currentOrganizationId });\n commitOrganizationScopeValue(organizationId, ScopeChangeInitiator.ROUTER);\n }\n return true;\n }, [auth.sessionType, user, organizations, permissions, currentOrganizationId, commitOrganizationScopeValue, loadOrganizationOnDemand]);\n\n /**\n * Get the current active organization\n */\n const getCurrentOrganization = useCallback((): OrganizationContext | null => {\n if (!currentOrganizationId) {\n return null;\n }\n return organizations.find(o => o._id === currentOrganizationId) || null;\n }, [currentOrganizationId, organizations]);\n\n /**\n * Get privacy preferences\n */\n const getPrivacy = useCallback((): UserPrivacy | null => {\n return privacy;\n }, [privacy]);\n\n // Depend on the builder alone: the whole AppScope value changes with every custom scope value, and through\n // this callback it would re-render every `useUserOrgs` consumer.\n const buildScopeContextualParameters = appScope.buildContextualParameters;\n const recordConsentDecision = useCallback(async (grantedPurposes: readonly ConsentPurpose[]): Promise<UserPrivacy> => {\n const request = ++preferencesRequestRef.current;\n const operation = registry.resourceConfigurations[CoreResourceType.USER_SELF_PREFERENCES]?.operations.find(\n (candidate) => candidate.operationIdentifier === CoreResourceOperation.UPDATE\n && candidate.isOperationDefault === true\n && candidate.isBulkOperation !== true\n && (\n candidate.variantType === ResourceOperationVariantType.API_CALL\n ),\n );\n if (!operation) {\n throw new Error('Cannot record a consent decision: this application mounts no user self-preferences UPDATE operation');\n }\n\n const updated = await doOperation<UserPreferences>(\n ResourcesConfig_OperationPathUtils.buildOperationPathKeyFromOperation(operation),\n {\n // This provider sits ABOVE `ScopedResourceRegistryProvider`, so the `doOperation` it holds injects\n // no scope: the user id the self-preferences route is addressed by has to be supplied here. With an\n // empty set the client could not build the URL and every decision failed before a request left\n // (`frontend_resource_no_endpoint_available`, #977 — found by driving the prompt in a browser).\n contextualParameters: buildScopeContextualParameters(),\n requestData: {\n // The client instant is only a CLAIM that this write is a decision; the server replaces it.\n privacy: { consentedPurposes: normalizeConsentPurposes(grantedPurposes), consentDecidedAt: new Date() },\n },\n },\n );\n const storedPrivacy = updated?.privacy;\n if (!storedPrivacy) {\n throw new Error('Consent decision was written but the response carried no privacy block');\n }\n // A later preferences request owns the STATE (see `preferencesRequestRef`); this decision is stored all the same, is\n // returned to its caller, and still re-loads the organizations below, which do not depend on who owns the state.\n if (request === preferencesRequestRef.current) {\n setPrivacy(storedPrivacy);\n // Updating the user's preferences record re-emits USER_PREFERENCES_CHANGED through the effect\n // above, which is how the analytics provider learns the new set without a second channel.\n setUser((previous) => previous\n ? { ...previous, userSelfPreferences: { ...(previous.userSelfPreferences ?? {}), privacy: storedPrivacy } as UserContext['userSelfPreferences'] }\n : previous);\n }\n // While a required purpose was missing the backend refused this person's organization reads, so\n // session restore may have loaded none (#534 re-review N1). Re-load them now that the decision is\n // stored; a failure leaves the decision recorded and is retried on the next restore.\n if (organizations.length === 0) {\n await refreshOrganizations().catch((error: unknown) => {\n logger.warn('Organizations could not be re-loaded after a consent decision', { error });\n });\n }\n return storedPrivacy;\n }, [buildScopeContextualParameters, doOperation, registry, organizations.length, refreshOrganizations]);\n\n /**\n * Take in the person's own preferences after a write made by a surface OTHER than `recordConsentDecision` (#1973).\n *\n * The Preferences page is the generic resource form over `userSelfPreferences`, and it writes through the ordinary\n * UPDATE, not through this provider. Until this existed nothing told the provider about that write, so `privacy`\n * kept the value the page loaded with: an ANALYTICS grant made there did not start the consent-based providers\n * (`ConsentBasedProviderSdksProvider` reads `privacy` through `useGrantedConsentPurposes`), and a WITHDRAWAL did not\n * stop a provider already running, which kept capturing and kept its browser storage until a reload or a sign-out.\n * Measured in a real browser against Wonder Todos with PostHog, 2026-11-16.\n *\n * The record is READ again rather than taken from the event: the event carries the operation, not the stored row,\n * and the server's answer is what decided (`consentDecidedAt` is the server's instant, never the client's claim). The\n * same two updates `recordConsentDecision` makes then follow: `privacy`, and the person's preferences, whose effect\n * re-emits `USER_PREFERENCES_CHANGED` to the language, regional and theme contexts too.\n */\n const refreshOwnPreferences = useCallback(async (): Promise<void> => {\n const readOperation = findDefaultApiReadOperation(registry.resourceConfigurations[CoreResourceType.USER_SELF_PREFERENCES]);\n if (!readOperation) return;\n const request = ++preferencesRequestRef.current;\n const stored = await doOperation<UserPreferences>(\n ResourcesConfig_OperationPathUtils.buildOperationPathKeyFromOperation(readOperation),\n // Above `ScopedResourceRegistryProvider`, so the user id the route is addressed by is supplied here, as in\n // `recordConsentDecision`.\n { contextualParameters: buildScopeContextualParameters() },\n );\n // An older answer than a request started since: the newer one decides (see `preferencesRequestRef`).\n if (!stored || request !== preferencesRequestRef.current) return;\n // A record with no privacy block grants nothing: an absent decision must stop a running consent-based provider, not\n // keep the grant this page held before (#1973 review). `consentDecidedAt` stays absent, as it is on such a record.\n const storedPrivacy: UserPrivacy = stored.privacy ?? { consentedPurposes: [] };\n setPrivacy(storedPrivacy);\n setUser((previous) => previous\n ? { ...previous, userSelfPreferences: { ...(previous.userSelfPreferences ?? {}), ...stored, privacy: storedPrivacy } as UserContext['userSelfPreferences'] }\n : previous);\n }, [buildScopeContextualParameters, doOperation, registry]);\n\n useEffect(() => on(\n FrontendEvents.RESOURCE_OPERATION_EXECUTED,\n () => {\n void refreshOwnPreferences().catch((error: unknown) => {\n logger.warn('The preferences could not be read again after they were written', { error });\n });\n },\n (payload) => payload.resourceType === CoreResourceType.USER_SELF_PREFERENCES\n && !isReadShapedOperation(payload.operation ?? { operationIdentifier: payload.operationIdentifier }),\n ), [on, refreshOwnPreferences]);\n\n /**\n * Logout wrapper that also clears user/org data\n */\n const logout = useCallback((): void => {\n logDebug('Logging out user', { userId: user?._id, organizationId: currentOrganizationId });\n\n // Announced first, while the person's consent still holds — see the block above (#1977).\n announceDeparture(SessionEndReason.SIGNED_OUT);\n\n // Clear user/org data first\n setUser(null);\n setOrganizations([]);\n commitOrganizationScopeValue(null);\n setPermissions(null);\n setPrivacy(null);\n emitPreferencesChanged(null);\n\n // Reset initialization flag\n hasInitializedRef.current = false;\n previousTokenRef.current = null;\n\n // Call auth logout (clears tokens, disconnects WebSocket)\n authLogout();\n }, [user?._id, currentOrganizationId, authLogout, announceDeparture, commitOrganizationScopeValue, emitPreferencesChanged]);\n\n // Auto-load user/org data when token becomes available\n useEffect(() => {\n const accessToken = auth.accessToken;\n\n // Skip if no token or token hasn't changed\n if (!accessToken || accessToken === previousTokenRef.current) {\n return;\n }\n\n // Skip if session is already restored with this token\n if (auth.sessionRestored && user) {\n previousTokenRef.current = accessToken;\n return;\n }\n\n // Skip if already initializing\n if (hasInitializedRef.current && auth.isRestoringSession) {\n return;\n }\n\n logDebug('Token changed, initiating session restoration', {\n hasToken: !!accessToken,\n previousToken: !!previousTokenRef.current\n });\n\n previousTokenRef.current = accessToken;\n hasInitializedRef.current = true;\n\n // Restore session (will fetch user/org data)\n restoreSession().catch((error) => {\n logger.error('Session restoration failed', { error });\n });\n }, [auth.accessToken, auth.sessionRestored, auth.isRestoringSession, user, restoreSession]);\n\n // Clear data when token is removed (logged out)\n useEffect(() => {\n if (!auth.accessToken && previousTokenRef.current) {\n logDebug('Token removed, clearing user/org data');\n // Announced before `privacy: null`, with the reason the auth session recorded (#1977).\n announceDeparture(getSessionEndReason());\n setUser(null);\n setOrganizations([]);\n commitOrganizationScopeValue(null);\n setPermissions(null);\n setPrivacy(null);\n emitPreferencesChanged(null);\n previousTokenRef.current = null;\n hasInitializedRef.current = false;\n }\n }, [auth.accessToken, announceDeparture, commitOrganizationScopeValue, emitPreferencesChanged, getSessionEndReason]);\n\n const value = useMemo<UserOrgsContextType>(() => ({\n // Re-exported from AuthSession for backward compatibility\n auth,\n identifyByEmail,\n authenticateWithPassword,\n authenticate,\n getSessionState,\n isAuthenticated,\n logout,\n restoreSession,\n\n // OAuth2 + cross-frontend-handoff methods (delegated from AuthSession)\n initiateOAuth2Login,\n handleAuthCodeExchange,\n\n // User data\n user,\n\n // Organization data\n organizations,\n currentOrganizationId,\n permissions,\n primaryScopeInitiatorIds,\n\n // Privacy (only preference managed here)\n privacy,\n\n // Organization management\n setCurrentOrganization,\n followRouteOrganization,\n getCurrentOrganization,\n refreshOrganizations,\n\n // Privacy getter\n getPrivacy,\n recordConsentDecision,\n }), [\n auth,\n identifyByEmail,\n authenticateWithPassword,\n authenticate,\n getSessionState,\n isAuthenticated,\n logout,\n restoreSession,\n initiateOAuth2Login,\n handleAuthCodeExchange,\n user,\n organizations,\n currentOrganizationId,\n permissions,\n primaryScopeInitiatorIds,\n privacy,\n setCurrentOrganization,\n followRouteOrganization,\n getCurrentOrganization,\n refreshOrganizations,\n getPrivacy,\n recordConsentDecision,\n ]);\n\n return <UserOrgsContext.Provider value={value}>{children}</UserOrgsContext.Provider>;\n};\n\n// useUserOrgs hook is now in separate file: ./useUserOrgs.ts\n// This separation is required for React Fast Refresh compatibility\n"]}
@@ -0,0 +1,16 @@
1
+ import type React from 'react';
2
+ /**
3
+ * Whether an activation (a click, or a key) on a clickable CONTAINER started on a control INSIDE it.
4
+ *
5
+ * A collection row (a table row, a card) opens its record when it is clicked, and its cells hold controls of their own:
6
+ * a reference to another record, a copy button, a link. A click on one of those is that control's, and the row must not
7
+ * ALSO open its record. Before this, a click on the person a member row names opened the person AND the membership on
8
+ * top of it, so the reader landed on the membership with the person one Back below (Settings Hub, measured
9
+ * 2026-11-14); on a list page a reference `<a>` followed its link and the row opened its own record from the same
10
+ * click.
11
+ *
12
+ * The container itself is never an inner control, even when it carries a control role of its own. A control that is a
13
+ * sibling laid over the container (the card's overlay activator) stops its own event and never reaches here.
14
+ */
15
+ export declare function activationStartedOnInnerControl(event: React.SyntheticEvent<Element>): boolean;
16
+ //# sourceMappingURL=inner-control-activation.utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inner-control-activation.utils.d.ts","sourceRoot":"","sources":["../../../../src/core/ui/inner-control-activation.utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAyB/B;;;;;;;;;;;;GAYG;AACH,wBAAgB,+BAA+B,CAAC,KAAK,EAAE,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC,GAAG,OAAO,CAM7F"}
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The elements that act on a click or a key of their own: a link, a button, a form control, and their ARIA roles.
3
+ *
4
+ * Kept to the controls a person can operate, not to every focusable element: a `tabIndex` alone does not make an
5
+ * element do something when it is clicked.
6
+ */
7
+ const INNER_CONTROL_SELECTOR = [
8
+ 'a[href]',
9
+ 'button',
10
+ 'input',
11
+ 'select',
12
+ 'textarea',
13
+ 'summary',
14
+ '[contenteditable="true"]',
15
+ '[role="button"]',
16
+ '[role="link"]',
17
+ '[role="checkbox"]',
18
+ '[role="switch"]',
19
+ '[role="menuitem"]',
20
+ '[role="option"]',
21
+ '[role="tab"]',
22
+ ].join(', ');
23
+ /**
24
+ * Whether an activation (a click, or a key) on a clickable CONTAINER started on a control INSIDE it.
25
+ *
26
+ * A collection row (a table row, a card) opens its record when it is clicked, and its cells hold controls of their own:
27
+ * a reference to another record, a copy button, a link. A click on one of those is that control's, and the row must not
28
+ * ALSO open its record. Before this, a click on the person a member row names opened the person AND the membership on
29
+ * top of it, so the reader landed on the membership with the person one Back below (Settings Hub, measured
30
+ * 2026-11-14); on a list page a reference `<a>` followed its link and the row opened its own record from the same
31
+ * click.
32
+ *
33
+ * The container itself is never an inner control, even when it carries a control role of its own. A control that is a
34
+ * sibling laid over the container (the card's overlay activator) stops its own event and never reaches here.
35
+ */
36
+ export function activationStartedOnInnerControl(event) {
37
+ const target = event.target;
38
+ const container = event.currentTarget;
39
+ if (!(target instanceof Element) || target === container)
40
+ return false;
41
+ const control = target.closest(INNER_CONTROL_SELECTOR);
42
+ return control !== null && control !== container && container.contains(control);
43
+ }
44
+ //# sourceMappingURL=inner-control-activation.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inner-control-activation.utils.js","sourceRoot":"","sources":["../../../../src/core/ui/inner-control-activation.utils.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,sBAAsB,GAAG;IAC7B,SAAS;IACT,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,UAAU;IACV,SAAS;IACT,0BAA0B;IAC1B,iBAAiB;IACjB,eAAe;IACf,mBAAmB;IACnB,iBAAiB;IACjB,mBAAmB;IACnB,iBAAiB;IACjB,cAAc;CACf,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAEb;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,+BAA+B,CAAC,KAAoC;IAClF,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;IAC5B,MAAM,SAAS,GAAG,KAAK,CAAC,aAAa,CAAC;IACtC,IAAI,CAAC,CAAC,MAAM,YAAY,OAAO,CAAC,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC;IACvE,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,sBAAsB,CAAC,CAAC;IACvD,OAAO,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,SAAS,IAAI,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAClF,CAAC","sourcesContent":["import type React from 'react';\n\n/**\n * The elements that act on a click or a key of their own: a link, a button, a form control, and their ARIA roles.\n *\n * Kept to the controls a person can operate, not to every focusable element: a `tabIndex` alone does not make an\n * element do something when it is clicked.\n */\nconst INNER_CONTROL_SELECTOR = [\n 'a[href]',\n 'button',\n 'input',\n 'select',\n 'textarea',\n 'summary',\n '[contenteditable=\"true\"]',\n '[role=\"button\"]',\n '[role=\"link\"]',\n '[role=\"checkbox\"]',\n '[role=\"switch\"]',\n '[role=\"menuitem\"]',\n '[role=\"option\"]',\n '[role=\"tab\"]',\n].join(', ');\n\n/**\n * Whether an activation (a click, or a key) on a clickable CONTAINER started on a control INSIDE it.\n *\n * A collection row (a table row, a card) opens its record when it is clicked, and its cells hold controls of their own:\n * a reference to another record, a copy button, a link. A click on one of those is that control's, and the row must not\n * ALSO open its record. Before this, a click on the person a member row names opened the person AND the membership on\n * top of it, so the reader landed on the membership with the person one Back below (Settings Hub, measured\n * 2026-11-14); on a list page a reference `<a>` followed its link and the row opened its own record from the same\n * click.\n *\n * The container itself is never an inner control, even when it carries a control role of its own. A control that is a\n * sibling laid over the container (the card's overlay activator) stops its own event and never reaches here.\n */\nexport function activationStartedOnInnerControl(event: React.SyntheticEvent<Element>): boolean {\n const target = event.target;\n const container = event.currentTarget;\n if (!(target instanceof Element) || target === container) return false;\n const control = target.closest(INNER_CONTROL_SELECTOR);\n return control !== null && control !== container && container.contains(control);\n}\n"]}