@axa-fr/react-oidc 7.27.15 → 7.27.16

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.
package/README.md CHANGED
@@ -281,6 +281,15 @@ const defaultDemonstratingProofOfPossessionConfiguration: DemonstratingProofOfPo
281
281
 
282
282
  ## How to consume
283
283
 
284
+ > **Note (issue #1679):** `useOidc`, `useOidcUser`, `useOidcAccessToken` and
285
+ > `useOidcIdToken` are safe to call **outside** of an `<OidcProvider>` (e.g.
286
+ > in unit tests or Storybook stories). When no provider is mounted, they
287
+ > emit a single `console.warn` per configuration name and return stable
288
+ > default values (`isAuthenticated: false`, `oidcUser: null`,
289
+ > `accessToken: null`, `idToken: null`, with no-op `login`/`logout`/
290
+ > `renewTokens`/`reloadOidcUser`). Use `OidcClient.getOrThrow(name)` if you
291
+ > prefer the previous fail-fast behaviour.
292
+
284
293
  "useOidc" returns all props from the Hook :
285
294
 
286
295
  ```javascript
@@ -1 +1 @@
1
- {"version":3,"file":"FetchToken.d.ts","sourceRoot":"","sources":["../src/FetchToken.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAc,MAAM,qBAAqB,CAAC;AAGxD,MAAM,WAAW,2BAA2B;IAC1C,KAAK,CAAC,EAAE,KAAK,CAAC;CACf;AAgBD,eAAO,MAAM,aAAa,GAEtB,QAAO,KAAY,EACnB,0BAA4C,EAC5C,iCAAgC,OAAe,MAEjD,qBAAgB,MACf,OAAO,2BAA2B,4CAOlC,CAAC;AAEJ,eAAO,MAAM,YAAY,GACvB,QAAO,KAAY,EACnB,0BAA4C,EAC5C,iCAAgC,OAAe;mBAMrC,WAAW,GAAG,GAAG,SAAS,WAAW;CAYhD,CAAC"}
1
+ {"version":3,"file":"FetchToken.d.ts","sourceRoot":"","sources":["../src/FetchToken.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAc,MAAM,qBAAqB,CAAC;AAGxD,MAAM,WAAW,2BAA2B;IAC1C,KAAK,CAAC,EAAE,KAAK,CAAC;CACf;AAgBD,eAAO,MAAM,aAAa,GAEtB,QAAO,KAAY,EACnB,0BAA4C,EAC5C,iCAAgC,OAAe,MAEjD,qBAAgB,MACf,OAAO,2BAA2B,4CAOlC,CAAC;AAEJ,eAAO,MAAM,YAAY,GACvB,QAAO,KAAY,EACnB,0BAA4C,EAC5C,iCAAgC,OAAe;mBAQrC,WAAW,GAAG,GAAG,SAAS,WAAW;CAYhD,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"OidcSecure.d.ts","sourceRoot":"","sources":["../src/OidcSecure.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAc,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,EAAE,EAAE,EAAE,iBAAiB,EAAa,MAAM,OAAO,CAAC;AAEzD,MAAM,MAAM,eAAe,GAAG;IAC5B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,MAAM,CAAC,EAAE,SAAS,CAAC;IACnB,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF,eAAO,MAAM,UAAU,EAAE,EAAE,CAAC,iBAAiB,CAAC,eAAe,CAAC,CAkB7D,CAAC;AAEF,eAAO,MAAM,cAAc,GAEvB,kBAAkB,EAAE,CAAC,iBAAiB,CAAC,eAAe,CAAC,CAAC,EACxD,kBAAmB,EACnB,YAAa,EACb,0BAA6B,MAE/B,UAAK,4CAMJ,CAAC"}
1
+ {"version":3,"file":"OidcSecure.d.ts","sourceRoot":"","sources":["../src/OidcSecure.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAc,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,EAAE,EAAE,EAAE,iBAAiB,EAAa,MAAM,OAAO,CAAC;AAEzD,MAAM,MAAM,eAAe,GAAG;IAC5B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,MAAM,CAAC,EAAE,SAAS,CAAC;IACnB,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF,eAAO,MAAM,UAAU,EAAE,EAAE,CAAC,iBAAiB,CAAC,eAAe,CAAC,CAoB7D,CAAC;AAEF,eAAO,MAAM,cAAc,GAEvB,kBAAkB,EAAE,CAAC,iBAAiB,CAAC,eAAe,CAAC,CAAC,EACxD,kBAAmB,EACnB,YAAa,EACb,0BAA6B,MAE/B,UAAK,4CAMJ,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"ReactOidc.d.ts","sourceRoot":"","sources":["../src/ReactOidc.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAc,SAAS,EAAU,MAAM,qBAAqB,CAAC;AAkBpE,eAAO,MAAM,OAAO,GAAI,0BAA4C;2BA4BlD,MAAM,GAAG,SAAS,WACxB,SAAS,GAAG,SAAS,qCAEtB,MAAM;4BAWC,MAAM,GAAG,IAAI,GAAG,SAAS,WAC/B,SAAS,GAAG,SAAS;2BAKrB,SAAS,GAAG,SAAS,KAC5B,OAAO,CAAC,eAAe,GAAG,WAAW,CAAC;;CAe1C,CAAC;AAsBF,MAAM,MAAM,eAAe,GAAG;IAC5B,WAAW,CAAC,EAAE,GAAG,CAAC;IAClB,kBAAkB,CAAC,EAAE,GAAG,CAAC;IACzB,6CAA6C,CAAC,EAAE,GAAG,CAAC;CACrD,CAAC;AASF,eAAO,MAAM,kBAAkB,GAAI,0BAA4C,oBAsC9E,CAAC;AAeF,MAAM,MAAM,WAAW,GAAG;IACxB,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,cAAc,CAAC,EAAE,GAAG,CAAC;CACtB,CAAC;AAEF,eAAO,MAAM,cAAc,GAAI,0BAA4C,gBAiC1E,CAAC"}
1
+ {"version":3,"file":"ReactOidc.d.ts","sourceRoot":"","sources":["../src/ReactOidc.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAc,SAAS,EAAU,MAAM,qBAAqB,CAAC;AAoBpE,eAAO,MAAM,OAAO,GAAI,0BAA4C;2BAkClD,MAAM,GAAG,SAAS,WACxB,SAAS,GAAG,SAAS,qCAEtB,MAAM,KACZ,OAAO,CAAC,OAAO,CAAC;4BASH,MAAM,GAAG,IAAI,GAAG,SAAS,WAC/B,SAAS,GAAG,SAAS,KAC5B,OAAO,CAAC,IAAI,CAAC;2BASN,SAAS,GAAG,SAAS,KAC5B,OAAO,CAAC,eAAe,GAAG,WAAW,CAAC;;CAoB1C,CAAC;AAyBF,MAAM,MAAM,eAAe,GAAG;IAC5B,WAAW,CAAC,EAAE,GAAG,CAAC;IAClB,kBAAkB,CAAC,EAAE,GAAG,CAAC;IACzB,6CAA6C,CAAC,EAAE,GAAG,CAAC;CACrD,CAAC;AASF,eAAO,MAAM,kBAAkB,GAAI,0BAA4C,oBA2C9E,CAAC;AAkBF,MAAM,MAAM,WAAW,GAAG;IACxB,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,cAAc,CAAC,EAAE,GAAG,CAAC;CACtB,CAAC;AAEF,eAAO,MAAM,cAAc,GAAI,0BAA4C,gBAsC1E,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"User.d.ts","sourceRoot":"","sources":["../src/User.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,KAAK,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAGpE,oBAAY,cAAc;IACxB,eAAe,oBAAoB;IACnC,OAAO,iBAAiB;IACxB,MAAM,gBAAgB;IACtB,YAAY,uBAAuB;CACpC;AAED,MAAM,MAAM,QAAQ,CAAC,CAAC,SAAS,YAAY,GAAG,YAAY,IAAI;IAC5D,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC;IACf,MAAM,EAAE,cAAc,CAAC;CACxB,CAAC;AAEF,eAAO,MAAM,WAAW,GAAI,CAAC,SAAS,YAAY,GAAG,YAAY,EAC/D,0BAA6B,EAC7B,2CAAyC;;;;CA+D1C,CAAC"}
1
+ {"version":3,"file":"User.d.ts","sourceRoot":"","sources":["../src/User.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,KAAK,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAKpE,oBAAY,cAAc;IACxB,eAAe,oBAAoB;IACnC,OAAO,iBAAiB;IACxB,MAAM,gBAAgB;IACtB,YAAY,uBAAuB;CACpC;AAED,MAAM,MAAM,QAAQ,CAAC,CAAC,SAAS,YAAY,GAAG,YAAY,IAAI;IAC5D,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC;IACf,MAAM,EAAE,cAAc,CAAC;CACxB,CAAC;AAEF,eAAO,MAAM,WAAW,GAAI,CAAC,SAAS,YAAY,GAAG,YAAY,EAC/D,0BAA6B,EAC7B,2CAAyC;;;;CAqE1C,CAAC"}
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ var _ = "default", v = (e, t, n = !1) => async (...r) => await t().fetchWithToke
9
9
  fetch: a
10
10
  });
11
11
  }, b = (e = null, n = _, r = !1) => {
12
- let i = e || window.fetch, a = t.get;
12
+ let i = e || window.fetch, a = t.getOrThrow;
13
13
  return { fetch: u((e, t) => v(i, () => a(n), r)(e, t), [
14
14
  i,
15
15
  n,
@@ -70,7 +70,7 @@ var _ = "default", v = (e, t, n = !1) => async (...r) => await t().fetchWithToke
70
70
  return d(() => {
71
71
  let e = !0;
72
72
  return (async () => {
73
- let n = t.get;
73
+ let n = t.getOrThrow;
74
74
  try {
75
75
  let o = n(r), { callbackPath: c } = await o.loginCallbackAsync(), l = c || "/";
76
76
  if (a) try {
@@ -145,12 +145,12 @@ var _ = "default", v = (e, t, n = !1) => async (...r) => await t().fetchWithToke
145
145
  })
146
146
  }), F = ({ configurationName: e }) => (d(() => {
147
147
  (async () => {
148
- t.get(e).silentLoginCallbackAsync();
148
+ t.getOrThrow(e).silentLoginCallbackAsync();
149
149
  })().catch((e) => {
150
150
  console.error("Error during silent login callback:", e);
151
151
  });
152
152
  }, [e]), null), I = ({ configurationName: e }) => {
153
- let n = s(window.location.href), r = t.get, i = r(e), a = null;
153
+ let n = s(window.location.href), r = t.getOrThrow, i = r(e), a = null;
154
154
  for (let [e, t] of Object.entries(n)) e === "state" || e === "scope" || (a === null && (a = {}), a[e] = t);
155
155
  return d(() => {
156
156
  i.tokens || i.loginAsync(null, a, !0, n.scope);
@@ -302,7 +302,7 @@ var _ = "default", v = (e, t, n = !1) => async (...r) => await t().fetchWithToke
302
302
  });
303
303
  }
304
304
  }, W = ({ children: e, callbackPath: n = null, extras: r = null, configurationName: i = "default" }) => {
305
- let a = t.get, o = a(i);
305
+ let a = t.getOrThrow, o = a(i);
306
306
  return d(() => {
307
307
  o.tokens || o.loginAsync(n, r);
308
308
  }, [
@@ -315,37 +315,58 @@ var _ = "default", v = (e, t, n = !1) => async (...r) => await t().fetchWithToke
315
315
  extras: n,
316
316
  configurationName: r,
317
317
  children: /* @__PURE__ */ h(e, { ...i })
318
- }), K = "default", q = (e, t) => {
319
- let n = !1;
320
- return e(t) && (n = e(t).tokens != null), n;
321
- }, J = (e = K) => {
322
- let n = t.get, [r, i] = p(() => q(n, e));
318
+ }), K = /* @__PURE__ */ new Set(), q = (e) => {
319
+ K.has(e) || (K.add(e), console.warn(`@axa-fr/react-oidc: no OIDC configuration found for "${e}". Make sure to wrap your component tree with <OidcProvider configurationName="${e}">. Hooks are returning safe default values (issue #1679).`));
320
+ }, J = "default", Y = (e, t) => {
321
+ let n = !1, r = e(t);
322
+ return r && (n = r.tokens != null), n;
323
+ }, X = (e = J) => {
324
+ let n = t.get, [r, i] = p(() => Y(n, e));
323
325
  return d(() => {
324
- let r = !0, a = n(e), o = a.subscribeEvents((a, o) => {
325
- (a === t.eventNames.logout_from_another_tab || a === t.eventNames.logout_from_same_tab || a === t.eventNames.token_acquired) && r && i(q(n, e));
326
+ let r = !0, a = n(e);
327
+ if (!a) {
328
+ q(e);
329
+ return;
330
+ }
331
+ let o = a.subscribeEvents((a, o) => {
332
+ (a === t.eventNames.logout_from_another_tab || a === t.eventNames.logout_from_same_tab || a === t.eventNames.token_acquired) && r && i(Y(n, e));
326
333
  });
327
334
  return () => {
328
335
  r = !1, a.removeEventSubscription(o);
329
336
  };
330
337
  }, [e]), {
331
- login: (t = void 0, r = void 0, i = !1, a = void 0) => n(e).loginAsync(t, r, !1, a, i),
332
- logout: (t = void 0, r = void 0) => n(e).logoutAsync(t, r),
338
+ login: (t = void 0, r = void 0, i = !1, a = void 0) => {
339
+ let o = n(e);
340
+ return o ? o.loginAsync(t, r, !1, a, i) : (q(e), Promise.resolve());
341
+ },
342
+ logout: (t = void 0, r = void 0) => {
343
+ let i = n(e);
344
+ return i ? i.logoutAsync(t, r) : (q(e), Promise.resolve());
345
+ },
333
346
  renewTokens: async (t = void 0) => {
334
- let r = await n(e).renewTokensAsync(t);
347
+ let r = n(e);
348
+ if (!r) return q(e), {
349
+ accessToken: null,
350
+ accessTokenPayload: null,
351
+ idToken: null,
352
+ idTokenPayload: null
353
+ };
354
+ let i = await r.renewTokensAsync(t);
335
355
  return {
336
- accessToken: r.accessToken,
337
- accessTokenPayload: r.accessTokenPayload,
338
- idToken: r.idToken,
339
- idTokenPayload: r.idTokenPayload
356
+ accessToken: i.accessToken,
357
+ accessTokenPayload: i.accessTokenPayload,
358
+ idToken: i.idToken,
359
+ idTokenPayload: i.idTokenPayload
340
360
  };
341
361
  },
342
362
  isAuthenticated: r
343
363
  };
344
- }, Y = {
364
+ }, Z = {
345
365
  accessToken: null,
346
366
  accessTokenPayload: null
347
- }, X = (e) => {
367
+ }, Q = (e) => {
348
368
  let n = t.get, r = n(e);
369
+ if (!r) return Z;
349
370
  if (r.tokens) {
350
371
  let e = r.tokens;
351
372
  return {
@@ -354,21 +375,26 @@ var _ = "default", v = (e, t, n = !1) => async (...r) => await t().fetchWithToke
354
375
  generateDemonstrationOfProofOfPossessionAsync: r.configuration.demonstrating_proof_of_possession ? (t, n) => r.generateDemonstrationOfProofOfPossessionAsync(e.accessToken, t, n) : null
355
376
  };
356
377
  }
357
- return Y;
378
+ return Z;
358
379
  };
359
- function Z(e, t) {
380
+ function ee(e, t) {
360
381
  return e.configuration.demonstrating_proof_of_possession ? (n, r, i = {}) => e.generateDemonstrationOfProofOfPossessionAsync(t.accessToken, n, r, i) : null;
361
382
  }
362
- var Q = (e = K) => {
363
- let n = t.get, [r, i] = p(() => X(e));
383
+ var te = (e = J) => {
384
+ let n = t.get, [r, i] = p(() => Q(e));
364
385
  return d(() => {
365
- let r = !0, a = n(e), o = a.subscribeEvents((e, n) => {
386
+ let r = !0, a = n(e);
387
+ if (!a) {
388
+ q(e);
389
+ return;
390
+ }
391
+ let o = a.subscribeEvents((e, n) => {
366
392
  if ((e === t.eventNames.token_renewed || e === t.eventNames.token_acquired || e === t.eventNames.logout_from_another_tab || e === t.eventNames.logout_from_same_tab || e === t.eventNames.refreshTokensAsync_error || e === t.eventNames.syncTokensAsync_error) && r) {
367
393
  let e = a.tokens;
368
- i(e == null ? Y : {
394
+ i(e == null ? Z : {
369
395
  accessToken: e.accessToken,
370
396
  accessTokenPayload: e.accessTokenPayload,
371
- generateDemonstrationOfProofOfPossessionAsync: Z(a, e)
397
+ generateDemonstrationOfProofOfPossessionAsync: ee(a, e)
372
398
  });
373
399
  }
374
400
  });
@@ -379,8 +405,9 @@ var Q = (e = K) => {
379
405
  }, $ = {
380
406
  idToken: null,
381
407
  idTokenPayload: null
382
- }, ee = (e) => {
408
+ }, ne = (e) => {
383
409
  let n = t.get, r = n(e);
410
+ if (!r) return $;
384
411
  if (r.tokens) {
385
412
  let e = r.tokens;
386
413
  return {
@@ -389,10 +416,15 @@ var Q = (e = K) => {
389
416
  };
390
417
  }
391
418
  return $;
392
- }, te = (e = K) => {
393
- let n = t.get, [r, i] = p(() => ee(e));
419
+ }, re = (e = J) => {
420
+ let n = t.get, [r, i] = p(() => ne(e));
394
421
  return d(() => {
395
- let r = !0, a = n(e), o = a.subscribeEvents((e, n) => {
422
+ let r = !0, a = n(e);
423
+ if (!a) {
424
+ q(e);
425
+ return;
426
+ }
427
+ let o = a.subscribeEvents((e, n) => {
396
428
  if ((e === t.eventNames.token_renewed || e === t.eventNames.token_acquired || e === t.eventNames.logout_from_another_tab || e === t.eventNames.logout_from_same_tab || e === t.eventNames.refreshTokensAsync_error || e === t.eventNames.syncTokensAsync_error) && r) {
397
429
  let e = a.tokens;
398
430
  i(e == null ? $ : {
@@ -405,58 +437,62 @@ var Q = (e = K) => {
405
437
  r = !1, a.removeEventSubscription(o);
406
438
  };
407
439
  }, [e]), r;
408
- }, ne = /* @__PURE__ */ function(e) {
440
+ }, ie = /* @__PURE__ */ function(e) {
409
441
  return e.Unauthenticated = "Unauthenticated", e.Loading = "Loading user", e.Loaded = "User loaded", e.LoadingError = "Error loading user", e;
410
- }({}), re = (e = "default", n = !1) => {
411
- let r = t.get(e).userInfo(), [i, a] = p({
412
- user: r,
413
- status: r ? "User loaded" : "Unauthenticated"
414
- }), [o, s] = p(+!!r), c = f(+!!r);
442
+ }({}), ae = (e = "default", n = !1) => {
443
+ let r = t.get(e), i = r ? r.userInfo() : null, [a, o] = p({
444
+ user: i,
445
+ status: i ? "User loaded" : "Unauthenticated"
446
+ }), [s, c] = p(+!!i), l = f(+!!i);
415
447
  return d(() => {
416
- let r = t.get(e), s = !0;
417
- if (r && r.tokens) {
418
- let e = o === c.current;
448
+ let r = t.get(e), i = !0;
449
+ if (!r) {
450
+ q(e);
451
+ return;
452
+ }
453
+ if (r.tokens) {
454
+ let e = s === l.current;
419
455
  if (e && r.userInfo()) return;
420
- c.current = o, queueMicrotask(() => {
421
- s && a({
422
- ...i,
456
+ l.current = s, queueMicrotask(() => {
457
+ i && o({
458
+ ...a,
423
459
  status: "Loading user"
424
460
  });
425
461
  }), r.userInfoAsync(!e, n).then((e) => {
426
- s && a({
462
+ i && o({
427
463
  user: e,
428
464
  status: "User loaded"
429
465
  });
430
- }).catch(() => a({
431
- ...i,
466
+ }).catch(() => o({
467
+ ...a,
432
468
  status: "Error loading user"
433
469
  }));
434
470
  } else queueMicrotask(() => {
435
- s && a({
471
+ i && o({
436
472
  user: null,
437
473
  status: "Unauthenticated"
438
474
  });
439
475
  });
440
- let l = r.subscribeEvents((e) => {
441
- (e === t.eventNames.logout_from_another_tab || e === t.eventNames.logout_from_same_tab) && s && a({
476
+ let c = r.subscribeEvents((e) => {
477
+ (e === t.eventNames.logout_from_another_tab || e === t.eventNames.logout_from_same_tab) && i && o({
442
478
  user: null,
443
479
  status: "Unauthenticated"
444
480
  });
445
481
  });
446
482
  return () => {
447
- s = !1, r.removeEventSubscription(l);
483
+ i = !1, r.removeEventSubscription(c);
448
484
  };
449
485
  }, [
450
- o,
486
+ s,
451
487
  e,
452
488
  n
453
489
  ]), {
454
- oidcUser: i.user,
455
- oidcUserLoadingState: i.status,
490
+ oidcUser: a.user,
491
+ oidcUserLoadingState: a.status,
456
492
  reloadOidcUser: () => {
457
- s(o + 1);
493
+ c(s + 1);
458
494
  }
459
495
  };
460
496
  };
461
497
  //#endregion
462
- export { e as OidcClient, n as OidcLocation, U as OidcProvider, W as OidcSecure, ne as OidcUserStatus, i as TokenAutomaticRenewMode, a as TokenRenewMode, J as useOidc, Q as useOidcAccessToken, b as useOidcFetch, te as useOidcIdToken, re as useOidcUser, y as withOidcFetch, G as withOidcSecure };
498
+ export { e as OidcClient, n as OidcLocation, U as OidcProvider, W as OidcSecure, ie as OidcUserStatus, i as TokenAutomaticRenewMode, a as TokenRenewMode, X as useOidc, te as useOidcAccessToken, b as useOidcFetch, re as useOidcIdToken, ae as useOidcUser, y as withOidcFetch, G as withOidcSecure };
@@ -1 +1 @@
1
- (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`@axa-fr/oidc-client`),require(`react`),require(`react/jsx-runtime`)):typeof define==`function`&&define.amd?define([`exports`,`@axa-fr/oidc-client`,`react`,`react/jsx-runtime`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e[`react-oidc`]={},e._axa_fr_oidc_client,e.React,e.react_jsx_runtime))})(this,function(e,t,n,r){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var i=Object.create,a=Object.defineProperty,o=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,c=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty,u=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=s(t),c=0,u=i.length,d;c<u;c++)d=i[c],!l.call(e,d)&&d!==n&&a(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(r=o(t,d))||r.enumerable});return e};n=((e,t,n)=>(n=e==null?{}:i(c(e)),u(t||!e||!e.__esModule?a(n,`default`,{value:e,enumerable:!0}):n,e)))(n,1);var d=`default`,f=(e,t,n=!1)=>async(...r)=>await t().fetchWithTokens(e,n)(...r),p=(e=null,t=d,n=!1)=>i=>a=>{let{fetch:o}=m(e||a.fetch,t,n);return(0,r.jsx)(i,{...a,fetch:o})},m=(e=null,r=d,i=!1)=>{let a=e||window.fetch,o=t.OidcClient.get;return{fetch:(0,n.useCallback)((e,t)=>f(a,()=>o(r),i)(e,t),[a,r,i])}},h=()=>(0,r.jsx)(`div`,{className:`oidc-authenticating`,children:(0,r.jsxs)(`div`,{className:`oidc-authenticating__container`,children:[(0,r.jsx)(`h1`,{className:`oidc-authenticating__title`,children:`Error authentication`}),(0,r.jsx)(`p`,{className:`oidc-authenticating__content`,children:`An error occurred during authentication.`})]})}),g=()=>(0,r.jsx)(`div`,{className:`oidc-authenticating`,children:(0,r.jsxs)(`div`,{className:`oidc-authenticating__container`,children:[(0,r.jsx)(`h1`,{className:`oidc-authenticating__title`,children:`Authentication in progress`}),(0,r.jsx)(`p`,{className:`oidc-authenticating__content`,children:`You will be redirected to the login page.`})]})}),_=()=>Math.random().toString(36).slice(2,8),v=(e,t)=>(n,r)=>{if(typeof e.CustomEvent==`function`)return new e.CustomEvent(n,r);let i=r||{bubbles:!1,cancelable:!1,detail:void 0},a=t.createEvent(`CustomEvent`);return a.initCustomEvent(n,i.bubbles,i.cancelable,i.detail),a.prototype=e.Event.prototype,a},y=(e,t,n)=>({replaceState:(r,i)=>{let a=n(),o=i||e.history.state;e.history.replaceState({key:a,state:o},null,r),e.dispatchEvent(t(`popstate`))}}),b=()=>y(window,v(window,document),_),x=()=>(0,r.jsx)(`div`,{className:`oidc-callback`,children:(0,r.jsxs)(`div`,{className:`oidc-callback__container`,children:[(0,r.jsx)(`h1`,{className:`oidc-callback__title`,children:`Authentication complete`}),(0,r.jsx)(`p`,{className:`oidc-callback__content`,children:`You will be redirected to your application.`})]})}),S=200,C=(e,t=window)=>t.location.pathname===e||e===`/`,w=({callBackError:e,callBackSuccess:i,configurationName:a,withCustomHistory:o,navigateAfterCallback:s})=>{let[c,l]=(0,n.useState)(!1);(0,n.useEffect)(()=>{let e=!0;return(async()=>{let n=t.OidcClient.get;try{let r=n(a),{callbackPath:i}=await r.loginCallbackAsync(),c=i||`/`;if(s)try{await s(c),r.publishEvent(t.OidcClient.eventNames.loginCallbackAsync_navigated,{configurationName:a,callbackPath:c})}catch(n){r.publishEvent(t.OidcClient.eventNames.loginCallbackAsync_navigation_error,{configurationName:a,callbackPath:c,error:n}),e&&(console.warn(n),l(!0))}else (o?o():b()).replaceState(c),await new Promise(e=>{setTimeout(()=>{e()},S)}),e&&(C(c)?r.publishEvent(t.OidcClient.eventNames.loginCallbackAsync_navigated,{configurationName:a,callbackPath:c}):(r.publishEvent(t.OidcClient.eventNames.loginCallbackAsync_navigation_error,{configurationName:a,callbackPath:c,error:Error(`Navigation did not commit: expected "${c}" but found "${window.location.pathname}"`)}),l(!0)))}catch(t){e&&(console.warn(t),l(!0))}})(),()=>{e=!1}},[]);let u=e||h,d=i||x;return c?(0,r.jsx)(u,{configurationName:a}):(0,r.jsx)(d,{configurationName:a})},T=()=>(0,r.jsx)(`span`,{className:`oidc-loading`,children:`Loading`}),E=()=>(0,r.jsx)(`div`,{className:`oidc-loading-timeout`,children:(0,r.jsxs)(`div`,{className:`oidc-loading-timeout__container`,children:[(0,r.jsx)(`h1`,{className:`oidc-loading-timeout__title`,children:`Loading timeout`}),(0,r.jsx)(`p`,{className:`oidc-loading-timeout__content`,children:`Authentication is taking longer than expected. Please try refreshing the page.`})]})}),D=()=>(0,r.jsx)(`div`,{className:`oidc-serviceworker`,children:(0,r.jsxs)(`div`,{className:`oidc-serviceworker__container`,children:[(0,r.jsx)(`h1`,{className:`oidc-serviceworker__title`,children:`Unable to authenticate on this browser`}),(0,r.jsx)(`p`,{className:`oidc-serviceworker__content`,children:`Your browser is not secure enough to make authentication work. Try updating your browser or use a newer browser.`})]})}),O=()=>(0,r.jsx)(`div`,{className:`oidc-session-lost`,children:(0,r.jsxs)(`div`,{className:`oidc-session-lost__container`,children:[(0,r.jsx)(`h1`,{className:`oidc-session-lost__title`,children:`Session timed out`}),(0,r.jsx)(`p`,{className:`oidc-session-lost__content`,children:`Your session has expired. Please re-authenticate.`})]})}),k=({configurationName:e})=>((0,n.useEffect)(()=>{(async()=>{t.OidcClient.get(e).silentLoginCallbackAsync()})().catch(e=>{console.error(`Error during silent login callback:`,e)})},[e]),null),A=({configurationName:e})=>{let i=(0,t.getParseQueryStringFromLocation)(window.location.href),a=t.OidcClient.get,o=a(e),s=null;for(let[e,t]of Object.entries(i))e===`state`||e===`scope`||(s===null&&(s={}),s[e]=t);return(0,n.useEffect)(()=>{o.tokens||o.loginAsync(null,s,!0,i.scope)},[]),(0,r.jsx)(r.Fragment,{})},j=n.default.memo(({callbackErrorComponent:e,callbackSuccessComponent:i,redirect_uri:a,silent_redirect_uri:o,silent_login_uri:s,children:c,configurationName:l,withCustomHistory:u=null,navigateAfterCallback:d=null})=>{let[f,p]=(0,n.useState)(window?(0,t.getPath)(window.location.href):``);(0,n.useEffect)(()=>{let e=()=>p((0,t.getPath)(window.location.href));return e(),window.addEventListener(`popstate`,e,!1),()=>window.removeEventListener(`popstate`,e,!1)},[]);let m=(0,t.getPath)(a);if(o&&f===(0,t.getPath)(o))return(0,r.jsx)(k,{configurationName:l});if(s&&f===(0,t.getPath)(s))return(0,r.jsx)(A,{configurationName:l});switch(f){case m:return(0,r.jsx)(w,{callBackError:e,callBackSuccess:i,configurationName:l,withCustomHistory:u,navigateAfterCallback:d});default:return(0,r.jsx)(r.Fragment,{children:c})}}),M={name:``,data:null},N=({loadingComponent:e,children:i,configurationName:a})=>{let[o,s]=(0,n.useState)(!0),c=t.OidcClient.get,l=c(a);return(0,n.useEffect)(()=>{let e=!0;return l&&l.tryKeepExistingSessionAsync().then(()=>{e&&s(!1)}),()=>{e=!1}},[a]),(0,r.jsx)(r.Fragment,{children:o?(0,r.jsx)(e,{configurationName:a}):(0,r.jsx)(r.Fragment,{children:i})})},P=({isLoading:e,loadingComponent:t,children:n,configurationName:i})=>{let a=t;return e?(0,r.jsx)(a,{configurationName:i,children:n}):(0,r.jsx)(r.Fragment,{children:n})},F=3e4,I=(e,n)=>e===t.OidcClient.eventNames.token_acquired||e===t.OidcClient.eventNames.token_renewed||e===t.OidcClient.eventNames.loginCallbackAsync_end?!0:e===t.OidcClient.eventNames.tryKeepExistingSessionAsync_end?n?.success===!0:!1,L=({children:e,configuration:i,configurationName:a=`default`,callbackSuccessComponent:o=x,authenticatingComponent:s=g,loadingComponent:c=T,loadingTimeoutComponent:l=E,serviceWorkerNotSupportedComponent:u=D,authenticatingErrorComponent:d=h,sessionLostComponent:f=O,onSessionLost:p=null,onLogoutFromAnotherTab:m=null,onLogoutFromSameTab:_=null,withCustomHistory:v=null,navigateAfterCallback:y=null,onEvent:b=null,getFetch:S=null,location:C=null})=>{if(i&&i.redirect_uri&&i.silent_redirect_uri&&i.redirect_uri===i.silent_redirect_uri)throw Error(`redirect_uri and silent_redirect_uri must be different`);let w=(e=`default`)=>t.OidcClient.getOrCreate(S??t.getFetchDefault,C??new t.OidcLocation)(i,e),[k,A]=(0,n.useState)(M),[L,R]=(0,n.useState)(!1),[z,B]=(0,n.useState)(a);(0,n.useEffect)(()=>{let e=w(a).subscribeEvents((e,t)=>{b&&b(a,e,t)});return()=>{w(a).removeEventSubscription(e)}},[a,b]),(0,n.useEffect)(()=>{let e=w(a).subscribeEvents((e,n)=>{if(I(e,n)&&R(!0),e===t.OidcClient.eventNames.refreshTokensAsync_error||e===t.OidcClient.eventNames.syncTokensAsync_error){if(p!=null){p();return}A({name:e,data:n})}else if(e===t.OidcClient.eventNames.logout_from_another_tab){if(m!=null){m();return}A({name:e,data:n})}else e===t.OidcClient.eventNames.logout_from_same_tab?_?.():(e===t.OidcClient.eventNames.loadingTimeout_error||e===t.OidcClient.eventNames.loginAsync_begin||e===t.OidcClient.eventNames.loginCallbackAsync_end||e===t.OidcClient.eventNames.loginAsync_error||e===t.OidcClient.eventNames.loginCallbackAsync_error||e===t.OidcClient.eventNames.service_worker_not_supported_by_browser&&i.service_worker_only===!0)&&A({name:e,data:n})});return queueMicrotask(()=>{B(a)}),()=>{w(a).removeEventSubscription(e),A(M),R(!1)}},[i,a]),(0,n.useEffect)(()=>{let e=i?.loading_timeout_ms??F;if(e<=0||L||w(a)?.tokens!=null||!(k.name===``||k.name===t.OidcClient.eventNames.loginAsync_begin))return;let n=setTimeout(()=>{w(a).publishEvent(t.OidcClient.eventNames.loadingTimeout_error,{timeoutMs:e})},e);return()=>clearTimeout(n)},[k.name,L,a,i]);let V=f,H=s,U=c,W=l,G=u,K=d,q=z!==a,J=w(a);switch(k.name){case t.OidcClient.eventNames.service_worker_not_supported_by_browser:return(0,r.jsx)(P,{loadingComponent:U,isLoading:q,configurationName:a,children:(0,r.jsx)(G,{configurationName:a})});case t.OidcClient.eventNames.loginAsync_begin:return(0,r.jsx)(P,{loadingComponent:U,isLoading:q,configurationName:a,children:(0,r.jsx)(H,{configurationName:a})});case t.OidcClient.eventNames.loadingTimeout_error:return(0,r.jsx)(P,{loadingComponent:U,isLoading:q,configurationName:a,children:(0,r.jsx)(W,{configurationName:a})});case t.OidcClient.eventNames.loginAsync_error:case t.OidcClient.eventNames.loginCallbackAsync_error:return(0,r.jsx)(P,{loadingComponent:U,isLoading:q,configurationName:a,children:(0,r.jsx)(K,{configurationName:a})});case t.OidcClient.eventNames.refreshTokensAsync_error:case t.OidcClient.eventNames.syncTokensAsync_error:case t.OidcClient.eventNames.logout_from_another_tab:return(0,r.jsx)(P,{loadingComponent:U,isLoading:q,configurationName:a,children:(0,r.jsx)(V,{configurationName:a})});default:return(0,r.jsx)(P,{loadingComponent:U,isLoading:q,configurationName:a,children:(0,r.jsx)(j,{redirect_uri:J.configuration.redirect_uri,silent_redirect_uri:J.configuration.silent_redirect_uri,silent_login_uri:J.configuration.silent_login_uri,callbackSuccessComponent:o,callbackErrorComponent:d,authenticatingComponent:s,configurationName:a,withCustomHistory:v,navigateAfterCallback:y,location:C??new t.OidcLocation,children:(0,r.jsx)(N,{loadingComponent:U,configurationName:a,children:e})})})}},R=({children:e,callbackPath:i=null,extras:a=null,configurationName:o=`default`})=>{let s=t.OidcClient.get,c=s(o);return(0,n.useEffect)(()=>{c.tokens||c.loginAsync(i,a)},[o,i,a]),c.tokens?(0,r.jsx)(r.Fragment,{children:e}):null},z=(e,t=null,n=null,i=`default`)=>a=>(0,r.jsx)(R,{callbackPath:t,extras:n,configurationName:i,children:(0,r.jsx)(e,{...a})}),B=`default`,V=(e,t)=>{let n=!1;return e(t)&&(n=e(t).tokens!=null),n},H=(e=B)=>{let r=t.OidcClient.get,[i,a]=(0,n.useState)(()=>V(r,e));return(0,n.useEffect)(()=>{let n=!0,i=r(e),o=i.subscribeEvents((i,o)=>{(i===t.OidcClient.eventNames.logout_from_another_tab||i===t.OidcClient.eventNames.logout_from_same_tab||i===t.OidcClient.eventNames.token_acquired)&&n&&a(V(r,e))});return()=>{n=!1,i.removeEventSubscription(o)}},[e]),{login:(t=void 0,n=void 0,i=!1,a=void 0)=>r(e).loginAsync(t,n,!1,a,i),logout:(t=void 0,n=void 0)=>r(e).logoutAsync(t,n),renewTokens:async(t=void 0)=>{let n=await r(e).renewTokensAsync(t);return{accessToken:n.accessToken,accessTokenPayload:n.accessTokenPayload,idToken:n.idToken,idTokenPayload:n.idTokenPayload}},isAuthenticated:i}},U={accessToken:null,accessTokenPayload:null},W=e=>{let n=t.OidcClient.get,r=n(e);if(r.tokens){let e=r.tokens;return{accessToken:e.accessToken,accessTokenPayload:e.accessTokenPayload,generateDemonstrationOfProofOfPossessionAsync:r.configuration.demonstrating_proof_of_possession?(t,n)=>r.generateDemonstrationOfProofOfPossessionAsync(e.accessToken,t,n):null}}return U};function G(e,t){return e.configuration.demonstrating_proof_of_possession?(n,r,i={})=>e.generateDemonstrationOfProofOfPossessionAsync(t.accessToken,n,r,i):null}var K=(e=B)=>{let r=t.OidcClient.get,[i,a]=(0,n.useState)(()=>W(e));return(0,n.useEffect)(()=>{let n=!0,i=r(e),o=i.subscribeEvents((e,r)=>{if((e===t.OidcClient.eventNames.token_renewed||e===t.OidcClient.eventNames.token_acquired||e===t.OidcClient.eventNames.logout_from_another_tab||e===t.OidcClient.eventNames.logout_from_same_tab||e===t.OidcClient.eventNames.refreshTokensAsync_error||e===t.OidcClient.eventNames.syncTokensAsync_error)&&n){let e=i.tokens;a(e==null?U:{accessToken:e.accessToken,accessTokenPayload:e.accessTokenPayload,generateDemonstrationOfProofOfPossessionAsync:G(i,e)})}});return()=>{n=!1,i.removeEventSubscription(o)}},[e]),i},q={idToken:null,idTokenPayload:null},J=e=>{let n=t.OidcClient.get,r=n(e);if(r.tokens){let e=r.tokens;return{idToken:e.idToken,idTokenPayload:e.idTokenPayload}}return q},Y=(e=B)=>{let r=t.OidcClient.get,[i,a]=(0,n.useState)(()=>J(e));return(0,n.useEffect)(()=>{let n=!0,i=r(e),o=i.subscribeEvents((e,r)=>{if((e===t.OidcClient.eventNames.token_renewed||e===t.OidcClient.eventNames.token_acquired||e===t.OidcClient.eventNames.logout_from_another_tab||e===t.OidcClient.eventNames.logout_from_same_tab||e===t.OidcClient.eventNames.refreshTokensAsync_error||e===t.OidcClient.eventNames.syncTokensAsync_error)&&n){let e=i.tokens;a(e==null?q:{idToken:e.idToken,idTokenPayload:e.idTokenPayload})}});return()=>{n=!1,i.removeEventSubscription(o)}},[e]),i},X=function(e){return e.Unauthenticated=`Unauthenticated`,e.Loading=`Loading user`,e.Loaded=`User loaded`,e.LoadingError=`Error loading user`,e}({});Object.defineProperty(e,`OidcClient`,{enumerable:!0,get:function(){return t.OidcClient}}),Object.defineProperty(e,`OidcLocation`,{enumerable:!0,get:function(){return t.OidcLocation}}),e.OidcProvider=L,e.OidcSecure=R,e.OidcUserStatus=X,Object.defineProperty(e,`TokenAutomaticRenewMode`,{enumerable:!0,get:function(){return t.TokenAutomaticRenewMode}}),Object.defineProperty(e,`TokenRenewMode`,{enumerable:!0,get:function(){return t.TokenRenewMode}}),e.useOidc=H,e.useOidcAccessToken=K,e.useOidcFetch=m,e.useOidcIdToken=Y,e.useOidcUser=(e=`default`,r=!1)=>{let i=t.OidcClient.get(e).userInfo(),[a,o]=(0,n.useState)({user:i,status:i?`User loaded`:`Unauthenticated`}),[s,c]=(0,n.useState)(+!!i),l=(0,n.useRef)(+!!i);return(0,n.useEffect)(()=>{let n=t.OidcClient.get(e),i=!0;if(n&&n.tokens){let e=s===l.current;if(e&&n.userInfo())return;l.current=s,queueMicrotask(()=>{i&&o({...a,status:`Loading user`})}),n.userInfoAsync(!e,r).then(e=>{i&&o({user:e,status:`User loaded`})}).catch(()=>o({...a,status:`Error loading user`}))}else queueMicrotask(()=>{i&&o({user:null,status:`Unauthenticated`})});let c=n.subscribeEvents(e=>{(e===t.OidcClient.eventNames.logout_from_another_tab||e===t.OidcClient.eventNames.logout_from_same_tab)&&i&&o({user:null,status:`Unauthenticated`})});return()=>{i=!1,n.removeEventSubscription(c)}},[s,e,r]),{oidcUser:a.user,oidcUserLoadingState:a.status,reloadOidcUser:()=>{c(s+1)}}},e.withOidcFetch=p,e.withOidcSecure=z});
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`@axa-fr/oidc-client`),require(`react`),require(`react/jsx-runtime`)):typeof define==`function`&&define.amd?define([`exports`,`@axa-fr/oidc-client`,`react`,`react/jsx-runtime`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e[`react-oidc`]={},e._axa_fr_oidc_client,e.React,e.react_jsx_runtime))})(this,function(e,t,n,r){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var i=Object.create,a=Object.defineProperty,o=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,c=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty,u=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=s(t),c=0,u=i.length,d;c<u;c++)d=i[c],!l.call(e,d)&&d!==n&&a(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(r=o(t,d))||r.enumerable});return e};n=((e,t,n)=>(n=e==null?{}:i(c(e)),u(t||!e||!e.__esModule?a(n,`default`,{value:e,enumerable:!0}):n,e)))(n,1);var d=`default`,f=(e,t,n=!1)=>async(...r)=>await t().fetchWithTokens(e,n)(...r),p=(e=null,t=d,n=!1)=>i=>a=>{let{fetch:o}=m(e||a.fetch,t,n);return(0,r.jsx)(i,{...a,fetch:o})},m=(e=null,r=d,i=!1)=>{let a=e||window.fetch,o=t.OidcClient.getOrThrow;return{fetch:(0,n.useCallback)((e,t)=>f(a,()=>o(r),i)(e,t),[a,r,i])}},h=()=>(0,r.jsx)(`div`,{className:`oidc-authenticating`,children:(0,r.jsxs)(`div`,{className:`oidc-authenticating__container`,children:[(0,r.jsx)(`h1`,{className:`oidc-authenticating__title`,children:`Error authentication`}),(0,r.jsx)(`p`,{className:`oidc-authenticating__content`,children:`An error occurred during authentication.`})]})}),g=()=>(0,r.jsx)(`div`,{className:`oidc-authenticating`,children:(0,r.jsxs)(`div`,{className:`oidc-authenticating__container`,children:[(0,r.jsx)(`h1`,{className:`oidc-authenticating__title`,children:`Authentication in progress`}),(0,r.jsx)(`p`,{className:`oidc-authenticating__content`,children:`You will be redirected to the login page.`})]})}),_=()=>Math.random().toString(36).slice(2,8),v=(e,t)=>(n,r)=>{if(typeof e.CustomEvent==`function`)return new e.CustomEvent(n,r);let i=r||{bubbles:!1,cancelable:!1,detail:void 0},a=t.createEvent(`CustomEvent`);return a.initCustomEvent(n,i.bubbles,i.cancelable,i.detail),a.prototype=e.Event.prototype,a},y=(e,t,n)=>({replaceState:(r,i)=>{let a=n(),o=i||e.history.state;e.history.replaceState({key:a,state:o},null,r),e.dispatchEvent(t(`popstate`))}}),b=()=>y(window,v(window,document),_),x=()=>(0,r.jsx)(`div`,{className:`oidc-callback`,children:(0,r.jsxs)(`div`,{className:`oidc-callback__container`,children:[(0,r.jsx)(`h1`,{className:`oidc-callback__title`,children:`Authentication complete`}),(0,r.jsx)(`p`,{className:`oidc-callback__content`,children:`You will be redirected to your application.`})]})}),S=200,C=(e,t=window)=>t.location.pathname===e||e===`/`,w=({callBackError:e,callBackSuccess:i,configurationName:a,withCustomHistory:o,navigateAfterCallback:s})=>{let[c,l]=(0,n.useState)(!1);(0,n.useEffect)(()=>{let e=!0;return(async()=>{let n=t.OidcClient.getOrThrow;try{let r=n(a),{callbackPath:i}=await r.loginCallbackAsync(),c=i||`/`;if(s)try{await s(c),r.publishEvent(t.OidcClient.eventNames.loginCallbackAsync_navigated,{configurationName:a,callbackPath:c})}catch(n){r.publishEvent(t.OidcClient.eventNames.loginCallbackAsync_navigation_error,{configurationName:a,callbackPath:c,error:n}),e&&(console.warn(n),l(!0))}else (o?o():b()).replaceState(c),await new Promise(e=>{setTimeout(()=>{e()},S)}),e&&(C(c)?r.publishEvent(t.OidcClient.eventNames.loginCallbackAsync_navigated,{configurationName:a,callbackPath:c}):(r.publishEvent(t.OidcClient.eventNames.loginCallbackAsync_navigation_error,{configurationName:a,callbackPath:c,error:Error(`Navigation did not commit: expected "${c}" but found "${window.location.pathname}"`)}),l(!0)))}catch(t){e&&(console.warn(t),l(!0))}})(),()=>{e=!1}},[]);let u=e||h,d=i||x;return c?(0,r.jsx)(u,{configurationName:a}):(0,r.jsx)(d,{configurationName:a})},T=()=>(0,r.jsx)(`span`,{className:`oidc-loading`,children:`Loading`}),E=()=>(0,r.jsx)(`div`,{className:`oidc-loading-timeout`,children:(0,r.jsxs)(`div`,{className:`oidc-loading-timeout__container`,children:[(0,r.jsx)(`h1`,{className:`oidc-loading-timeout__title`,children:`Loading timeout`}),(0,r.jsx)(`p`,{className:`oidc-loading-timeout__content`,children:`Authentication is taking longer than expected. Please try refreshing the page.`})]})}),D=()=>(0,r.jsx)(`div`,{className:`oidc-serviceworker`,children:(0,r.jsxs)(`div`,{className:`oidc-serviceworker__container`,children:[(0,r.jsx)(`h1`,{className:`oidc-serviceworker__title`,children:`Unable to authenticate on this browser`}),(0,r.jsx)(`p`,{className:`oidc-serviceworker__content`,children:`Your browser is not secure enough to make authentication work. Try updating your browser or use a newer browser.`})]})}),O=()=>(0,r.jsx)(`div`,{className:`oidc-session-lost`,children:(0,r.jsxs)(`div`,{className:`oidc-session-lost__container`,children:[(0,r.jsx)(`h1`,{className:`oidc-session-lost__title`,children:`Session timed out`}),(0,r.jsx)(`p`,{className:`oidc-session-lost__content`,children:`Your session has expired. Please re-authenticate.`})]})}),k=({configurationName:e})=>((0,n.useEffect)(()=>{(async()=>{t.OidcClient.getOrThrow(e).silentLoginCallbackAsync()})().catch(e=>{console.error(`Error during silent login callback:`,e)})},[e]),null),A=({configurationName:e})=>{let i=(0,t.getParseQueryStringFromLocation)(window.location.href),a=t.OidcClient.getOrThrow,o=a(e),s=null;for(let[e,t]of Object.entries(i))e===`state`||e===`scope`||(s===null&&(s={}),s[e]=t);return(0,n.useEffect)(()=>{o.tokens||o.loginAsync(null,s,!0,i.scope)},[]),(0,r.jsx)(r.Fragment,{})},j=n.default.memo(({callbackErrorComponent:e,callbackSuccessComponent:i,redirect_uri:a,silent_redirect_uri:o,silent_login_uri:s,children:c,configurationName:l,withCustomHistory:u=null,navigateAfterCallback:d=null})=>{let[f,p]=(0,n.useState)(window?(0,t.getPath)(window.location.href):``);(0,n.useEffect)(()=>{let e=()=>p((0,t.getPath)(window.location.href));return e(),window.addEventListener(`popstate`,e,!1),()=>window.removeEventListener(`popstate`,e,!1)},[]);let m=(0,t.getPath)(a);if(o&&f===(0,t.getPath)(o))return(0,r.jsx)(k,{configurationName:l});if(s&&f===(0,t.getPath)(s))return(0,r.jsx)(A,{configurationName:l});switch(f){case m:return(0,r.jsx)(w,{callBackError:e,callBackSuccess:i,configurationName:l,withCustomHistory:u,navigateAfterCallback:d});default:return(0,r.jsx)(r.Fragment,{children:c})}}),M={name:``,data:null},N=({loadingComponent:e,children:i,configurationName:a})=>{let[o,s]=(0,n.useState)(!0),c=t.OidcClient.get,l=c(a);return(0,n.useEffect)(()=>{let e=!0;return l&&l.tryKeepExistingSessionAsync().then(()=>{e&&s(!1)}),()=>{e=!1}},[a]),(0,r.jsx)(r.Fragment,{children:o?(0,r.jsx)(e,{configurationName:a}):(0,r.jsx)(r.Fragment,{children:i})})},P=({isLoading:e,loadingComponent:t,children:n,configurationName:i})=>{let a=t;return e?(0,r.jsx)(a,{configurationName:i,children:n}):(0,r.jsx)(r.Fragment,{children:n})},F=3e4,I=(e,n)=>e===t.OidcClient.eventNames.token_acquired||e===t.OidcClient.eventNames.token_renewed||e===t.OidcClient.eventNames.loginCallbackAsync_end?!0:e===t.OidcClient.eventNames.tryKeepExistingSessionAsync_end?n?.success===!0:!1,L=({children:e,configuration:i,configurationName:a=`default`,callbackSuccessComponent:o=x,authenticatingComponent:s=g,loadingComponent:c=T,loadingTimeoutComponent:l=E,serviceWorkerNotSupportedComponent:u=D,authenticatingErrorComponent:d=h,sessionLostComponent:f=O,onSessionLost:p=null,onLogoutFromAnotherTab:m=null,onLogoutFromSameTab:_=null,withCustomHistory:v=null,navigateAfterCallback:y=null,onEvent:b=null,getFetch:S=null,location:C=null})=>{if(i&&i.redirect_uri&&i.silent_redirect_uri&&i.redirect_uri===i.silent_redirect_uri)throw Error(`redirect_uri and silent_redirect_uri must be different`);let w=(e=`default`)=>t.OidcClient.getOrCreate(S??t.getFetchDefault,C??new t.OidcLocation)(i,e),[k,A]=(0,n.useState)(M),[L,R]=(0,n.useState)(!1),[z,B]=(0,n.useState)(a);(0,n.useEffect)(()=>{let e=w(a).subscribeEvents((e,t)=>{b&&b(a,e,t)});return()=>{w(a).removeEventSubscription(e)}},[a,b]),(0,n.useEffect)(()=>{let e=w(a).subscribeEvents((e,n)=>{if(I(e,n)&&R(!0),e===t.OidcClient.eventNames.refreshTokensAsync_error||e===t.OidcClient.eventNames.syncTokensAsync_error){if(p!=null){p();return}A({name:e,data:n})}else if(e===t.OidcClient.eventNames.logout_from_another_tab){if(m!=null){m();return}A({name:e,data:n})}else e===t.OidcClient.eventNames.logout_from_same_tab?_?.():(e===t.OidcClient.eventNames.loadingTimeout_error||e===t.OidcClient.eventNames.loginAsync_begin||e===t.OidcClient.eventNames.loginCallbackAsync_end||e===t.OidcClient.eventNames.loginAsync_error||e===t.OidcClient.eventNames.loginCallbackAsync_error||e===t.OidcClient.eventNames.service_worker_not_supported_by_browser&&i.service_worker_only===!0)&&A({name:e,data:n})});return queueMicrotask(()=>{B(a)}),()=>{w(a).removeEventSubscription(e),A(M),R(!1)}},[i,a]),(0,n.useEffect)(()=>{let e=i?.loading_timeout_ms??F;if(e<=0||L||w(a)?.tokens!=null||!(k.name===``||k.name===t.OidcClient.eventNames.loginAsync_begin))return;let n=setTimeout(()=>{w(a).publishEvent(t.OidcClient.eventNames.loadingTimeout_error,{timeoutMs:e})},e);return()=>clearTimeout(n)},[k.name,L,a,i]);let V=f,H=s,U=c,W=l,G=u,K=d,q=z!==a,J=w(a);switch(k.name){case t.OidcClient.eventNames.service_worker_not_supported_by_browser:return(0,r.jsx)(P,{loadingComponent:U,isLoading:q,configurationName:a,children:(0,r.jsx)(G,{configurationName:a})});case t.OidcClient.eventNames.loginAsync_begin:return(0,r.jsx)(P,{loadingComponent:U,isLoading:q,configurationName:a,children:(0,r.jsx)(H,{configurationName:a})});case t.OidcClient.eventNames.loadingTimeout_error:return(0,r.jsx)(P,{loadingComponent:U,isLoading:q,configurationName:a,children:(0,r.jsx)(W,{configurationName:a})});case t.OidcClient.eventNames.loginAsync_error:case t.OidcClient.eventNames.loginCallbackAsync_error:return(0,r.jsx)(P,{loadingComponent:U,isLoading:q,configurationName:a,children:(0,r.jsx)(K,{configurationName:a})});case t.OidcClient.eventNames.refreshTokensAsync_error:case t.OidcClient.eventNames.syncTokensAsync_error:case t.OidcClient.eventNames.logout_from_another_tab:return(0,r.jsx)(P,{loadingComponent:U,isLoading:q,configurationName:a,children:(0,r.jsx)(V,{configurationName:a})});default:return(0,r.jsx)(P,{loadingComponent:U,isLoading:q,configurationName:a,children:(0,r.jsx)(j,{redirect_uri:J.configuration.redirect_uri,silent_redirect_uri:J.configuration.silent_redirect_uri,silent_login_uri:J.configuration.silent_login_uri,callbackSuccessComponent:o,callbackErrorComponent:d,authenticatingComponent:s,configurationName:a,withCustomHistory:v,navigateAfterCallback:y,location:C??new t.OidcLocation,children:(0,r.jsx)(N,{loadingComponent:U,configurationName:a,children:e})})})}},R=({children:e,callbackPath:i=null,extras:a=null,configurationName:o=`default`})=>{let s=t.OidcClient.getOrThrow,c=s(o);return(0,n.useEffect)(()=>{c.tokens||c.loginAsync(i,a)},[o,i,a]),c.tokens?(0,r.jsx)(r.Fragment,{children:e}):null},z=(e,t=null,n=null,i=`default`)=>a=>(0,r.jsx)(R,{callbackPath:t,extras:n,configurationName:i,children:(0,r.jsx)(e,{...a})}),B=new Set,V=e=>{B.has(e)||(B.add(e),console.warn(`@axa-fr/react-oidc: no OIDC configuration found for "${e}". Make sure to wrap your component tree with <OidcProvider configurationName="${e}">. Hooks are returning safe default values (issue #1679).`))},H=`default`,U=(e,t)=>{let n=!1,r=e(t);return r&&(n=r.tokens!=null),n},W=(e=H)=>{let r=t.OidcClient.get,[i,a]=(0,n.useState)(()=>U(r,e));return(0,n.useEffect)(()=>{let n=!0,i=r(e);if(!i){V(e);return}let o=i.subscribeEvents((i,o)=>{(i===t.OidcClient.eventNames.logout_from_another_tab||i===t.OidcClient.eventNames.logout_from_same_tab||i===t.OidcClient.eventNames.token_acquired)&&n&&a(U(r,e))});return()=>{n=!1,i.removeEventSubscription(o)}},[e]),{login:(t=void 0,n=void 0,i=!1,a=void 0)=>{let o=r(e);return o?o.loginAsync(t,n,!1,a,i):(V(e),Promise.resolve())},logout:(t=void 0,n=void 0)=>{let i=r(e);return i?i.logoutAsync(t,n):(V(e),Promise.resolve())},renewTokens:async(t=void 0)=>{let n=r(e);if(!n)return V(e),{accessToken:null,accessTokenPayload:null,idToken:null,idTokenPayload:null};let i=await n.renewTokensAsync(t);return{accessToken:i.accessToken,accessTokenPayload:i.accessTokenPayload,idToken:i.idToken,idTokenPayload:i.idTokenPayload}},isAuthenticated:i}},G={accessToken:null,accessTokenPayload:null},K=e=>{let n=t.OidcClient.get,r=n(e);if(!r)return G;if(r.tokens){let e=r.tokens;return{accessToken:e.accessToken,accessTokenPayload:e.accessTokenPayload,generateDemonstrationOfProofOfPossessionAsync:r.configuration.demonstrating_proof_of_possession?(t,n)=>r.generateDemonstrationOfProofOfPossessionAsync(e.accessToken,t,n):null}}return G};function q(e,t){return e.configuration.demonstrating_proof_of_possession?(n,r,i={})=>e.generateDemonstrationOfProofOfPossessionAsync(t.accessToken,n,r,i):null}var J=(e=H)=>{let r=t.OidcClient.get,[i,a]=(0,n.useState)(()=>K(e));return(0,n.useEffect)(()=>{let n=!0,i=r(e);if(!i){V(e);return}let o=i.subscribeEvents((e,r)=>{if((e===t.OidcClient.eventNames.token_renewed||e===t.OidcClient.eventNames.token_acquired||e===t.OidcClient.eventNames.logout_from_another_tab||e===t.OidcClient.eventNames.logout_from_same_tab||e===t.OidcClient.eventNames.refreshTokensAsync_error||e===t.OidcClient.eventNames.syncTokensAsync_error)&&n){let e=i.tokens;a(e==null?G:{accessToken:e.accessToken,accessTokenPayload:e.accessTokenPayload,generateDemonstrationOfProofOfPossessionAsync:q(i,e)})}});return()=>{n=!1,i.removeEventSubscription(o)}},[e]),i},Y={idToken:null,idTokenPayload:null},X=e=>{let n=t.OidcClient.get,r=n(e);if(!r)return Y;if(r.tokens){let e=r.tokens;return{idToken:e.idToken,idTokenPayload:e.idTokenPayload}}return Y},Z=(e=H)=>{let r=t.OidcClient.get,[i,a]=(0,n.useState)(()=>X(e));return(0,n.useEffect)(()=>{let n=!0,i=r(e);if(!i){V(e);return}let o=i.subscribeEvents((e,r)=>{if((e===t.OidcClient.eventNames.token_renewed||e===t.OidcClient.eventNames.token_acquired||e===t.OidcClient.eventNames.logout_from_another_tab||e===t.OidcClient.eventNames.logout_from_same_tab||e===t.OidcClient.eventNames.refreshTokensAsync_error||e===t.OidcClient.eventNames.syncTokensAsync_error)&&n){let e=i.tokens;a(e==null?Y:{idToken:e.idToken,idTokenPayload:e.idTokenPayload})}});return()=>{n=!1,i.removeEventSubscription(o)}},[e]),i},Q=function(e){return e.Unauthenticated=`Unauthenticated`,e.Loading=`Loading user`,e.Loaded=`User loaded`,e.LoadingError=`Error loading user`,e}({});Object.defineProperty(e,`OidcClient`,{enumerable:!0,get:function(){return t.OidcClient}}),Object.defineProperty(e,`OidcLocation`,{enumerable:!0,get:function(){return t.OidcLocation}}),e.OidcProvider=L,e.OidcSecure=R,e.OidcUserStatus=Q,Object.defineProperty(e,`TokenAutomaticRenewMode`,{enumerable:!0,get:function(){return t.TokenAutomaticRenewMode}}),Object.defineProperty(e,`TokenRenewMode`,{enumerable:!0,get:function(){return t.TokenRenewMode}}),e.useOidc=W,e.useOidcAccessToken=J,e.useOidcFetch=m,e.useOidcIdToken=Z,e.useOidcUser=(e=`default`,r=!1)=>{let i=t.OidcClient.get(e),a=i?i.userInfo():null,[o,s]=(0,n.useState)({user:a,status:a?`User loaded`:`Unauthenticated`}),[c,l]=(0,n.useState)(+!!a),u=(0,n.useRef)(+!!a);return(0,n.useEffect)(()=>{let n=t.OidcClient.get(e),i=!0;if(!n){V(e);return}if(n.tokens){let e=c===u.current;if(e&&n.userInfo())return;u.current=c,queueMicrotask(()=>{i&&s({...o,status:`Loading user`})}),n.userInfoAsync(!e,r).then(e=>{i&&s({user:e,status:`User loaded`})}).catch(()=>s({...o,status:`Error loading user`}))}else queueMicrotask(()=>{i&&s({user:null,status:`Unauthenticated`})});let a=n.subscribeEvents(e=>{(e===t.OidcClient.eventNames.logout_from_another_tab||e===t.OidcClient.eventNames.logout_from_same_tab)&&i&&s({user:null,status:`Unauthenticated`})});return()=>{i=!1,n.removeEventSubscription(a)}},[c,e,r]),{oidcUser:o.user,oidcUserLoadingState:o.status,reloadOidcUser:()=>{l(c+1)}}},e.withOidcFetch=p,e.withOidcSecure=z});
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Emits a `console.warn` once per `configurationName` when an OIDC hook is
3
+ * used without a matching `<OidcProvider>`. Introduced for issue #1679 so
4
+ * that consumers get a clear, non-fatal signal in tests and Storybook.
5
+ *
6
+ * Exported for testing purposes.
7
+ */
8
+ export declare const warnMissingConfigurationOnce: (configurationName: string) => void;
9
+ /**
10
+ * Resets the internal set of already-warned configuration names. Intended
11
+ * for tests only.
12
+ */
13
+ export declare const resetWarnedConfigurations: () => void;
14
+ //# sourceMappingURL=warnMissingConfiguration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"warnMissingConfiguration.d.ts","sourceRoot":"","sources":["../src/warnMissingConfiguration.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,eAAO,MAAM,4BAA4B,GAAI,mBAAmB,MAAM,KAAG,IAUxE,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,yBAAyB,QAAO,IAE5C,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@axa-fr/react-oidc",
3
- "version": "7.27.15",
3
+ "version": "7.27.16",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.umd.cjs",
@@ -40,8 +40,8 @@
40
40
  "lint": "eslint src"
41
41
  },
42
42
  "dependencies": {
43
- "@axa-fr/oidc-client": "7.27.15",
44
- "@axa-fr/oidc-client-service-worker": "7.27.15"
43
+ "@axa-fr/oidc-client": "7.27.16",
44
+ "@axa-fr/oidc-client-service-worker": "7.27.16"
45
45
  },
46
46
  "peerDependencies": {
47
47
  "react": "^17.0.0 || ^18.0.0 || ^19.0.0"
@@ -41,7 +41,9 @@ export const useOidcFetch = (
41
41
  demonstratingProofOfPossession: boolean = false,
42
42
  ) => {
43
43
  const previousFetch = fetch || window.fetch;
44
- const getOidc = OidcClient.get;
44
+ // useOidcFetch relies on an initialized OIDC configuration to attach
45
+ // the bearer token, so we keep the original fail-fast behaviour.
46
+ const getOidc = OidcClient.getOrThrow;
45
47
 
46
48
  const memoizedFetchCallback = useCallback(
47
49
  (input: RequestInfo | URL, init?: RequestInit) => {
@@ -13,7 +13,9 @@ export const OidcSecure: FC<PropsWithChildren<OidcSecureProps>> = ({
13
13
  extras = null,
14
14
  configurationName = 'default',
15
15
  }) => {
16
- const getOidc = OidcClient.get;
16
+ // Keep the previous fail-fast behaviour: this component cannot
17
+ // meaningfully render without an initialized OIDC configuration.
18
+ const getOidc = OidcClient.getOrThrow;
17
19
  const oidc = getOidc(configurationName);
18
20
  useEffect(() => {
19
21
  if (!oidc.tokens) {
package/src/ReactOidc.tsx CHANGED
@@ -1,6 +1,8 @@
1
1
  import { OidcClient, StringMap, Tokens } from '@axa-fr/oidc-client';
2
2
  import { useEffect, useState } from 'react';
3
3
 
4
+ import { warnMissingConfigurationOnce } from './warnMissingConfiguration.js';
5
+
4
6
  const defaultConfigurationName = 'default';
5
7
 
6
8
  type GetOidcFn = {
@@ -11,7 +13,7 @@ const defaultIsAuthenticated = (getOidc: GetOidcFn, configurationName: string) =
11
13
  let isAuthenticated = false;
12
14
  const oidc = getOidc(configurationName);
13
15
  if (oidc) {
14
- isAuthenticated = getOidc(configurationName).tokens != null;
16
+ isAuthenticated = oidc.tokens != null;
15
17
  }
16
18
  return isAuthenticated;
17
19
  };
@@ -25,6 +27,12 @@ export const useOidc = (configurationName = defaultConfigurationName) => {
25
27
  useEffect(() => {
26
28
  let isMounted = true;
27
29
  const oidc = getOidc(configurationName);
30
+ // Hooks may be rendered outside of an <OidcProvider> (issue #1679):
31
+ // in that case `oidc` is null and we simply skip event subscription.
32
+ if (!oidc) {
33
+ warnMissingConfigurationOnce(configurationName);
34
+ return undefined;
35
+ }
28
36
 
29
37
  const newSubscriptionId = oidc.subscribeEvents((name: string, data: any) => {
30
38
  if (
@@ -48,25 +56,34 @@ export const useOidc = (configurationName = defaultConfigurationName) => {
48
56
  extras: StringMap | undefined = undefined,
49
57
  silentLoginOnly = false,
50
58
  scope: string = undefined,
51
- ) => {
52
- return getOidc(configurationName).loginAsync(
53
- callbackPath,
54
- extras,
55
- false,
56
- scope,
57
- silentLoginOnly,
58
- );
59
+ ): Promise<unknown> => {
60
+ const oidc = getOidc(configurationName);
61
+ if (!oidc) {
62
+ warnMissingConfigurationOnce(configurationName);
63
+ return Promise.resolve();
64
+ }
65
+ return oidc.loginAsync(callbackPath, extras, false, scope, silentLoginOnly);
59
66
  };
60
67
  const logout = (
61
68
  callbackPath: string | null | undefined = undefined,
62
69
  extras: StringMap | undefined = undefined,
63
- ) => {
64
- return getOidc(configurationName).logoutAsync(callbackPath, extras);
70
+ ): Promise<void> => {
71
+ const oidc = getOidc(configurationName);
72
+ if (!oidc) {
73
+ warnMissingConfigurationOnce(configurationName);
74
+ return Promise.resolve();
75
+ }
76
+ return oidc.logoutAsync(callbackPath, extras);
65
77
  };
66
78
  const renewTokens = async (
67
79
  extras: StringMap | undefined = undefined,
68
80
  ): Promise<OidcAccessToken | OidcIdToken> => {
69
- const tokens = await getOidc(configurationName).renewTokensAsync(extras);
81
+ const oidc = getOidc(configurationName);
82
+ if (!oidc) {
83
+ warnMissingConfigurationOnce(configurationName);
84
+ return { accessToken: null, accessTokenPayload: null, idToken: null, idTokenPayload: null };
85
+ }
86
+ const tokens = await oidc.renewTokensAsync(extras);
70
87
 
71
88
  return {
72
89
  // @ts-ignore
@@ -87,6 +104,9 @@ const accessTokenInitialState = { accessToken: null, accessTokenPayload: null };
87
104
  const initTokens = (configurationName: string) => {
88
105
  const getOidc = OidcClient.get;
89
106
  const oidc = getOidc(configurationName);
107
+ if (!oidc) {
108
+ return accessTokenInitialState;
109
+ }
90
110
  if (oidc.tokens) {
91
111
  const tokens = oidc.tokens;
92
112
  return {
@@ -122,6 +142,11 @@ export const useOidcAccessToken = (configurationName = defaultConfigurationName)
122
142
  useEffect(() => {
123
143
  let isMounted = true;
124
144
  const oidc = getOidc(configurationName);
145
+ // No provider in the tree (issue #1679): keep the default token state.
146
+ if (!oidc) {
147
+ warnMissingConfigurationOnce(configurationName);
148
+ return undefined;
149
+ }
125
150
 
126
151
  const newSubscriptionId = oidc.subscribeEvents((name: string, data: any) => {
127
152
  if (
@@ -161,6 +186,9 @@ const initIdToken = (configurationName: string) => {
161
186
  const getOidc = OidcClient.get;
162
187
  const oidc = getOidc(configurationName);
163
188
 
189
+ if (!oidc) {
190
+ return idTokenInitialState;
191
+ }
164
192
  if (oidc.tokens) {
165
193
  const tokens = oidc.tokens;
166
194
  return { idToken: tokens.idToken, idTokenPayload: tokens.idTokenPayload };
@@ -180,6 +208,11 @@ export const useOidcIdToken = (configurationName = defaultConfigurationName) =>
180
208
  useEffect(() => {
181
209
  let isMounted = true;
182
210
  const oidc = getOidc(configurationName);
211
+ // No provider in the tree (issue #1679): keep the default id-token state.
212
+ if (!oidc) {
213
+ warnMissingConfigurationOnce(configurationName);
214
+ return undefined;
215
+ }
183
216
 
184
217
  const newSubscriptionId = oidc.subscribeEvents((name: string, data: any) => {
185
218
  if (
package/src/User.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { OidcClient, type OidcUserInfo } from '@axa-fr/oidc-client';
2
2
  import { useEffect, useRef, useState } from 'react';
3
3
 
4
+ import { warnMissingConfigurationOnce } from './warnMissingConfiguration.js';
5
+
4
6
  export enum OidcUserStatus {
5
7
  Unauthenticated = 'Unauthenticated',
6
8
  Loading = 'Loading user',
@@ -18,7 +20,9 @@ export const useOidcUser = <T extends OidcUserInfo = OidcUserInfo>(
18
20
  demonstrating_proof_of_possession = false,
19
21
  ) => {
20
22
  const oidc = OidcClient.get(configurationName);
21
- const user = oidc.userInfo<T>();
23
+ // When the hook is used outside of an <OidcProvider> (issue #1679),
24
+ // `OidcClient.get` returns null instead of throwing.
25
+ const user = oidc ? oidc.userInfo<T>() : null;
22
26
  const [oidcUser, setOidcUser] = useState<OidcUser<T>>({
23
27
  user: user,
24
28
  status: user ? OidcUserStatus.Loaded : OidcUserStatus.Unauthenticated,
@@ -29,7 +33,11 @@ export const useOidcUser = <T extends OidcUserInfo = OidcUserInfo>(
29
33
  useEffect(() => {
30
34
  const oidc = OidcClient.get(configurationName);
31
35
  let isMounted = true;
32
- if (oidc && oidc.tokens) {
36
+ if (!oidc) {
37
+ warnMissingConfigurationOnce(configurationName);
38
+ return undefined;
39
+ }
40
+ if (oidc.tokens) {
33
41
  const isCache = oidcUserId === oidcPreviousUserIdRef.current;
34
42
  if (isCache && oidc.userInfo<T>()) {
35
43
  return;
@@ -7,6 +7,7 @@ import CallbackManager, { CallBackSuccess, verifyNavigationCommitted } from './C
7
7
  vi.mock('@axa-fr/oidc-client', () => ({
8
8
  OidcClient: {
9
9
  get: vi.fn(),
10
+ getOrThrow: vi.fn(),
10
11
  eventNames: {
11
12
  loginCallbackAsync_navigated: 'loginCallbackAsync_navigated',
12
13
  loginCallbackAsync_navigation_error: 'loginCallbackAsync_navigation_error',
@@ -58,7 +59,7 @@ describe('CallbackManager', () => {
58
59
  mockLoginCallbackAsync = vi.fn();
59
60
  mockReplaceState = vi.fn();
60
61
 
61
- (OidcClient.get as ReturnType<typeof vi.fn>).mockReturnValue({
62
+ (OidcClient.getOrThrow as ReturnType<typeof vi.fn>).mockReturnValue({
62
63
  loginCallbackAsync: mockLoginCallbackAsync,
63
64
  publishEvent: mockPublishEvent,
64
65
  });
@@ -34,7 +34,7 @@ const CallbackManager: ComponentType<any> = ({
34
34
  useEffect(() => {
35
35
  let isMounted = true;
36
36
  const playCallbackAsync = async () => {
37
- const getOidc = OidcClient.get;
37
+ const getOidc = OidcClient.getOrThrow;
38
38
  try {
39
39
  const oidcClient = getOidc(configurationName);
40
40
  const { callbackPath } = await oidcClient.loginCallbackAsync();
@@ -8,7 +8,7 @@ export interface SilentCallbackProps {
8
8
  const SilentCallbackManager: FC<SilentCallbackProps> = ({ configurationName }) => {
9
9
  useEffect(() => {
10
10
  const playCallbackAsync = async () => {
11
- const oidc = OidcClient.get(configurationName);
11
+ const oidc = OidcClient.getOrThrow(configurationName);
12
12
  oidc.silentLoginCallbackAsync();
13
13
  };
14
14
 
@@ -4,7 +4,7 @@ import { ComponentType, useEffect } from 'react';
4
4
  const SilentLogin: ComponentType<any> = ({ configurationName }) => {
5
5
  const queryParams = getParseQueryStringFromLocation(window.location.href);
6
6
 
7
- const getOidc = OidcClient.get;
7
+ const getOidc = OidcClient.getOrThrow;
8
8
  const oidc = getOidc(configurationName);
9
9
 
10
10
  let extras = null;
@@ -0,0 +1,89 @@
1
+ import { renderHook } from '@testing-library/react';
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ import { useOidc, useOidcAccessToken, useOidcIdToken } from './ReactOidc';
5
+ import { OidcUserStatus, useOidcUser } from './User';
6
+ import { resetWarnedConfigurations } from './warnMissingConfiguration';
7
+
8
+ vi.mock('@axa-fr/oidc-client', () => ({
9
+ OidcClient: {
10
+ get: vi.fn(() => null),
11
+ getOrThrow: vi.fn(() => {
12
+ throw new Error('OIDC library does seem initialized.');
13
+ }),
14
+ eventNames: {
15
+ logout_from_another_tab: 'logout_from_another_tab',
16
+ logout_from_same_tab: 'logout_from_same_tab',
17
+ token_acquired: 'token_acquired',
18
+ token_renewed: 'token_renewed',
19
+ refreshTokensAsync_error: 'refreshTokensAsync_error',
20
+ syncTokensAsync_error: 'syncTokensAsync_error',
21
+ },
22
+ },
23
+ }));
24
+
25
+ describe('hooks used outside <OidcProvider> (issue #1679)', () => {
26
+ let warnSpy: ReturnType<typeof vi.spyOn>;
27
+
28
+ beforeEach(() => {
29
+ resetWarnedConfigurations();
30
+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
31
+ });
32
+
33
+ afterEach(() => {
34
+ warnSpy.mockRestore();
35
+ });
36
+
37
+ describe('useOidc', () => {
38
+ it('does not throw and returns safe defaults', () => {
39
+ const { result } = renderHook(() => useOidc());
40
+ expect(result.current.isAuthenticated).toBe(false);
41
+ expect(typeof result.current.login).toBe('function');
42
+ expect(typeof result.current.logout).toBe('function');
43
+ expect(typeof result.current.renewTokens).toBe('function');
44
+ });
45
+
46
+ it('login / logout / renewTokens resolve without throwing', async () => {
47
+ const { result } = renderHook(() => useOidc());
48
+ await expect(result.current.login()).resolves.toBeUndefined();
49
+ await expect(result.current.logout()).resolves.toBeUndefined();
50
+ await expect(result.current.renewTokens()).resolves.toMatchObject({
51
+ accessToken: null,
52
+ idToken: null,
53
+ });
54
+ });
55
+
56
+ it('warns once per configuration name', () => {
57
+ renderHook(() => useOidc('cfg-a'));
58
+ renderHook(() => useOidc('cfg-a'));
59
+ renderHook(() => useOidc('cfg-b'));
60
+ const messagesForA = warnSpy.mock.calls.filter(args => String(args[0]).includes('"cfg-a"'));
61
+ const messagesForB = warnSpy.mock.calls.filter(args => String(args[0]).includes('"cfg-b"'));
62
+ expect(messagesForA.length).toBe(1);
63
+ expect(messagesForB.length).toBe(1);
64
+ });
65
+ });
66
+
67
+ describe('useOidcAccessToken', () => {
68
+ it('returns the default access-token state', () => {
69
+ const { result } = renderHook(() => useOidcAccessToken());
70
+ expect(result.current).toEqual({ accessToken: null, accessTokenPayload: null });
71
+ });
72
+ });
73
+
74
+ describe('useOidcIdToken', () => {
75
+ it('returns the default id-token state', () => {
76
+ const { result } = renderHook(() => useOidcIdToken());
77
+ expect(result.current).toEqual({ idToken: null, idTokenPayload: null });
78
+ });
79
+ });
80
+
81
+ describe('useOidcUser', () => {
82
+ it('returns the default user state without throwing', () => {
83
+ const { result } = renderHook(() => useOidcUser());
84
+ expect(result.current.oidcUser).toBeNull();
85
+ expect(result.current.oidcUserLoadingState).toBe(OidcUserStatus.Unauthenticated);
86
+ expect(typeof result.current.reloadOidcUser).toBe('function');
87
+ });
88
+ });
89
+ });
@@ -0,0 +1,28 @@
1
+ const warnedConfigurations = new Set<string>();
2
+
3
+ /**
4
+ * Emits a `console.warn` once per `configurationName` when an OIDC hook is
5
+ * used without a matching `<OidcProvider>`. Introduced for issue #1679 so
6
+ * that consumers get a clear, non-fatal signal in tests and Storybook.
7
+ *
8
+ * Exported for testing purposes.
9
+ */
10
+ export const warnMissingConfigurationOnce = (configurationName: string): void => {
11
+ if (warnedConfigurations.has(configurationName)) {
12
+ return;
13
+ }
14
+ warnedConfigurations.add(configurationName);
15
+ console.warn(
16
+ `@axa-fr/react-oidc: no OIDC configuration found for "${configurationName}". ` +
17
+ `Make sure to wrap your component tree with <OidcProvider configurationName="${configurationName}">. ` +
18
+ `Hooks are returning safe default values (issue #1679).`,
19
+ );
20
+ };
21
+
22
+ /**
23
+ * Resets the internal set of already-warned configuration names. Intended
24
+ * for tests only.
25
+ */
26
+ export const resetWarnedConfigurations = (): void => {
27
+ warnedConfigurations.clear();
28
+ };