@orangecheck/auth-client 2.42.4 → 2.43.1

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.
@@ -60,6 +60,25 @@ function isTimeout(err) {
60
60
  const name = err?.name;
61
61
  return name === "TimeoutError" || name === "AbortError";
62
62
  }
63
+ async function adoptStarted(started) {
64
+ try {
65
+ const signal = timeoutSignal(ME_TIMEOUT_MS);
66
+ const res = await Promise.race([
67
+ started,
68
+ new Promise(
69
+ (_, reject) => signal.addEventListener("abort", () => reject(signal.reason), { once: true })
70
+ )
71
+ ]);
72
+ if (!res.ok) return null;
73
+ const body = await res.clone().json();
74
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return null;
75
+ const account = body.account;
76
+ if (typeof account !== "object" || Array.isArray(account)) return null;
77
+ return res;
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
63
82
  async function fetchHostRoster(cfg) {
64
83
  try {
65
84
  const res = await fetch(`${cfg.authOrigin}${cfg.mePath}`, {
@@ -96,7 +115,8 @@ function normalizeAccount(raw) {
96
115
  function OcSessionProvider({
97
116
  children,
98
117
  config,
99
- defaultReturnTo
118
+ defaultReturnTo,
119
+ firstRead
100
120
  }) {
101
121
  const cfg = React.useMemo(() => resolveConfig(config), [config]);
102
122
  React.useState(() => {
@@ -111,6 +131,7 @@ function OcSessionProvider({
111
131
  const [status, setStatus] = React.useState("loading");
112
132
  const [error, setError] = React.useState(null);
113
133
  const [tabPinned, setTabPinned] = React.useState(false);
134
+ const firstReadRef = React.useRef(firstRead);
114
135
  const pinInFlightRef = React.useRef(false);
115
136
  const pinThisTab = React.useCallback(
116
137
  async (didOc) => {
@@ -139,7 +160,19 @@ function OcSessionProvider({
139
160
  if (typeof window === "undefined") return;
140
161
  try {
141
162
  let pin = readTabSession();
142
- let res = await fetch(cfg.mePath, {
163
+ const take = firstReadRef.current;
164
+ firstReadRef.current = void 0;
165
+ let started = null;
166
+ try {
167
+ const got = take?.();
168
+ started = got ? Promise.resolve(got) : null;
169
+ } catch {
170
+ started = null;
171
+ }
172
+ if (started && pin) started.catch(() => void 0);
173
+ let res = (started && !pin ? await adoptStarted(started) : null) ?? // A check that never answers would leave the page loading for good;
174
+ // past the timeout it is an error, which every site already shows.
175
+ await fetch(cfg.mePath, {
143
176
  method: "GET",
144
177
  credentials: "include",
145
178
  headers: { Accept: "application/json", ...tabSessionHeader() },
@@ -380,4 +413,4 @@ export {
380
413
  useOcSession,
381
414
  useOptionalOcSession
382
415
  };
383
- //# sourceMappingURL=chunk-JLMDCC6K.mjs.map
416
+ //# sourceMappingURL=chunk-X4IFJDCV.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/provider.tsx"],"sourcesContent":["import * as React from 'react';\n\nimport {\n buildAddAccountUrl,\n buildSignInUrl,\n DEFAULT_CONFIG,\n DISPLAY_IDENTITY_KINDS,\n resolveConfig,\n type DisplayIdentity,\n type DisplayIdentityKind,\n type OcAccount,\n type OcAccountSummary,\n type OcAuthConfig,\n type OcSessionState,\n type OcSignOutResult,\n type OcSignOutScope,\n} from './types';\nimport { keepFragmentOnReturnLinks, restoreReturnFragment } from './return-to';\nimport {\n clearTabSession,\n consumeTabAccountHint,\n consumeTabAdoptMarker,\n installTabFetchInterceptor,\n installTabLinkDecorator,\n readTabSession,\n tabSessionHeader,\n writeTabSession,\n} from './tab-session';\n\nconst SessionContext = React.createContext<OcSessionState | null>(null);\n\n/** Back and forward; a router's move renders the tree again, which reads the address again. */\nfunction onHistory(change: () => void): () => void {\n window.addEventListener('popstate', change);\n return () => window.removeEventListener('popstate', change);\n}\nconst pageAddress = () => window.location.href.split('#')[0];\n/** The server has no page, and the browser's first render must say what the server's HTML said. */\nconst noPageYet = () => undefined;\n\ntype RawSigningMethod = 'fedimint_threshold' | 'fedimint_client' | 'bip322';\n\ninterface RawRosterEntry {\n did_oc?: string;\n didOc?: string;\n display_name?: string | null;\n displayName?: string | null;\n primary_btc?: string | null;\n primaryBtc?: string | null;\n display_identity?: { kind?: string; value?: string } | null;\n displayIdentity?: { kind?: string; value?: string } | null;\n last_seen_at?: string | null;\n lastSeenAt?: string | null;\n}\n\ninterface MeResponse {\n account?: {\n id?: string;\n account_id?: string;\n accountId?: string;\n did_oc?: string;\n didOc?: string;\n primary_btc?: string | null;\n primaryBtc?: string | null;\n has_email?: boolean;\n hasEmail?: boolean;\n display_name?: string | null;\n displayName?: string | null;\n nostr_npub?: string | null;\n nostrNpub?: string | null;\n home_federation_slug?: string | null;\n homeFederation?: string | null;\n signing_method?: RawSigningMethod | null;\n signingMethod?: RawSigningMethod | null;\n is_owner?: boolean;\n isOwner?: boolean;\n display_identity?: { kind?: string; value?: string } | null;\n displayIdentity?: { kind?: string; value?: string } | null;\n };\n /** Multi-account roster · other accounts in this browser. Absent\n * on hosts that haven't deployed the multi-account migration yet\n * — treated as `[]` (single-account fallback). */\n roster?: RawRosterEntry[];\n}\n\n/**\n * Resolve the badge identity from a `/api/auth/me` account payload.\n * Total: returns the carried `{kind,value}` when well-formed, else\n * `{kind:'did',value:didOc}` — so accounts that never promoted, and\n * sessions minted before the field shipped, degrade cleanly.\n */\nfunction normalizeDisplayIdentity(\n raw: NonNullable<MeResponse['account']>,\n didOc: string\n): DisplayIdentity {\n const di = raw.display_identity ?? raw.displayIdentity;\n if (\n di &&\n typeof di === 'object' &&\n typeof di.value === 'string' &&\n di.value.length > 0 &&\n typeof di.kind === 'string' &&\n (DISPLAY_IDENTITY_KINDS as readonly string[]).includes(di.kind)\n ) {\n return { kind: di.kind as DisplayIdentityKind, value: di.value };\n }\n return { kind: 'did', value: didOc };\n}\n\n/**\n * Multi-account · normalize one roster entry from /api/auth/me. Drops\n * entries with no did_oc (defensive — the host shouldn't emit those).\n */\nfunction normalizeRosterEntry(raw: RawRosterEntry): OcAccountSummary | null {\n const didOc = raw.did_oc ?? raw.didOc;\n if (!didOc) return null;\n const di = raw.display_identity ?? raw.displayIdentity;\n const displayIdentity: DisplayIdentity =\n di &&\n typeof di === 'object' &&\n typeof di.value === 'string' &&\n di.value.length > 0 &&\n typeof di.kind === 'string' &&\n (DISPLAY_IDENTITY_KINDS as readonly string[]).includes(di.kind)\n ? { kind: di.kind as DisplayIdentityKind, value: di.value }\n : { kind: 'did', value: didOc };\n return {\n didOc,\n displayName: raw.display_name ?? raw.displayName ?? null,\n primaryBtc: raw.primary_btc ?? raw.primaryBtc ?? null,\n displayIdentity,\n lastSeenAt: raw.last_seen_at ?? raw.lastSeenAt ?? null,\n };\n}\n\n/**\n * Multi-account · fetch the roster from the AUTH HOST cross-origin.\n *\n * Consumer subdomains expose a LOCAL `/api/auth/me` that verifies the JWT\n * but has no database, so it never carries the `roster` (which is host DB\n * state). When the local /me comes back authenticated with an empty roster,\n * we source it from the host directly — the same credentialed cross-origin\n * pattern this provider already uses for logout + account PATCH, and the\n * host already serves `.ochk.io` consumers via CORS.\n *\n * Best-effort by construction: any failure resolves to `[]`, so a roster\n * fetch can never change the authenticated state derived from the local /me.\n */\n/** How long a session check may take before the page stops waiting on it. */\nexport const ME_TIMEOUT_MS = 10_000;\n\n/** `AbortSignal.timeout` where the browser has it, a timer where it does not. */\nfunction timeoutSignal(ms: number): AbortSignal {\n if (typeof AbortSignal.timeout === 'function') return AbortSignal.timeout(ms);\n const controller = new AbortController();\n setTimeout(() => controller.abort(), ms);\n return controller.signal;\n}\n\nfunction isTimeout(err: unknown): boolean {\n const name = (err as { name?: unknown } | null)?.name;\n return name === 'TimeoutError' || name === 'AbortError';\n}\n\n/**\n * A session read the page started itself, kept when it answered 2xx within\n * the timeout with a body of the session read's shape (an object with an\n * `account`, null or an object). Anything else is null, and the provider\n * reads again on its own.\n */\nasync function adoptStarted(started: Promise<Response>): Promise<Response | null> {\n try {\n const signal = timeoutSignal(ME_TIMEOUT_MS);\n const res = await Promise.race([\n started,\n new Promise<never>((_, reject) =>\n signal.addEventListener('abort', () => reject(signal.reason), { once: true })\n ),\n ]);\n if (!res.ok) return null;\n const body: unknown = await res.clone().json();\n if (typeof body !== 'object' || body === null || Array.isArray(body)) return null;\n const account = (body as { account?: unknown }).account;\n if (typeof account !== 'object' || Array.isArray(account)) return null;\n return res;\n } catch {\n return null;\n }\n}\n\nasync function fetchHostRoster(cfg: Required<OcAuthConfig>): Promise<OcAccountSummary[]> {\n try {\n // Per-tab · carry the pin so the host computes \"peers\" relative\n // to THIS tab's effective account, not the cookie default.\n const res = await fetch(`${cfg.authOrigin}${cfg.mePath}`, {\n method: 'GET',\n credentials: 'include',\n headers: { Accept: 'application/json', ...tabSessionHeader() },\n signal: timeoutSignal(ME_TIMEOUT_MS),\n });\n if (!res.ok) return [];\n const body = (await res.json()) as MeResponse;\n return Array.isArray(body.roster)\n ? body.roster\n .map(normalizeRosterEntry)\n .filter((r): r is OcAccountSummary => r !== null)\n : [];\n } catch {\n return [];\n }\n}\n\nfunction normalizeAccount(raw: MeResponse['account']): OcAccount | null {\n if (!raw) return null;\n const didOc = raw.did_oc ?? raw.didOc;\n const accountId = raw.id ?? raw.account_id ?? raw.accountId;\n if (!didOc || !accountId) return null;\n return {\n accountId,\n didOc,\n primaryBtc: raw.primary_btc ?? raw.primaryBtc ?? null,\n hasEmail: raw.has_email ?? raw.hasEmail ?? false,\n displayName: raw.display_name ?? raw.displayName ?? null,\n nostrNpub: raw.nostr_npub ?? raw.nostrNpub ?? null,\n homeFederation: raw.home_federation_slug ?? raw.homeFederation ?? null,\n signingMethod: raw.signing_method ?? raw.signingMethod ?? null,\n isOwner: Boolean(raw.is_owner ?? raw.isOwner ?? false),\n displayIdentity: normalizeDisplayIdentity(raw, didOc),\n };\n}\n\nexport interface OcSessionProviderProps {\n children: React.ReactNode;\n config?: OcAuthConfig;\n /**\n * Optional return URL passed to the sign-in page. Defaults to the\n * current page. Its fragment is never sent: it is kept in this tab and\n * restored on return (./return-to).\n */\n defaultReturnTo?: string;\n /**\n * The page's own start on the first session check: a script in the\n * document head can send the same `GET mePath` with credentials before\n * the bundle loads, and hand its response here. Called once, for the\n * first check only. A read that fails, times out, answers other than 2xx,\n * has a body without an `account` (null or an object), or arrives while\n * this tab carries a pin, is dropped and the provider reads again itself.\n */\n firstRead?: () => Promise<Response> | null | undefined;\n}\n\n/**\n * Top-level provider that exposes the cross-subdomain oc_session to every\n * component below it. Mount once, near the root of your tree.\n */\nexport function OcSessionProvider({\n children,\n config,\n defaultReturnTo,\n firstRead,\n}: OcSessionProviderProps): React.ReactElement {\n const cfg = React.useMemo(() => resolveConfig(config), [config]);\n // Back from a sign-in or a check: put back the fragment its return\n // address left in this tab, before any page below reads the address.\n // The adoption marker the auth host appends goes first, so the fragment\n // takes its place. Children's effects run before this provider's, so\n // this happens during the first render, once; both calls are idempotent.\n React.useState(() => {\n if (typeof window !== 'undefined') {\n consumeTabAdoptMarker();\n restoreReturnFragment();\n }\n return null;\n });\n const [account, setAccount] = React.useState<OcAccount | null>(null);\n const [roster, setRoster] = React.useState<OcAccountSummary[]>([]);\n const [status, setStatus] = React.useState<OcSessionState['status']>('loading');\n const [error, setError] = React.useState<Error | null>(null);\n const [tabPinned, setTabPinned] = React.useState(false);\n // Taken by the first check only; every later check reads for itself.\n const firstReadRef = React.useRef(firstRead);\n\n // Per-tab · mint a pin for this tab via the host. Called once per\n // tab on first authenticated resolve, so a later switch in ANOTHER\n // tab can't yank this one — it keeps presenting its own token.\n // Best-effort: a host that predates `/api/auth/tab` (or a network\n // failure) leaves the tab unpinned, which is exactly the legacy\n // cookie-following behavior.\n const pinInFlightRef = React.useRef(false);\n const pinThisTab = React.useCallback(\n async (didOc: string) => {\n if (!cfg.multiAccount || pinInFlightRef.current || readTabSession()) return;\n pinInFlightRef.current = true;\n try {\n const res = await fetch(`${cfg.authOrigin}/api/auth/tab`, {\n method: 'POST',\n credentials: 'include',\n headers: { Accept: 'application/json' },\n });\n if (!res.ok) return;\n const body = (await res.json()) as {\n ok?: boolean;\n token?: string;\n account?: { did_oc?: string };\n };\n // Only pin when the host minted for the account this tab\n // just resolved — a cookie flip racing between our /me and\n // /tab calls must not pin the WRONG account.\n if (\n body.ok &&\n typeof body.token === 'string' &&\n body.account?.did_oc === didOc\n ) {\n writeTabSession({ token: body.token, didOc });\n setTabPinned(true);\n }\n } catch {\n // best-effort by construction\n } finally {\n pinInFlightRef.current = false;\n }\n },\n [cfg.authOrigin, cfg.multiAccount]\n );\n\n const refresh = React.useCallback(async () => {\n if (typeof window === 'undefined') return;\n try {\n let pin = readTabSession();\n const take = firstReadRef.current;\n firstReadRef.current = undefined;\n let started: Promise<Response> | null = null;\n try {\n const got = take?.();\n started = got ? Promise.resolve(got) : null;\n } catch {\n started = null;\n }\n // The page's own start carries no pin, so a pinned tab reads again.\n if (started && pin) started.catch(() => undefined);\n let res =\n (started && !pin ? await adoptStarted(started) : null) ??\n // A check that never answers would leave the page loading for good;\n // past the timeout it is an error, which every site already shows.\n (await fetch(cfg.mePath, {\n method: 'GET',\n credentials: 'include',\n headers: { Accept: 'application/json', ...tabSessionHeader() },\n signal: timeoutSignal(ME_TIMEOUT_MS),\n }));\n // Per-tab · 401 with a pin present means the pinned token is\n // dead (expired, or revoked and rejected by the host). Drop\n // the pin and retry once as the browser-default account.\n if (res.status === 401 && pin) {\n clearTabSession();\n pin = null;\n setTabPinned(false);\n res = await fetch(cfg.mePath, {\n method: 'GET',\n credentials: 'include',\n headers: { Accept: 'application/json' },\n signal: timeoutSignal(ME_TIMEOUT_MS),\n });\n }\n if (res.status === 401) {\n setAccount(null);\n setRoster([]);\n setStatus('anonymous');\n setError(null);\n return;\n }\n if (!res.ok) {\n setStatus('error');\n setError(new Error(`me endpoint returned ${res.status}`));\n return;\n }\n const body = (await res.json()) as MeResponse;\n const acct = normalizeAccount(body.account);\n // Per-tab reconciliation · the server answered as a different\n // account than the pin → it doesn't honor `x-oc-tab-session`\n // yet (pre-migration deploy). Drop the pin: the UI must never\n // display an account the server isn't acting as.\n if (acct && pin && acct.didOc !== pin.didOc) {\n clearTabSession();\n pin = null;\n }\n setTabPinned(pin !== null);\n const rosterEntries = Array.isArray(body.roster)\n ? body.roster\n .map(normalizeRosterEntry)\n .filter((r): r is OcAccountSummary => r !== null)\n : [];\n setAccount(acct);\n setRoster(rosterEntries);\n setStatus(acct ? 'authenticated' : 'anonymous');\n setError(null);\n\n // Per-tab · authenticated but unpinned → pin this tab to the\n // account it just resolved (fire-and-forget).\n if (acct && !pin) void pinThisTab(acct.didOc);\n\n // Multi-account · the local /me carried no roster (the standard\n // case on consumer subdomains, whose local /me has no DB). When\n // we're authenticated and NOT already on the auth host, source\n // the roster from the host so the §accounts switcher lights up.\n // Best-effort: never touches account/status on failure.\n const currentOrigin =\n typeof window !== 'undefined' ? window.location.origin : null;\n if (\n cfg.multiAccount &&\n acct &&\n rosterEntries.length === 0 &&\n currentOrigin !== null &&\n !cfg.authOrigin.startsWith(currentOrigin)\n ) {\n const peers = await fetchHostRoster(cfg);\n if (peers.length > 0) setRoster(peers);\n }\n } catch (err) {\n setStatus('error');\n setError(\n isTimeout(err)\n ? new Error(`me endpoint did not answer within ${ME_TIMEOUT_MS / 1000}s`)\n : err instanceof Error\n ? err\n : new Error(String(err))\n );\n }\n }, [cfg, pinThisTab]);\n\n React.useEffect(() => {\n let cancelled = false;\n // Post-ceremony adoption · the auth host appends `#oc-adopt` when\n // returning from a sign-in/add ceremony: the user expects THIS tab\n // to become the account they just authenticated, so a stale pin\n // must not survive the round trip.\n consumeTabAdoptMarker();\n void (async () => {\n // New-tab inheritance · if the opener stamped `#oc-as=<did>`,\n // adopt that account BEFORE the first /me fetch so this tab\n // resolves as the opener's account, not the cookie default.\n if (cfg.multiAccount) await consumeTabAccountHint(cfg.authOrigin);\n if (!cancelled) void refresh();\n })();\n return () => {\n cancelled = true;\n };\n }, [refresh, cfg.authOrigin, cfg.multiAccount]);\n\n // A link that brings the browser back here keeps this page's fragment\n // in the tab, since its return_to cannot carry it.\n React.useEffect(() => keepFragmentOnReturnLinks(), []);\n\n // Per-tab · attach the pin to every same-site fetch so app-level data\n // calls execute as the account this tab displays. Scoped + reversible;\n // see installTabFetchInterceptor for the conservative rules.\n React.useEffect(\n () => (cfg.multiAccount ? installTabFetchInterceptor(cfg.authOrigin) : undefined),\n [cfg.authOrigin, cfg.multiAccount]\n );\n\n // Per-tab · stamp this tab's effective account onto outgoing\n // family-origin links so a new/cross-subdomain tab inherits it\n // instead of the shared cookie default. See installTabLinkDecorator.\n React.useEffect(\n () => (cfg.multiAccount ? installTabLinkDecorator(cfg.authOrigin) : undefined),\n [cfg.authOrigin, cfg.multiAccount]\n );\n\n const trySignOut = React.useCallback(\n async (opts?: { scope?: OcSignOutScope }): Promise<OcSignOutResult> => {\n const scope: OcSignOutScope = opts?.scope ?? 'all';\n let res: Response;\n try {\n const url = new URL(`${cfg.authOrigin}${cfg.logoutPath}`);\n if (scope === 'current') url.searchParams.set('scope', 'current');\n res = await fetch(url.toString(), {\n method: 'POST',\n credentials: 'include',\n // Per-tab · carry the pin so scope='current' signs out\n // the account THIS tab is operating as, not whichever\n // account the shared cookie happens to point at.\n headers: { ...tabSessionHeader() },\n // `keepalive` lets the logout round-trip complete even if\n // the caller hard-navigates away in the same tick (e.g.\n // `<OcAccountMenu>` redirects home immediately on sign-out).\n // Without it the in-flight request is cancelled on unload\n // and the `.ochk.io` cookie may never get cleared.\n keepalive: true,\n });\n } catch {\n // The auth host never answered, so the session may well live on.\n // Nothing local changes: showing \"signed out\" here would be false.\n return { ok: false, reason: 'unreachable' };\n }\n // 401: no session reached the host, so there is none to end.\n if (!res.ok && res.status !== 401) {\n return { ok: false, reason: 'refused', status: res.status };\n }\n // The signed-out account's token is dead — the pin must not outlive it.\n clearTabSession();\n setTabPinned(false);\n // Multi-account: with scope='current', the server may have\n // switched the active session to a roster peer instead of\n // clearing the cookie. Re-fetch /api/auth/me so this\n // provider reflects the new active account; if the body\n // says `switched_to !== null`, refresh resolves to the\n // peer, otherwise it resolves to anonymous.\n if (scope === 'current' && res.ok) {\n await refresh();\n return { ok: true };\n }\n setAccount(null);\n setRoster([]);\n setStatus('anonymous');\n return { ok: true };\n },\n [cfg.authOrigin, cfg.logoutPath, refresh]\n );\n // The long-standing call: same type, but it no longer reports \"signed out\" when\n // the auth host did not end the session. trySignOut says what happened.\n const signOut = React.useCallback(\n async (opts?: { scope?: OcSignOutScope }): Promise<void> => {\n await trySignOut(opts);\n },\n [trySignOut]\n );\n\n const switchAccount = React.useCallback(\n async (didOc: string) => {\n if (typeof window === 'undefined') return;\n const res = await fetch(`${cfg.authOrigin}/api/auth/switch`, {\n method: 'POST',\n credentials: 'include',\n headers: { 'Content-Type': 'application/json', ...tabSessionHeader() },\n body: JSON.stringify({ did_oc: didOc }),\n });\n if (!res.ok) {\n let reason = `http_${res.status}`;\n try {\n const body = (await res.json()) as { reason?: string };\n if (body.reason) reason = body.reason;\n } catch {\n // keep http_ fallback\n }\n throw new Error(`[@orangecheck/auth-client] switchAccount failed: ${reason}`);\n }\n // Per-tab · pin THIS tab to the switch target using the fresh\n // JWT the host echoes in the body. The host has also flipped\n // the shared cookie — the default for FUTURE tabs — but other\n // open tabs keep their own pins and are not yanked. Pin to the\n // did the SERVER minted for (merge-graph collapse may differ\n // from the requested did).\n try {\n const body = (await res.json()) as {\n token?: string;\n account?: { did_oc?: string };\n };\n if (typeof body.token === 'string' && body.account?.did_oc) {\n writeTabSession({ token: body.token, didOc: body.account.did_oc });\n setTabPinned(true);\n }\n } catch {\n // body unreadable — cookie still flipped; refresh resolves it\n }\n // Re-fetch /me to surface the new active account + freshly\n // computed roster (the previous active account is now a peer,\n // swap is symmetric).\n await refresh();\n },\n [cfg.authOrigin, refresh]\n );\n\n const addAccountUrl = React.useCallback(\n (returnTo?: string) => {\n const rt =\n returnTo ?? (typeof window !== 'undefined' ? window.location.href : undefined);\n return buildAddAccountUrl(cfg, rt);\n },\n [cfg]\n );\n\n const setDisplayIdentity = React.useCallback(\n async (kind: DisplayIdentityKind) => {\n if (typeof window === 'undefined') return;\n // PATCH the auth host directly (family-CORS). It writes the\n // pref, re-mints the `.ochk.io` session cookie with the new\n // `display_identity` claim, and Set-Cookies it back — so the\n // choice propagates to every subdomain. Then refresh so this\n // session reflects it immediately.\n const res = await fetch(`${cfg.authOrigin}/api/auth/account`, {\n method: 'PATCH',\n credentials: 'include',\n headers: { 'Content-Type': 'application/json', ...tabSessionHeader() },\n body: JSON.stringify({ display_identity: kind }),\n });\n if (!res.ok) {\n let reason = `http_${res.status}`;\n try {\n const body = (await res.json()) as { reason?: string };\n if (body.reason) reason = body.reason;\n } catch {\n // keep the http_ fallback\n }\n throw new Error(`[@orangecheck/auth-client] setDisplayIdentity failed: ${reason}`);\n }\n // Per-tab · the PATCH re-mints; when this tab is pinned the\n // host echoes the fresh token in the body (it only rewrites\n // the shared cookie when the cookie account was the actor).\n // Re-pin so the tab carries the updated claims.\n try {\n const body = (await res.json()) as {\n token?: string;\n account?: { did_oc?: string };\n };\n const pin = readTabSession();\n if (\n pin &&\n typeof body.token === 'string' &&\n body.account?.did_oc === pin.didOc\n ) {\n writeTabSession({ token: body.token, didOc: pin.didOc });\n }\n } catch {\n // body unreadable — refresh below still reconciles state\n }\n await refresh();\n },\n [cfg.authOrigin, refresh]\n );\n\n // Read through the store, not from the window as this renders: a server-rendered\n // link keeps the server's href when hydrating, so the page is added after.\n const here = React.useSyncExternalStore(onHistory, pageAddress, noPageYet);\n const value = React.useMemo<OcSessionState>(() => {\n const returnTo = defaultReturnTo ?? here;\n return {\n status,\n account,\n roster,\n tabPinned,\n error,\n refresh,\n signOut,\n trySignOut,\n switchAccount,\n addAccountUrl,\n setDisplayIdentity,\n signInUrl: buildSignInUrl(cfg, returnTo),\n };\n }, [\n status,\n account,\n roster,\n tabPinned,\n error,\n refresh,\n signOut,\n trySignOut,\n switchAccount,\n addAccountUrl,\n setDisplayIdentity,\n cfg,\n defaultReturnTo,\n here,\n ]);\n\n return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>;\n}\n\n/**\n * Access the current cross-subdomain oc_session. Must be called inside\n * an `<OcSessionProvider>`.\n */\nexport function useOcSession(): OcSessionState {\n const ctx = React.useContext(SessionContext);\n if (!ctx) {\n throw new Error(\n '[@orangecheck/auth-client] useOcSession() must be called inside <OcSessionProvider>'\n );\n }\n return ctx;\n}\n\n/**\n * Non-throwing variant — returns `null` if called outside a provider.\n * Useful for libraries that want to read the session *if it exists* but\n * shouldn't crash on apps that haven't opted in.\n */\nexport function useOptionalOcSession(): OcSessionState | null {\n return React.useContext(SessionContext);\n}\n\nexport { DEFAULT_CONFIG };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,YAAY,WAAW;AA2pBZ;AA9nBX,IAAM,iBAAuB,oBAAqC,IAAI;AAGtE,SAAS,UAAU,QAAgC;AAC/C,SAAO,iBAAiB,YAAY,MAAM;AAC1C,SAAO,MAAM,OAAO,oBAAoB,YAAY,MAAM;AAC9D;AACA,IAAM,cAAc,MAAM,OAAO,SAAS,KAAK,MAAM,GAAG,EAAE,CAAC;AAE3D,IAAM,YAAY,MAAM;AAqDxB,SAAS,yBACL,KACA,OACe;AACf,QAAM,KAAK,IAAI,oBAAoB,IAAI;AACvC,MACI,MACA,OAAO,OAAO,YACd,OAAO,GAAG,UAAU,YACpB,GAAG,MAAM,SAAS,KAClB,OAAO,GAAG,SAAS,YAClB,uBAA6C,SAAS,GAAG,IAAI,GAChE;AACE,WAAO,EAAE,MAAM,GAAG,MAA6B,OAAO,GAAG,MAAM;AAAA,EACnE;AACA,SAAO,EAAE,MAAM,OAAO,OAAO,MAAM;AACvC;AAMA,SAAS,qBAAqB,KAA8C;AACxE,QAAM,QAAQ,IAAI,UAAU,IAAI;AAChC,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,KAAK,IAAI,oBAAoB,IAAI;AACvC,QAAM,kBACF,MACA,OAAO,OAAO,YACd,OAAO,GAAG,UAAU,YACpB,GAAG,MAAM,SAAS,KAClB,OAAO,GAAG,SAAS,YAClB,uBAA6C,SAAS,GAAG,IAAI,IACxD,EAAE,MAAM,GAAG,MAA6B,OAAO,GAAG,MAAM,IACxD,E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import {
5
5
  resolveConfig
6
6
  } from "./chunk-PQHFAVVM.mjs";
@@ -250,4 +250,4 @@ export {
250
250
  useWebAuthnList,
251
251
  useStepUpAuth
252
252
  };
253
- //# sourceMappingURL=chunk-M2VUFCZU.mjs.map
253
+ //# sourceMappingURL=chunk-YGXMLIQ3.mjs.map
@@ -4,8 +4,8 @@ import {
4
4
  OcAddressInput,
5
5
  OcSignInButton,
6
6
  useOcAddressSuggestion
7
- } from "./chunk-VQY7IYHV.mjs";
8
- import "./chunk-JLMDCC6K.mjs";
7
+ } from "./chunk-UHQCVPT4.mjs";
8
+ import "./chunk-X4IFJDCV.mjs";
9
9
  import "./chunk-PQHFAVVM.mjs";
10
10
  import "./chunk-JTT77LMU.mjs";
11
11
  import "./chunk-4BOO7EQR.mjs";
package/dist/index.d.ts CHANGED
@@ -67,8 +67,9 @@ interface OcSessionProviderProps {
67
67
  children: React.ReactNode;
68
68
  config?: OcAuthConfig;
69
69
  defaultReturnTo?: string;
70
+ firstRead?: () => Promise<Response> | null | undefined;
70
71
  }
71
- declare function OcSessionProvider({ children, config, defaultReturnTo, }: OcSessionProviderProps): React.ReactElement;
72
+ declare function OcSessionProvider({ children, config, defaultReturnTo, firstRead, }: OcSessionProviderProps): React.ReactElement;
72
73
  declare function useOcSession(): OcSessionState;
73
74
  declare function useOptionalOcSession(): OcSessionState | null;
74
75
 
package/dist/index.js CHANGED
@@ -363,6 +363,25 @@ function isTimeout(err) {
363
363
  const name = err?.name;
364
364
  return name === "TimeoutError" || name === "AbortError";
365
365
  }
366
+ async function adoptStarted(started) {
367
+ try {
368
+ const signal = timeoutSignal(ME_TIMEOUT_MS);
369
+ const res = await Promise.race([
370
+ started,
371
+ new Promise(
372
+ (_, reject) => signal.addEventListener("abort", () => reject(signal.reason), { once: true })
373
+ )
374
+ ]);
375
+ if (!res.ok) return null;
376
+ const body = await res.clone().json();
377
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return null;
378
+ const account = body.account;
379
+ if (typeof account !== "object" || Array.isArray(account)) return null;
380
+ return res;
381
+ } catch {
382
+ return null;
383
+ }
384
+ }
366
385
  async function fetchHostRoster(cfg) {
367
386
  try {
368
387
  const res = await fetch(`${cfg.authOrigin}${cfg.mePath}`, {
@@ -399,7 +418,8 @@ function normalizeAccount(raw) {
399
418
  function OcSessionProvider({
400
419
  children,
401
420
  config,
402
- defaultReturnTo
421
+ defaultReturnTo,
422
+ firstRead
403
423
  }) {
404
424
  const cfg = React4__namespace.useMemo(() => resolveConfig(config), [config]);
405
425
  React4__namespace.useState(() => {
@@ -414,6 +434,7 @@ function OcSessionProvider({
414
434
  const [status, setStatus] = React4__namespace.useState("loading");
415
435
  const [error, setError] = React4__namespace.useState(null);
416
436
  const [tabPinned, setTabPinned] = React4__namespace.useState(false);
437
+ const firstReadRef = React4__namespace.useRef(firstRead);
417
438
  const pinInFlightRef = React4__namespace.useRef(false);
418
439
  const pinThisTab = React4__namespace.useCallback(
419
440
  async (didOc) => {
@@ -442,7 +463,19 @@ function OcSessionProvider({
442
463
  if (typeof window === "undefined") return;
443
464
  try {
444
465
  let pin = readTabSession();
445
- let res = await fetch(cfg.mePath, {
466
+ const take = firstReadRef.current;
467
+ firstReadRef.current = void 0;
468
+ let started = null;
469
+ try {
470
+ const got = take?.();
471
+ started = got ? Promise.resolve(got) : null;
472
+ } catch {
473
+ started = null;
474
+ }
475
+ if (started && pin) started.catch(() => void 0);
476
+ let res = (started && !pin ? await adoptStarted(started) : null) ?? // A check that never answers would leave the page loading for good;
477
+ // past the timeout it is an error, which every site already shows.
478
+ await fetch(cfg.mePath, {
446
479
  method: "GET",
447
480
  credentials: "include",
448
481
  headers: { Accept: "application/json", ...tabSessionHeader() },
@@ -2931,11 +2964,14 @@ function WalletFlow({
2931
2964
  address: `${uid}-address`,
2932
2965
  wallet: `${uid}-wallet`,
2933
2966
  message: `${uid}-message`,
2934
- signature: `${uid}-signature`
2967
+ signature: `${uid}-signature`,
2968
+ prompt: `${uid}-prompt`,
2969
+ error: `${uid}-error`
2935
2970
  };
2936
2971
  const [address, setAddress] = React4__namespace.useState("");
2937
2972
  const [error, setError] = React4__namespace.useState(null);
2938
2973
  const [submitting, setSubmitting] = React4__namespace.useState(false);
2974
+ const [back, setBack] = React4__namespace.useState(false);
2939
2975
  const [wallets, setWallets] = React4__namespace.useState(null);
2940
2976
  const [walletId, setWalletId] = React4__namespace.useState(null);
2941
2977
  const [manual, setManual] = React4__namespace.useState(null);
@@ -2989,6 +3025,7 @@ function WalletFlow({
2989
3025
  }
2990
3026
  async function signIn(e) {
2991
3027
  e.preventDefault();
3028
+ if (submitting) return;
2992
3029
  const addr = address.trim();
2993
3030
  if (!addr) {
2994
3031
  setError("Paste your Bitcoin address.");
@@ -3033,7 +3070,7 @@ function WalletFlow({
3033
3070
  }
3034
3071
  async function signInManual(e) {
3035
3072
  e.preventDefault();
3036
- if (!manual) return;
3073
+ if (!manual || submitting) return;
3037
3074
  const sig = pasted.trim();
3038
3075
  if (!sig) {
3039
3076
  setError("Paste the signature your wallet gave you.");
@@ -3059,7 +3096,7 @@ function WalletFlow({
3059
3096
  }
3060
3097
  if (manual) {
3061
3098
  return /* @__PURE__ */ jsxRuntime.jsxs("form", { onSubmit: signInManual, "data-oc-signin-wallet-manual": "", children: [
3062
- /* @__PURE__ */ jsxRuntime.jsxs(FlowHeader, { children: [
3099
+ /* @__PURE__ */ jsxRuntime.jsxs(FlowHeader, { id: ids.prompt, children: [
3063
3100
  "In your wallet, use \u201Csign message\u201D (BIP-322) with ",
3064
3101
  address.trim(),
3065
3102
  ", sign the text below, and paste the signature back here. Nothing is spent."
@@ -3096,25 +3133,29 @@ function WalletFlow({
3096
3133
  spellCheck: false,
3097
3134
  autoFocus: true,
3098
3135
  "aria-invalid": error ? true : void 0,
3136
+ "aria-describedby": describedBy(ids.prompt, ids.message, error && ids.error),
3099
3137
  style: { ...inputStyle2, resize: "vertical" }
3100
3138
  }
3101
3139
  )
3102
3140
  ] }),
3103
- error && /* @__PURE__ */ jsxRuntime.jsx(ErrorLine2, { children: error }),
3141
+ error && /* @__PURE__ */ jsxRuntime.jsx(ErrorLine2, { id: ids.error, children: error }),
3104
3142
  /* @__PURE__ */ jsxRuntime.jsx(
3105
3143
  "button",
3106
3144
  {
3107
3145
  type: "submit",
3108
- disabled: submitting || !pasted.trim(),
3146
+ disabled: !pasted.trim(),
3147
+ "aria-disabled": submitting || void 0,
3109
3148
  style: submitStyle(submitting || !pasted.trim()),
3110
3149
  children: submitting ? "Checking\u2026" : /* @__PURE__ */ jsxRuntime.jsx(Submit, { children: "Sign me in" })
3111
3150
  }
3112
3151
  ),
3152
+ /* @__PURE__ */ jsxRuntime.jsx(Busy, { children: submitting ? "Checking\u2026" : null }),
3113
3153
  /* @__PURE__ */ jsxRuntime.jsx(
3114
3154
  "button",
3115
3155
  {
3116
3156
  type: "button",
3117
3157
  onClick: () => {
3158
+ setBack(true);
3118
3159
  setManual(null);
3119
3160
  setPasted("");
3120
3161
  setError(null);
@@ -3146,7 +3187,9 @@ function WalletFlow({
3146
3187
  autoCapitalize: "none",
3147
3188
  spellCheck: false,
3148
3189
  required: true,
3190
+ autoFocus: back,
3149
3191
  "aria-invalid": error ? true : void 0,
3192
+ "aria-describedby": describedBy(error && ids.error),
3150
3193
  style: inputStyle2
3151
3194
  }
3152
3195
  ),
@@ -3163,16 +3206,18 @@ function WalletFlow({
3163
3206
  }
3164
3207
  )
3165
3208
  ] }),
3166
- error && /* @__PURE__ */ jsxRuntime.jsx(ErrorLine2, { children: error }),
3209
+ error && /* @__PURE__ */ jsxRuntime.jsx(ErrorLine2, { id: ids.error, children: error }),
3167
3210
  /* @__PURE__ */ jsxRuntime.jsx(
3168
3211
  "button",
3169
3212
  {
3170
3213
  type: "submit",
3171
- disabled: submitting || !address.trim(),
3214
+ disabled: !address.trim(),
3215
+ "aria-disabled": submitting || void 0,
3172
3216
  style: submitStyle(submitting || !address.trim()),
3173
3217
  children: submitting ? "Waiting for wallet\u2026" : noBrowserWallet ? /* @__PURE__ */ jsxRuntime.jsx(Submit, { children: "Get the message to sign" }) : /* @__PURE__ */ jsxRuntime.jsx(Submit, { children: "Sign in with wallet" })
3174
3218
  }
3175
3219
  ),
3220
+ /* @__PURE__ */ jsxRuntime.jsx(Busy, { children: submitting ? "Waiting for wallet\u2026" : null }),
3176
3221
  noBrowserWallet && /* @__PURE__ */ jsxRuntime.jsx(Hint, { children: "No browser wallet found here. You can sign with any wallet and paste." })
3177
3222
  ] });
3178
3223
  }
@@ -3186,6 +3231,8 @@ function EmailFlow({ authOrigin, add, credentials, onSuccess }) {
3186
3231
  const [token, setToken] = React4__namespace.useState(null);
3187
3232
  const [submitting, setSubmitting] = React4__namespace.useState(false);
3188
3233
  const [resent, setResent] = React4__namespace.useState(false);
3234
+ const [back, setBack] = React4__namespace.useState(false);
3235
+ const ids = { emailError: `${uid}-email-error`, codeError: `${uid}-code-error` };
3189
3236
  async function sendCode(address) {
3190
3237
  try {
3191
3238
  const res = await fetch(`${authOrigin}/api/auth/email-otp/start`, {
@@ -3205,6 +3252,7 @@ function EmailFlow({ authOrigin, add, credentials, onSuccess }) {
3205
3252
  }
3206
3253
  async function start(e) {
3207
3254
  e.preventDefault();
3255
+ if (submitting) return;
3208
3256
  const trimmed = identifiers.normalizeEmail(email);
3209
3257
  if (!trimmed || !/.+@.+\..+/.test(trimmed)) {
3210
3258
  setEmailError(humanSigninError("invalid_email", "email"));
@@ -3222,6 +3270,7 @@ function EmailFlow({ authOrigin, add, credentials, onSuccess }) {
3222
3270
  setStage("code");
3223
3271
  }
3224
3272
  async function resend() {
3273
+ if (submitting) return;
3225
3274
  setCodeError(null);
3226
3275
  setResent(false);
3227
3276
  setSubmitting(true);
@@ -3233,7 +3282,7 @@ function EmailFlow({ authOrigin, add, credentials, onSuccess }) {
3233
3282
  }
3234
3283
  async function verify(e) {
3235
3284
  e.preventDefault();
3236
- if (!token) return;
3285
+ if (!token || submitting) return;
3237
3286
  if (code.length !== 6) {
3238
3287
  setCodeError("The code is 6 digits.");
3239
3288
  return;
@@ -3265,7 +3314,7 @@ function EmailFlow({ authOrigin, add, credentials, onSuccess }) {
3265
3314
  }
3266
3315
  }
3267
3316
  if (stage === "enter") {
3268
- return /* @__PURE__ */ jsxRuntime.jsxs("form", { onSubmit: start, "data-oc-signin-email": "", children: [
3317
+ return /* @__PURE__ */ jsxRuntime.jsxs("form", { onSubmit: start, noValidate: true, "data-oc-signin-email": "", children: [
3269
3318
  /* @__PURE__ */ jsxRuntime.jsx(FlowHeader, { children: "We email you a 6-digit code. No password, and no wallet needed to start. Add a Bitcoin address any time: a way in that only you hold." }),
3270
3319
  /* @__PURE__ */ jsxRuntime.jsx(Label, { htmlFor: `${uid}-email`, children: "Email" }),
3271
3320
  /* @__PURE__ */ jsxRuntime.jsx(
@@ -3282,13 +3331,24 @@ function EmailFlow({ authOrigin, add, credentials, onSuccess }) {
3282
3331
  },
3283
3332
  placeholder: "you@example.com",
3284
3333
  required: true,
3334
+ autoFocus: back,
3285
3335
  "aria-invalid": emailError ? true : void 0,
3336
+ "aria-describedby": describedBy(emailError && ids.emailError),
3286
3337
  style: inputStyle2
3287
3338
  }
3288
3339
  ),
3289
- emailError && /* @__PURE__ */ jsxRuntime.jsx(ErrorLine2, { children: emailError }),
3290
- /* @__PURE__ */ jsxRuntime.jsx("button", { type: "submit", disabled: submitting, style: submitStyle(submitting), children: submitting ? "Sending\u2026" : /* @__PURE__ */ jsxRuntime.jsx(Submit, { children: "Send one-time code" }) })
3291
- ] });
3340
+ emailError && /* @__PURE__ */ jsxRuntime.jsx(ErrorLine2, { id: ids.emailError, children: emailError }),
3341
+ /* @__PURE__ */ jsxRuntime.jsx(
3342
+ "button",
3343
+ {
3344
+ type: "submit",
3345
+ "aria-disabled": submitting || void 0,
3346
+ style: submitStyle(submitting),
3347
+ children: submitting ? "Sending\u2026" : /* @__PURE__ */ jsxRuntime.jsx(Submit, { children: "Send one-time code" })
3348
+ }
3349
+ ),
3350
+ /* @__PURE__ */ jsxRuntime.jsx(Busy, { children: submitting ? "Sending\u2026" : null })
3351
+ ] }, "enter");
3292
3352
  }
3293
3353
  return /* @__PURE__ */ jsxRuntime.jsxs("form", { onSubmit: verify, "data-oc-signin-email-verify": "", children: [
3294
3354
  /* @__PURE__ */ jsxRuntime.jsxs(FlowHeader, { children: [
@@ -3316,26 +3376,29 @@ function EmailFlow({ authOrigin, add, credentials, onSuccess }) {
3316
3376
  required: true,
3317
3377
  autoFocus: true,
3318
3378
  "aria-invalid": codeError ? true : void 0,
3379
+ "aria-describedby": describedBy(codeError && ids.codeError),
3319
3380
  style: { ...inputStyle2, letterSpacing: "0.4em", fontSize: 16 }
3320
3381
  }
3321
3382
  ),
3322
- codeError && /* @__PURE__ */ jsxRuntime.jsx(ErrorLine2, { children: codeError }),
3383
+ codeError && /* @__PURE__ */ jsxRuntime.jsx(ErrorLine2, { id: ids.codeError, children: codeError }),
3323
3384
  /* @__PURE__ */ jsxRuntime.jsx(
3324
3385
  "button",
3325
3386
  {
3326
3387
  type: "submit",
3327
- disabled: submitting || code.length !== 6,
3388
+ disabled: code.length !== 6,
3389
+ "aria-disabled": submitting || void 0,
3328
3390
  style: submitStyle(submitting || code.length !== 6),
3329
3391
  children: submitting ? "Verifying\u2026" : /* @__PURE__ */ jsxRuntime.jsx(Submit, { children: "Verify \xB7 sign me in" })
3330
3392
  }
3331
3393
  ),
3394
+ /* @__PURE__ */ jsxRuntime.jsx(Busy, { children: submitting ? "Verifying\u2026" : null }),
3332
3395
  /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
3333
3396
  /* @__PURE__ */ jsxRuntime.jsx(
3334
3397
  "button",
3335
3398
  {
3336
3399
  type: "button",
3337
3400
  onClick: () => void resend(),
3338
- disabled: submitting,
3401
+ "aria-disabled": submitting || void 0,
3339
3402
  style: linkButtonStyle,
3340
3403
  children: "Send a new code"
3341
3404
  }
@@ -3345,6 +3408,7 @@ function EmailFlow({ authOrigin, add, credentials, onSuccess }) {
3345
3408
  {
3346
3409
  type: "button",
3347
3410
  onClick: () => {
3411
+ setBack(true);
3348
3412
  setStage("enter");
3349
3413
  setCode("");
3350
3414
  setToken(null);
@@ -3355,7 +3419,7 @@ function EmailFlow({ authOrigin, add, credentials, onSuccess }) {
3355
3419
  }
3356
3420
  )
3357
3421
  ] })
3358
- ] });
3422
+ ] }, "code");
3359
3423
  }
3360
3424
  function Submit({ children }) {
3361
3425
  return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
@@ -3364,6 +3428,7 @@ function Submit({ children }) {
3364
3428
  ] });
3365
3429
  }
3366
3430
  function FlowHeader({
3431
+ id,
3367
3432
  label,
3368
3433
  children
3369
3434
  }) {
@@ -3385,6 +3450,7 @@ function FlowHeader({
3385
3450
  /* @__PURE__ */ jsxRuntime.jsx(
3386
3451
  "p",
3387
3452
  {
3453
+ id,
3388
3454
  style: {
3389
3455
  color: "var(--muted-foreground, #a1a1aa)",
3390
3456
  fontSize: signinRoleSize("text", "13px"),
@@ -3485,10 +3551,11 @@ function submitStyle(disabled) {
3485
3551
  width: "100%"
3486
3552
  };
3487
3553
  }
3488
- function ErrorLine2({ children }) {
3554
+ function ErrorLine2({ id, children }) {
3489
3555
  return /* @__PURE__ */ jsxRuntime.jsx(
3490
3556
  "p",
3491
3557
  {
3558
+ id,
3492
3559
  role: "alert",
3493
3560
  style: {
3494
3561
  marginTop: 6,
@@ -3502,6 +3569,29 @@ function ErrorLine2({ children }) {
3502
3569
  }
3503
3570
  );
3504
3571
  }
3572
+ function describedBy(...ids) {
3573
+ return ids.filter(Boolean).join(" ") || void 0;
3574
+ }
3575
+ function Busy({ children }) {
3576
+ return /* @__PURE__ */ jsxRuntime.jsx(
3577
+ "span",
3578
+ {
3579
+ role: "status",
3580
+ style: {
3581
+ position: "absolute",
3582
+ width: 1,
3583
+ height: 1,
3584
+ margin: -1,
3585
+ padding: 0,
3586
+ overflow: "hidden",
3587
+ clip: "rect(0 0 0 0)",
3588
+ whiteSpace: "nowrap",
3589
+ border: 0
3590
+ },
3591
+ children: children ?? ""
3592
+ }
3593
+ );
3594
+ }
3505
3595
  function Hint({ children }) {
3506
3596
  return /* @__PURE__ */ jsxRuntime.jsx(
3507
3597
  "p",