@useauthio/react 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,247 @@
1
+ import { AuthioError } from "@useauthio/node";
2
+ import { startRegistration } from "@simplewebauthn/browser";
3
+ import { authioFetch } from "./fetch";
4
+ import { isBrowser } from "./ssr";
5
+
6
+ export interface AuthioPasskey {
7
+ id: string;
8
+ nickname: string | null;
9
+ aaguid: string | null;
10
+ authenticator_name: string;
11
+ transports: string[];
12
+ sign_count: number;
13
+ last_used_at: string | null;
14
+ created_at: string;
15
+ }
16
+
17
+ /** Shared options for authenticated `/v1/me/passkeys` calls. */
18
+ export interface PasskeyApiOptions {
19
+ apiUrl: string;
20
+ projectId: string;
21
+ accessToken: string;
22
+ signal?: AbortSignal;
23
+ fetchImpl?: typeof fetch;
24
+ }
25
+
26
+ export interface AddPasskeyOptions extends PasskeyApiOptions {
27
+ email: string;
28
+ /**
29
+ * WebAuthn ceremony origin (sent as `X-Authio-Origin`). Defaults to
30
+ * `window.location.origin` in the browser.
31
+ */
32
+ origin?: string;
33
+ }
34
+
35
+ export interface EnrollPasskeyOptions extends PasskeyApiOptions {
36
+ email: string;
37
+ /** Hosted sign-in UI base URL (lobby / custom domain). */
38
+ signInUrl: string;
39
+ /** Where to return after enrollment (`redirect_uri` query param). */
40
+ returnUrl?: string;
41
+ /** Post-login path on the return host (`next` query param). */
42
+ next?: string;
43
+ }
44
+
45
+ export interface BuildEnrollPasskeyUrlOptions {
46
+ signInUrl: string;
47
+ projectId: string;
48
+ email: string;
49
+ registerToken: string;
50
+ redirectUri?: string;
51
+ next?: string;
52
+ }
53
+
54
+ /** Normalize a hosted-UI base URL (no trailing slash). */
55
+ export function signInOrigin(signInUrl: string): string {
56
+ return signInUrl.replace(/\/$/, "");
57
+ }
58
+
59
+ /**
60
+ * True when inline WebAuthn registration can run on the current page
61
+ * (same origin as the hosted sign-in UI / custom auth domain).
62
+ */
63
+ export function canEnrollPasskeyEmbedded(signInUrl: string): boolean {
64
+ if (!isBrowser()) return false;
65
+ return window.location.origin === signInOrigin(signInUrl);
66
+ }
67
+
68
+ /** Build the hosted-UI URL for `mode=add_credential` passkey enrollment. */
69
+ export function buildEnrollPasskeyUrl(
70
+ opts: BuildEnrollPasskeyUrlOptions,
71
+ ): string {
72
+ const url = new URL(signInOrigin(opts.signInUrl));
73
+ url.searchParams.set("mode", "add_credential");
74
+ url.searchParams.set("project_id", opts.projectId);
75
+ url.searchParams.set("email", opts.email);
76
+ url.searchParams.set("token", opts.registerToken);
77
+ if (opts.redirectUri) {
78
+ url.searchParams.set("redirect_uri", opts.redirectUri);
79
+ }
80
+ if (opts.next) {
81
+ url.searchParams.set("next", opts.next);
82
+ }
83
+ return url.toString();
84
+ }
85
+
86
+ function bearerHeaders(
87
+ accessToken: string,
88
+ origin?: string,
89
+ ): Record<string, string> {
90
+ const h: Record<string, string> = {
91
+ Authorization: `Bearer ${accessToken}`,
92
+ };
93
+ if (origin) h["X-Authio-Origin"] = origin;
94
+ return h;
95
+ }
96
+
97
+ /** Mint a short-lived JWT for add-credential WebAuthn (`register-intent`). */
98
+ export async function mintPasskeyRegisterIntent(
99
+ opts: PasskeyApiOptions,
100
+ ): Promise<{ token: string; expiresIn: number }> {
101
+ const body = await authioFetch<{ token: string; expires_in: number }>({
102
+ apiUrl: opts.apiUrl,
103
+ projectId: opts.projectId,
104
+ path: "/v1/me/passkeys/register-intent",
105
+ method: "POST",
106
+ body: {},
107
+ signal: opts.signal,
108
+ fetchImpl: opts.fetchImpl,
109
+ extraHeaders: bearerHeaders(opts.accessToken),
110
+ });
111
+ return { token: body.token, expiresIn: body.expires_in };
112
+ }
113
+
114
+ /**
115
+ * Enroll a passkey by redirecting to the hosted sign-in UI on the
116
+ * sign-in origin (`mode=add_credential`). Use when the SPA origin
117
+ * differs from the WebAuthn RP ID.
118
+ */
119
+ export async function enrollPasskey(opts: EnrollPasskeyOptions): Promise<void> {
120
+ if (!isBrowser()) {
121
+ throw new AuthioError({
122
+ code: "not_in_browser",
123
+ message: "enrollPasskey can only be invoked in a browser environment.",
124
+ status: 0,
125
+ });
126
+ }
127
+
128
+ const intent = await mintPasskeyRegisterIntent(opts);
129
+ const redirectUri =
130
+ opts.returnUrl ?? (typeof window !== "undefined" ? window.location.href : "");
131
+ const target = buildEnrollPasskeyUrl({
132
+ signInUrl: opts.signInUrl,
133
+ projectId: opts.projectId,
134
+ email: opts.email,
135
+ registerToken: intent.token,
136
+ redirectUri,
137
+ next: opts.next,
138
+ });
139
+ window.location.assign(target);
140
+ }
141
+
142
+ /**
143
+ * Enroll a passkey inline on the current origin via WebAuthn.
144
+ *
145
+ * 1. `POST /v1/me/passkeys/register-intent`
146
+ * 2. `POST /v1/auth/passkey/register/options` + ceremony
147
+ * 3. `POST /v1/auth/passkey/register/verify`
148
+ */
149
+ export async function addPasskey(opts: AddPasskeyOptions): Promise<void> {
150
+ if (!isBrowser()) {
151
+ throw new AuthioError({
152
+ code: "not_in_browser",
153
+ message: "addPasskey can only be invoked in a browser environment.",
154
+ status: 0,
155
+ });
156
+ }
157
+
158
+ const origin = opts.origin ?? window.location.origin;
159
+ const intent = await mintPasskeyRegisterIntent(opts);
160
+
161
+ const options = await authioFetch<
162
+ Parameters<typeof startRegistration>[0]["optionsJSON"]
163
+ >({
164
+ apiUrl: opts.apiUrl,
165
+ projectId: opts.projectId,
166
+ path: "/v1/auth/passkey/register/options",
167
+ method: "POST",
168
+ body: { email: opts.email },
169
+ signal: opts.signal,
170
+ fetchImpl: opts.fetchImpl,
171
+ extraHeaders: bearerHeaders(intent.token, origin),
172
+ });
173
+
174
+ let attestation: Awaited<ReturnType<typeof startRegistration>>;
175
+ try {
176
+ attestation = await startRegistration({ optionsJSON: options });
177
+ } catch (err) {
178
+ throw new AuthioError({
179
+ code: "webauthn_cancelled",
180
+ message:
181
+ err instanceof Error
182
+ ? err.message
183
+ : "Passkey registration cancelled by user.",
184
+ status: 0,
185
+ });
186
+ }
187
+
188
+ await authioFetch<{ ok?: boolean }>({
189
+ apiUrl: opts.apiUrl,
190
+ projectId: opts.projectId,
191
+ path: "/v1/auth/passkey/register/verify",
192
+ method: "POST",
193
+ body: { email: opts.email, credential: attestation },
194
+ signal: opts.signal,
195
+ fetchImpl: opts.fetchImpl,
196
+ extraHeaders: bearerHeaders(intent.token, origin),
197
+ });
198
+ }
199
+
200
+ /** List passkeys for the signed-in user (`GET /v1/me/passkeys`). */
201
+ export async function listPasskeys(
202
+ opts: PasskeyApiOptions,
203
+ ): Promise<AuthioPasskey[]> {
204
+ const res = await authioFetch<{ data: AuthioPasskey[] }>({
205
+ apiUrl: opts.apiUrl,
206
+ projectId: opts.projectId,
207
+ path: "/v1/me/passkeys",
208
+ signal: opts.signal,
209
+ fetchImpl: opts.fetchImpl,
210
+ extraHeaders: bearerHeaders(opts.accessToken),
211
+ });
212
+ return res.data ?? [];
213
+ }
214
+
215
+ /** Rename a passkey (`PATCH /v1/me/passkeys/{credentialId}`). */
216
+ export async function renamePasskey(
217
+ opts: PasskeyApiOptions,
218
+ credentialId: string,
219
+ name: string,
220
+ ): Promise<void> {
221
+ await authioFetch<{ ok: boolean }>({
222
+ apiUrl: opts.apiUrl,
223
+ projectId: opts.projectId,
224
+ path: `/v1/me/passkeys/${encodeURIComponent(credentialId)}`,
225
+ method: "PATCH",
226
+ body: { nickname: name },
227
+ signal: opts.signal,
228
+ fetchImpl: opts.fetchImpl,
229
+ extraHeaders: bearerHeaders(opts.accessToken),
230
+ });
231
+ }
232
+
233
+ /** Revoke a passkey (`DELETE /v1/me/passkeys/{credentialId}`). */
234
+ export async function revokePasskey(
235
+ opts: PasskeyApiOptions,
236
+ credentialId: string,
237
+ ): Promise<void> {
238
+ await authioFetch<{ ok: boolean }>({
239
+ apiUrl: opts.apiUrl,
240
+ projectId: opts.projectId,
241
+ path: `/v1/me/passkeys/${encodeURIComponent(credentialId)}`,
242
+ method: "DELETE",
243
+ signal: opts.signal,
244
+ fetchImpl: opts.fetchImpl,
245
+ extraHeaders: bearerHeaders(opts.accessToken),
246
+ });
247
+ }
package/src/provider.tsx CHANGED
@@ -9,17 +9,21 @@ import React, {
9
9
  import { AuthioError } from "@useauthio/node";
10
10
  import { authioFetch } from "./fetch";
11
11
  import { createDefaultVerifier, readJwtExp } from "./jwt";
12
+ import { ActivityTracker } from "./activity";
12
13
  import { RefreshScheduler } from "./refresh";
13
14
  import { isBrowser } from "./ssr";
14
15
  import { createTokenStorage, type TokenStorage } from "./storage";
15
16
  import { mintLobbySignInUrl } from "./lobby-context";
16
17
  import { noopEmitter, type TelemetryEmitter } from "./telemetry";
17
- import type {
18
- AuthioContextValue,
19
- AuthioProviderProps,
20
- AuthioStatus,
21
- AuthioTokenVerifier,
22
- AuthioUser,
18
+ import {
19
+ coerceSessionPolicy,
20
+ type AuthioContextValue,
21
+ type AuthioProviderProps,
22
+ type AuthioStatus,
23
+ type AuthioTokenVerifier,
24
+ type AuthioUser,
25
+ type RawSessionPolicy,
26
+ type SessionPolicy,
23
27
  } from "./types";
24
28
 
25
29
  export const AuthioContext = createContext<AuthioContextValue | null>(null);
@@ -30,8 +34,17 @@ interface RefreshEnvelope {
30
34
  refresh_token?: string;
31
35
  expires_at?: string;
32
36
  user?: RawUser | null;
37
+ session_policy?: RawSessionPolicy;
33
38
  }
34
39
 
40
+ /**
41
+ * Grace window around a refresh inside which user activity still counts
42
+ * as "after" it. The tracker throttles writes to 1/s, so an interaction
43
+ * landing just after a refresh may carry a timestamp just before it;
44
+ * we err toward refreshing.
45
+ */
46
+ const ACTIVITY_GRACE_MS = 1000;
47
+
35
48
  interface RawUser {
36
49
  id?: string;
37
50
  user_id?: string;
@@ -77,6 +90,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
77
90
  projectId,
78
91
  storage: storageMode = "memory",
79
92
  refreshLeadSeconds = DEFAULT_REFRESH_LEAD,
93
+ idleRefresh = "defer",
80
94
  onTelemetryEvent,
81
95
  fetch: fetchImpl,
82
96
  signInUrl,
@@ -116,8 +130,24 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
116
130
  fetchImpl,
117
131
  signInUrl,
118
132
  emit,
133
+ idleRefresh,
119
134
  });
120
- propsRef.current = { apiUrl, projectId, fetchImpl, signInUrl, emit };
135
+ propsRef.current = { apiUrl, projectId, fetchImpl, signInUrl, emit, idleRefresh };
136
+
137
+ // User-activity tracker + the two timestamps the idle-deferral rule
138
+ // compares. Refs, not state: the scheduler reads them from a timer
139
+ // callback and a re-render must never re-create the tracker.
140
+ const activityRef = useRef<ActivityTracker | null>(null);
141
+ // Lazily (re)created so a StrictMode double-mount, which destroys the
142
+ // tracker in the simulated unmount, gets a fresh one on the re-run.
143
+ const getTracker = useCallback((): ActivityTracker => {
144
+ if (activityRef.current === null) {
145
+ activityRef.current = new ActivityTracker();
146
+ }
147
+ return activityRef.current;
148
+ }, []);
149
+ const lastRefreshAtRef = useRef(0);
150
+ const policyRef = useRef<SessionPolicy | null>(null);
121
151
 
122
152
  useEffect(() => {
123
153
  if (!projectId) {
@@ -143,6 +173,20 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
143
173
  skipInitialRefresh ? "unauthenticated" : "loading",
144
174
  );
145
175
  const [accessToken, setAccessToken] = useState<string | null>(null);
176
+ const [sessionPolicy, setSessionPolicy] = useState<SessionPolicy | null>(null);
177
+
178
+ /** Adopt a policy from an envelope and mark "refreshed now". */
179
+ const adoptPolicy = useCallback((policy: SessionPolicy | null) => {
180
+ policyRef.current = policy;
181
+ setSessionPolicy(policy);
182
+ lastRefreshAtRef.current = Date.now();
183
+ }, []);
184
+
185
+ const clearPolicy = useCallback(() => {
186
+ policyRef.current = null;
187
+ setSessionPolicy(null);
188
+ lastRefreshAtRef.current = 0;
189
+ }, []);
146
190
 
147
191
  /**
148
192
  * Single refresh attempt. Returns `true` on success (state has
@@ -199,6 +243,13 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
199
243
  setAccessToken(token);
200
244
  if (env.user) setUser(coerceUser(env.user));
201
245
  setStatus("authenticated");
246
+ // Older auth-core omits session_policy; keep whatever we last saw
247
+ // rather than flapping to null and re-enabling timer refresh.
248
+ adoptPolicy(
249
+ env.session_policy !== undefined
250
+ ? coerceSessionPolicy(env.session_policy)
251
+ : policyRef.current,
252
+ );
202
253
  p.emit({
203
254
  kind: "refresh_succeeded",
204
255
  timestamp: Date.now(),
@@ -222,16 +273,17 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
222
273
  });
223
274
  return false;
224
275
  }
225
- }, []);
276
+ }, [adoptPolicy]);
226
277
 
227
278
  // Re-spin the scheduler whenever the lead window changes.
228
279
  useEffect(() => {
229
- schedulerRef.current = new RefreshScheduler({
280
+ const scheduler = new RefreshScheduler({
230
281
  leadSeconds: refreshLeadSeconds,
231
282
  run: performRefresh,
232
283
  onGiveUp: () => {
233
284
  storageRef.current!.clear();
234
285
  refreshTokenRef.current = null;
286
+ clearPolicy();
235
287
  setAccessToken(null);
236
288
  setUser(null);
237
289
  setStatus("unauthenticated");
@@ -242,12 +294,48 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
242
294
  timestamp: Date.now(),
243
295
  runAt,
244
296
  }),
297
+ // Idle rule: hold the timer refresh when the effective policy has
298
+ // an inactivity timeout and the user hasn't touched the page since
299
+ // the last refresh. Without a policy (legacy projects, old
300
+ // auth-core) this is never true and behaviour is unchanged.
301
+ shouldDefer: () => {
302
+ if (propsRef.current.idleRefresh === "always") return false;
303
+ const policy = policyRef.current;
304
+ if (!policy || policy.idleTimeoutMin <= 0) return false;
305
+ const lastActivity = getTracker().lastActivityAt();
306
+ return lastActivity + ACTIVITY_GRACE_MS < lastRefreshAtRef.current;
307
+ },
308
+ onDeferred: (reason) =>
309
+ propsRef.current.emit({
310
+ kind: "refresh_deferred",
311
+ timestamp: Date.now(),
312
+ reason,
313
+ }),
314
+ });
315
+ schedulerRef.current = scheduler;
316
+ // The next interaction after an idle deferral re-arms the timer —
317
+ // immediately, if the token is already inside its lead window.
318
+ const tracker = getTracker();
319
+ const unsubscribe = tracker.onActivity(() => {
320
+ if (scheduler.deferredReason() !== "idle") return;
321
+ propsRef.current.emit({ kind: "refresh_resumed", timestamp: Date.now() });
322
+ scheduler.resume();
245
323
  });
246
324
  return () => {
247
- schedulerRef.current?.destroy();
248
- schedulerRef.current = null;
325
+ unsubscribe();
326
+ scheduler.destroy();
327
+ if (schedulerRef.current === scheduler) schedulerRef.current = null;
328
+ };
329
+ }, [refreshLeadSeconds, performRefresh, clearPolicy, getTracker]);
330
+
331
+ // Tear the activity tracker down with the provider.
332
+ useEffect(() => {
333
+ const tracker = getTracker();
334
+ return () => {
335
+ tracker.destroy();
336
+ if (activityRef.current === tracker) activityRef.current = null;
249
337
  };
250
- }, [refreshLeadSeconds, performRefresh]);
338
+ }, [getTracker]);
251
339
 
252
340
  // Initial bootstrap.
253
341
  useEffect(() => {
@@ -390,12 +478,13 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
390
478
  storageRef.current!.clear();
391
479
  refreshTokenRef.current = null;
392
480
  schedulerRef.current?.clear();
481
+ clearPolicy();
393
482
  setAccessToken(null);
394
483
  setUser(null);
395
484
  setStatus("unauthenticated");
396
485
  p.emit({ kind: "sign_out", timestamp: Date.now() });
397
486
  }
398
- }, []);
487
+ }, [clearPolicy]);
399
488
 
400
489
  const refresh = useCallback(
401
490
  (): Promise<boolean> => performRefresh(),
@@ -407,6 +496,7 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
407
496
  accessToken: string;
408
497
  refreshToken?: string | null;
409
498
  user?: AuthioUser | null;
499
+ sessionPolicy?: SessionPolicy | null;
410
500
  }): Promise<void> => {
411
501
  const p = propsRef.current;
412
502
  const verification = await verifierRef
@@ -441,6 +531,9 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
441
531
  setAccessToken(input.accessToken);
442
532
  if (input.user) setUser(input.user);
443
533
  setStatus("authenticated");
534
+ adoptPolicy(
535
+ input.sessionPolicy !== undefined ? input.sessionPolicy : policyRef.current,
536
+ );
444
537
  p.emit({
445
538
  kind: "sign_in_completed",
446
539
  timestamp: Date.now(),
@@ -451,14 +544,21 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
451
544
  schedulerRef.current?.scheduleAt(exp);
452
545
  }
453
546
  },
454
- [],
547
+ [adoptPolicy],
455
548
  );
456
549
 
550
+ const resolvedSignInUrl = signInUrl ?? DEFAULT_SIGN_IN_URL;
551
+
457
552
  const value = useMemo<AuthioContextValue>(
458
553
  () => ({
459
554
  user,
460
555
  status,
461
556
  accessToken,
557
+ sessionPolicy,
558
+ apiUrl,
559
+ projectId,
560
+ signInUrl: resolvedSignInUrl,
561
+ fetchImpl,
462
562
  getAccessToken,
463
563
  signIn,
464
564
  signOut,
@@ -469,6 +569,11 @@ export function AuthioProvider(props: AuthioProviderProps): React.ReactElement {
469
569
  user,
470
570
  status,
471
571
  accessToken,
572
+ sessionPolicy,
573
+ apiUrl,
574
+ projectId,
575
+ resolvedSignInUrl,
576
+ fetchImpl,
472
577
  getAccessToken,
473
578
  signIn,
474
579
  signOut,
package/src/refresh.ts CHANGED
@@ -10,6 +10,8 @@ const BACKOFF_DELAYS_MS = [1000, 2000, 4000, 8000, 16000, 30000];
10
10
  /** After five consecutive failures we surrender and transition to unauthenticated. */
11
11
  const MAX_ATTEMPTS = 5;
12
12
 
13
+ export type RefreshDeferReason = "hidden" | "idle";
14
+
13
15
  export interface RefreshSchedulerOptions {
14
16
  /** Schedule the silent refresh this many seconds before `exp`. */
15
17
  leadSeconds: number;
@@ -19,6 +21,15 @@ export interface RefreshSchedulerOptions {
19
21
  onGiveUp: () => void;
20
22
  /** Optional sink for "next refresh scheduled at" telemetry. */
21
23
  onScheduled?: (runAt: number) => void;
24
+ /**
25
+ * Consulted when the timer fires (after the hidden-tab check). Return
26
+ * `true` to hold the refresh until `resume()` is called — the
27
+ * provider uses this to skip refreshing while the user is idle under
28
+ * an inactivity policy. Omit for the legacy always-refresh behaviour.
29
+ */
30
+ shouldDefer?: () => boolean;
31
+ /** Fired when a tick is held back, with the reason. */
32
+ onDeferred?: (reason: RefreshDeferReason) => void;
22
33
  }
23
34
 
24
35
  /**
@@ -30,6 +41,10 @@ export interface RefreshSchedulerOptions {
30
41
  * - When the timer fires, if the tab is hidden, we DEFER — the
31
42
  * visibilitychange listener picks up where we left off when the
32
43
  * tab returns. Saves battery on a sleeping background tab.
44
+ * - If `shouldDefer()` says so (user idle under an inactivity
45
+ * policy), we also DEFER and wait for `resume()` — the provider
46
+ * calls it on the next user interaction, which re-runs the tick
47
+ * immediately when the token is inside its lead window.
33
48
  * - On failure we walk the `BACKOFF_DELAYS_MS` step list. After
34
49
  * `MAX_ATTEMPTS` failures the scheduler calls `onGiveUp` and
35
50
  * stops — the provider then transitions to `unauthenticated`.
@@ -41,6 +56,7 @@ export class RefreshScheduler {
41
56
  private attempts = 0;
42
57
  private lastExp: number | null = null;
43
58
  private destroyed = false;
59
+ private deferred: RefreshDeferReason | null = null;
44
60
  private visibilityHandler: (() => void) | null = null;
45
61
 
46
62
  constructor(private readonly opts: RefreshSchedulerOptions) {
@@ -55,10 +71,16 @@ export class RefreshScheduler {
55
71
  }
56
72
  }
57
73
 
74
+ /** Whether the last tick was held back (and why). `null` when not deferred. */
75
+ deferredReason(): RefreshDeferReason | null {
76
+ return this.deferred;
77
+ }
78
+
58
79
  scheduleAt(exp: number): void {
59
80
  if (this.destroyed) return;
60
81
  this.lastExp = exp;
61
82
  this.attempts = 0;
83
+ this.deferred = null;
62
84
  this.clear();
63
85
  const now = Math.floor(Date.now() / 1000);
64
86
  const delayMs = Math.max(0, (exp - now - this.opts.leadSeconds) * 1000);
@@ -66,14 +88,33 @@ export class RefreshScheduler {
66
88
  this.timer = setTimeout(() => void this.tick(), delayMs);
67
89
  }
68
90
 
91
+ /**
92
+ * Re-arm after a deferral. No-op unless a tick is currently held
93
+ * back. Re-schedules against the remembered `exp`, so a token that
94
+ * is already inside its lead window refreshes immediately.
95
+ */
96
+ resume(): void {
97
+ if (this.destroyed || this.deferred === null || this.lastExp === null) return;
98
+ this.scheduleAt(this.lastExp);
99
+ }
100
+
69
101
  private async tick(): Promise<void> {
70
102
  this.timer = null;
71
103
  if (this.destroyed) return;
72
104
  if (isTabHidden()) {
73
105
  // Defer until the tab is visible again; the visibility handler
74
106
  // will call scheduleAt when the user returns.
107
+ this.deferred = "hidden";
108
+ this.opts.onDeferred?.("hidden");
109
+ return;
110
+ }
111
+ if (this.opts.shouldDefer?.()) {
112
+ // User is idle under an inactivity policy. Hold until resume().
113
+ this.deferred = "idle";
114
+ this.opts.onDeferred?.("idle");
75
115
  return;
76
116
  }
117
+ this.deferred = null;
77
118
  let ok = false;
78
119
  try {
79
120
  ok = await this.opts.run();