@bymax-one/nest-auth 1.4.22 → 1.5.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.
@@ -1,16 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var React = require('react');
4
-
5
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
6
-
7
- var React__default = /*#__PURE__*/_interopDefault(React);
8
-
9
- var __defProp = Object.defineProperty;
10
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
11
- var AuthContext = React.createContext(null);
3
+ var react = require('react');
4
+ var jsxRuntime = require('react/jsx-runtime');
12
5
 
13
6
  // src/react/AuthProvider.tsx
7
+ var AuthContext = react.createContext(null);
14
8
  var DEFAULT_REVALIDATE_INTERVAL_MS = 3e5;
15
9
  var HTTP_STATUS_MIN = 100;
16
10
  function clientErrorStatus(error) {
@@ -20,12 +14,10 @@ function clientErrorStatus(error) {
20
14
  const code = status;
21
15
  return code >= HTTP_STATUS_MIN ? code : void 0;
22
16
  }
23
- __name(clientErrorStatus, "clientErrorStatus");
24
17
  function isFinalAnswer(error) {
25
18
  const status = clientErrorStatus(error);
26
19
  return status !== void 0 && status < 500 && status !== 429;
27
20
  }
28
- __name(isFinalAnswer, "isFinalAnswer");
29
21
  var INITIAL_STATE = {
30
22
  user: null,
31
23
  status: "loading",
@@ -40,46 +32,34 @@ function authReducer(state, action) {
40
32
  lastValidation: action.payload.timestamp
41
33
  };
42
34
  case "SET_LOADING":
43
- return {
44
- ...state,
45
- status: "loading"
46
- };
35
+ return { ...state, status: "loading" };
47
36
  case "CLEAR_SESSION":
48
- return {
49
- user: null,
50
- status: "unauthenticated",
51
- lastValidation: null
52
- };
37
+ return { user: null, status: "unauthenticated", lastValidation: null };
53
38
  case "SET_ERROR":
54
- return {
55
- user: null,
56
- status: "unauthenticated",
57
- lastValidation: state.lastValidation
58
- };
39
+ return { user: null, status: "unauthenticated", lastValidation: state.lastValidation };
59
40
  }
60
41
  }
61
- __name(authReducer, "authReducer");
62
42
  function isSessionExpiredError(error) {
63
43
  return clientErrorStatus(error) === 401;
64
44
  }
65
- __name(isSessionExpiredError, "isSessionExpiredError");
66
- function AuthProvider({ children, client, onSessionExpired, revalidateInterval = DEFAULT_REVALIDATE_INTERVAL_MS }) {
67
- const [state, dispatch] = React.useReducer(authReducer, INITIAL_STATE);
68
- const onSessionExpiredRef = React.useRef(onSessionExpired);
69
- const clientRef = React.useRef(client);
70
- const statusRef = React.useRef(INITIAL_STATE.status);
71
- const sessionGenerationRef = React.useRef({});
72
- React.useEffect(() => {
45
+ function AuthProvider({
46
+ children,
47
+ client,
48
+ onSessionExpired,
49
+ revalidateInterval = DEFAULT_REVALIDATE_INTERVAL_MS
50
+ }) {
51
+ const [state, dispatch] = react.useReducer(authReducer, INITIAL_STATE);
52
+ const onSessionExpiredRef = react.useRef(onSessionExpired);
53
+ const clientRef = react.useRef(client);
54
+ const statusRef = react.useRef(INITIAL_STATE.status);
55
+ const sessionGenerationRef = react.useRef({});
56
+ react.useEffect(() => {
73
57
  onSessionExpiredRef.current = onSessionExpired;
74
- }, [
75
- onSessionExpired
76
- ]);
77
- React.useEffect(() => {
58
+ }, [onSessionExpired]);
59
+ react.useEffect(() => {
78
60
  clientRef.current = client;
79
- }, [
80
- client
81
- ]);
82
- const syncedDispatch = React.useCallback((action) => {
61
+ }, [client]);
62
+ const syncedDispatch = react.useCallback((action) => {
83
63
  dispatch(action);
84
64
  switch (action.type) {
85
65
  case "SET_USER":
@@ -95,47 +75,39 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
95
75
  return;
96
76
  }
97
77
  }, []);
98
- const revalidate = React.useCallback(async (isInitial) => {
99
- const generation = sessionGenerationRef.current;
100
- try {
101
- const user = await clientRef.current.getMe();
102
- if (sessionGenerationRef.current !== generation) return;
103
- syncedDispatch({
104
- type: "SET_USER",
105
- payload: {
106
- user,
107
- timestamp: /* @__PURE__ */ new Date()
108
- }
109
- });
110
- } catch (error) {
111
- if (sessionGenerationRef.current !== generation) return;
112
- const wasAuthenticated = statusRef.current === "authenticated";
113
- if (isSessionExpiredError(error)) {
114
- if (!isInitial && wasAuthenticated) {
115
- try {
116
- onSessionExpiredRef.current?.();
117
- } catch (callbackError) {
118
- console.warn("[nest-auth] onSessionExpired callback threw:", callbackError);
78
+ const revalidate = react.useCallback(
79
+ async (isInitial) => {
80
+ const generation = sessionGenerationRef.current;
81
+ try {
82
+ const user = await clientRef.current.getMe();
83
+ if (sessionGenerationRef.current !== generation) return;
84
+ syncedDispatch({ type: "SET_USER", payload: { user, timestamp: /* @__PURE__ */ new Date() } });
85
+ } catch (error) {
86
+ if (sessionGenerationRef.current !== generation) return;
87
+ const wasAuthenticated = statusRef.current === "authenticated";
88
+ if (isSessionExpiredError(error)) {
89
+ if (!isInitial && wasAuthenticated) {
90
+ try {
91
+ onSessionExpiredRef.current?.();
92
+ } catch (callbackError) {
93
+ console.warn("[nest-auth] onSessionExpired callback threw:", callbackError);
94
+ }
119
95
  }
96
+ syncedDispatch({ type: "CLEAR_SESSION" });
97
+ return;
120
98
  }
121
- syncedDispatch({
122
- type: "CLEAR_SESSION"
123
- });
124
- return;
99
+ syncedDispatch({ type: "SET_ERROR" });
125
100
  }
126
- syncedDispatch({
127
- type: "SET_ERROR"
128
- });
129
- }
130
- }, [
131
- syncedDispatch
132
- ]);
133
- React.useEffect(() => {
101
+ },
102
+ [syncedDispatch]
103
+ );
104
+ react.useEffect(() => {
134
105
  void revalidate(true);
135
- }, [
136
- revalidate
137
- ]);
138
- React.useEffect(() => {
106
+ return () => {
107
+ sessionGenerationRef.current = {};
108
+ };
109
+ }, [revalidate]);
110
+ react.useEffect(() => {
139
111
  if (revalidateInterval <= 0) {
140
112
  return void 0;
141
113
  }
@@ -145,80 +117,51 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
145
117
  return () => {
146
118
  clearInterval(handle);
147
119
  };
148
- }, [
149
- revalidate,
150
- revalidateInterval
151
- ]);
152
- const login = React.useCallback(async (email, password, options) => {
153
- syncedDispatch({
154
- type: "SET_LOADING"
155
- });
156
- try {
157
- const result = await clientRef.current.login({
158
- email,
159
- password,
160
- ...options?.tenantId !== void 0 ? {
161
- tenantId: options.tenantId
162
- } : {}
163
- });
164
- if ("mfaRequired" in result) {
165
- sessionGenerationRef.current = {};
166
- syncedDispatch({
167
- type: "CLEAR_SESSION"
120
+ }, [revalidate, revalidateInterval]);
121
+ const login = react.useCallback(
122
+ async (email, password, options) => {
123
+ syncedDispatch({ type: "SET_LOADING" });
124
+ try {
125
+ const result = await clientRef.current.login({
126
+ email,
127
+ password,
128
+ ...options?.tenantId !== void 0 ? { tenantId: options.tenantId } : {}
168
129
  });
130
+ if ("mfaRequired" in result) {
131
+ sessionGenerationRef.current = {};
132
+ syncedDispatch({ type: "CLEAR_SESSION" });
133
+ return result;
134
+ }
135
+ sessionGenerationRef.current = {};
136
+ syncedDispatch({ type: "SET_USER", payload: { user: result.user, timestamp: /* @__PURE__ */ new Date() } });
169
137
  return result;
138
+ } catch (error) {
139
+ syncedDispatch({ type: "SET_ERROR" });
140
+ throw error;
170
141
  }
171
- sessionGenerationRef.current = {};
172
- syncedDispatch({
173
- type: "SET_USER",
174
- payload: {
175
- user: result.user,
176
- timestamp: /* @__PURE__ */ new Date()
177
- }
178
- });
179
- return result;
180
- } catch (error) {
181
- syncedDispatch({
182
- type: "SET_ERROR"
183
- });
184
- throw error;
185
- }
186
- }, [
187
- syncedDispatch
188
- ]);
189
- const register = React.useCallback(async (data) => {
190
- syncedDispatch({
191
- type: "SET_LOADING"
192
- });
193
- try {
194
- const result = await clientRef.current.register(data);
195
- sessionGenerationRef.current = {};
196
- syncedDispatch({
197
- type: "SET_USER",
198
- payload: {
199
- user: result.user,
200
- timestamp: /* @__PURE__ */ new Date()
201
- }
202
- });
203
- return result;
204
- } catch (error) {
205
- syncedDispatch({
206
- type: "SET_ERROR"
207
- });
208
- throw error;
209
- }
210
- }, [
211
- syncedDispatch
212
- ]);
213
- const clearSession = React.useCallback(() => {
142
+ },
143
+ [syncedDispatch]
144
+ );
145
+ const register = react.useCallback(
146
+ async (data) => {
147
+ syncedDispatch({ type: "SET_LOADING" });
148
+ try {
149
+ const result = await clientRef.current.register(data);
150
+ sessionGenerationRef.current = {};
151
+ syncedDispatch({ type: "SET_USER", payload: { user: result.user, timestamp: /* @__PURE__ */ new Date() } });
152
+ return result;
153
+ } catch (error) {
154
+ syncedDispatch({ type: "SET_ERROR" });
155
+ throw error;
156
+ }
157
+ },
158
+ [syncedDispatch]
159
+ );
160
+ const clearSession = react.useCallback(() => {
214
161
  sessionGenerationRef.current = {};
215
- syncedDispatch({
216
- type: "CLEAR_SESSION"
217
- });
218
- }, [
219
- syncedDispatch
220
- ]);
221
- const logout = React.useCallback(async () => {
162
+ syncedDispatch({ type: "CLEAR_SESSION" });
163
+ }, [syncedDispatch]);
164
+ const logout = react.useCallback(async () => {
222
165
  try {
223
166
  await clientRef.current.logout();
224
167
  } catch (error) {
@@ -227,59 +170,57 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
227
170
  throw error;
228
171
  }
229
172
  clearSession();
230
- }, [
231
- clearSession
232
- ]);
233
- const refresh = React.useCallback(async () => {
173
+ }, [clearSession]);
174
+ const refresh = react.useCallback(async () => {
234
175
  await revalidate(false);
235
- }, [
236
- revalidate
237
- ]);
238
- const forgotPassword = React.useCallback(
176
+ }, [revalidate]);
177
+ const forgotPassword = react.useCallback(
239
178
  async (email, tenantId) => {
240
179
  await clientRef.current.forgotPassword(email, tenantId);
241
180
  },
242
181
  // Stryker disable next-line ArrayDeclaration: empty deps array with only stable references in scope; a constant-string array re-runs identically
243
182
  []
244
183
  );
245
- const resetPassword = React.useCallback(
184
+ const resetPassword = react.useCallback(
246
185
  async (input) => {
247
186
  await clientRef.current.resetPassword(input);
248
187
  },
249
188
  // Stryker disable next-line ArrayDeclaration: empty deps array with only stable references in scope; a constant-string array re-runs identically
250
189
  []
251
190
  );
252
- const value = React.useMemo(() => ({
253
- user: state.user,
254
- status: state.status,
255
- isLoading: state.status === "loading",
256
- lastValidation: state.lastValidation,
257
- login,
258
- register,
259
- logout,
260
- refresh,
261
- forgotPassword,
262
- resetPassword
263
- }), [
264
- state.user,
265
- state.status,
266
- state.lastValidation,
267
- login,
268
- register,
269
- logout,
270
- refresh,
271
- forgotPassword,
272
- resetPassword
273
- ]);
274
- return /* @__PURE__ */ React__default.default.createElement(AuthContext.Provider, {
275
- value
276
- }, children);
191
+ const value = react.useMemo(
192
+ () => ({
193
+ user: state.user,
194
+ status: state.status,
195
+ isLoading: state.status === "loading",
196
+ lastValidation: state.lastValidation,
197
+ login,
198
+ register,
199
+ logout,
200
+ refresh,
201
+ forgotPassword,
202
+ resetPassword
203
+ }),
204
+ [
205
+ state.user,
206
+ state.status,
207
+ state.lastValidation,
208
+ login,
209
+ register,
210
+ logout,
211
+ refresh,
212
+ forgotPassword,
213
+ resetPassword
214
+ ]
215
+ );
216
+ return /* @__PURE__ */ jsxRuntime.jsx(AuthContext.Provider, { value, children });
277
217
  }
278
- __name(AuthProvider, "AuthProvider");
279
218
  function useSession() {
280
- const ctx = React.useContext(AuthContext);
219
+ const ctx = react.useContext(AuthContext);
281
220
  if (ctx === null) {
282
- throw new Error("useSession must be called within an <AuthProvider> \u2014 wrap the consuming tree in a provider built from createAuthClient().");
221
+ throw new Error(
222
+ "useSession must be called within an <AuthProvider> \u2014 wrap the consuming tree in a provider built from createAuthClient()."
223
+ );
283
224
  }
284
225
  return {
285
226
  user: ctx.user,
@@ -289,11 +230,12 @@ function useSession() {
289
230
  lastValidation: ctx.lastValidation
290
231
  };
291
232
  }
292
- __name(useSession, "useSession");
293
233
  function useAuth() {
294
- const ctx = React.useContext(AuthContext);
234
+ const ctx = react.useContext(AuthContext);
295
235
  if (ctx === null) {
296
- throw new Error("useAuth must be called within an <AuthProvider> \u2014 wrap the consuming tree in a provider built from createAuthClient().");
236
+ throw new Error(
237
+ "useAuth must be called within an <AuthProvider> \u2014 wrap the consuming tree in a provider built from createAuthClient()."
238
+ );
297
239
  }
298
240
  return {
299
241
  login: ctx.login,
@@ -303,7 +245,6 @@ function useAuth() {
303
245
  resetPassword: ctx.resetPassword
304
246
  };
305
247
  }
306
- __name(useAuth, "useAuth");
307
248
 
308
249
  // src/react/useAuthStatus.ts
309
250
  function useAuthStatus() {
@@ -313,9 +254,265 @@ function useAuthStatus() {
313
254
  isLoading
314
255
  };
315
256
  }
316
- __name(useAuthStatus, "useAuthStatus");
257
+ var WorkspacesContext = react.createContext(null);
258
+ var CHANNEL_NAME = "nest-auth:workspaces";
259
+ var MAX_PAGES = 20;
260
+ var REFUSAL_CODES = /* @__PURE__ */ new Set([
261
+ "auth.workspace_not_found",
262
+ "auth.insufficient_workspace_role",
263
+ "auth.workspace_pending_deletion"
264
+ ]);
265
+ var IDLE = {
266
+ owner: null,
267
+ status: "idle",
268
+ items: [],
269
+ lastActiveWorkspaceId: null,
270
+ chosen: null
271
+ };
272
+ var loadingFor = (owner) => ({ ...IDLE, owner, status: "loading" });
273
+ async function loadAll(client, signal) {
274
+ const items = [];
275
+ let lastActiveWorkspaceId = null;
276
+ let cursor;
277
+ for (let page = 0; page < MAX_PAGES; page += 1) {
278
+ const result = await client.listWorkspaces(cursor === void 0 ? void 0 : { cursor }, {
279
+ signal
280
+ });
281
+ if (signal.aborted) break;
282
+ if (page === 0) lastActiveWorkspaceId = result.lastActiveWorkspaceId;
283
+ items.push(...result.items);
284
+ if (result.nextCursor === null) break;
285
+ cursor = result.nextCursor;
286
+ }
287
+ return { items, lastActiveWorkspaceId };
288
+ }
289
+ function refusalCodeOf(error) {
290
+ if (typeof error !== "object" || error === null) return void 0;
291
+ const { name, code } = error;
292
+ if (name !== "AuthClientError" || typeof code !== "string") return void 0;
293
+ return REFUSAL_CODES.has(code) ? code : void 0;
294
+ }
295
+ function callHost(name, run) {
296
+ try {
297
+ run?.();
298
+ } catch (error) {
299
+ console.warn(`[nest-auth] ${name} callback threw:`, error);
300
+ }
301
+ }
302
+ function useReload(clientRef, statusRef, identityRef, setLoaded, controllerRef) {
303
+ return react.useCallback(async () => {
304
+ const owner = identityRef.current;
305
+ if (statusRef.current !== "authenticated") return;
306
+ controllerRef.current?.abort();
307
+ const controller = new AbortController();
308
+ controllerRef.current = controller;
309
+ try {
310
+ const result = await loadAll(clientRef.current, controller.signal);
311
+ if (!controller.signal.aborted) {
312
+ setLoaded((current) => ({
313
+ ...result,
314
+ owner,
315
+ status: "ready",
316
+ chosen: current.chosen
317
+ }));
318
+ }
319
+ } catch {
320
+ if (!controller.signal.aborted) {
321
+ setLoaded((current) => ({
322
+ ...IDLE,
323
+ owner,
324
+ status: "error",
325
+ chosen: current.chosen
326
+ }));
327
+ }
328
+ }
329
+ }, [clientRef, statusRef, identityRef, setLoaded, controllerRef]);
330
+ }
331
+ function useWorkspaceList(client, authStatus, identity) {
332
+ const [stored, setLoaded] = react.useState(IDLE);
333
+ const clientRef = react.useRef(client);
334
+ const statusRef = react.useRef(authStatus);
335
+ const identityRef = react.useRef(identity);
336
+ const controllerRef = react.useRef(null);
337
+ react.useEffect(() => {
338
+ clientRef.current = client;
339
+ statusRef.current = authStatus;
340
+ identityRef.current = identity;
341
+ });
342
+ const refresh = useReload(clientRef, statusRef, identityRef, setLoaded, controllerRef);
343
+ react.useEffect(() => {
344
+ if (authStatus === "authenticated" && identity !== null) {
345
+ setLoaded(
346
+ (current) => current.owner === identity && current.status === "ready" ? current : loadingFor(identity)
347
+ );
348
+ void refresh();
349
+ } else if (authStatus === "unauthenticated") {
350
+ setLoaded(IDLE);
351
+ }
352
+ return () => {
353
+ controllerRef.current?.abort();
354
+ };
355
+ }, [authStatus, identity, refresh]);
356
+ const loaded = stored.owner === identity ? stored : identity === null ? IDLE : loadingFor(identity);
357
+ return { loaded, setLoaded, clientRef, identityRef, statusRef, refresh };
358
+ }
359
+ function useChangeNotice(status, active, optionsRef) {
360
+ const previousRef = react.useRef(
361
+ null
362
+ );
363
+ react.useEffect(() => {
364
+ if (status === "loading") previousRef.current = null;
365
+ if (status !== "ready") return;
366
+ const previous = previousRef.current;
367
+ previousRef.current = { id: active?.workspace.id ?? null, value: active };
368
+ if (previous === null || previous.id === (active?.workspace.id ?? null)) return;
369
+ callHost(
370
+ "onWorkspaceChanged",
371
+ () => optionsRef.current.onWorkspaceChanged?.(previous.value, active)
372
+ );
373
+ }, [status, active, optionsRef]);
374
+ }
375
+ function useBroadcastReload(sessionRefresh, statusRef, identityRef, reload) {
376
+ const [request, setRequest] = react.useState(null);
377
+ react.useEffect(() => {
378
+ if (request !== null && request.heardAs === identityRef.current) void reload();
379
+ }, [request, identityRef, reload]);
380
+ return react.useCallback(() => {
381
+ if (statusRef.current !== "authenticated") return;
382
+ const heardAs = identityRef.current;
383
+ void sessionRefresh().then(() => setRequest({ heardAs }));
384
+ }, [sessionRefresh, statusRef, identityRef]);
385
+ }
386
+ function useWorkspaceChannel(onMessage) {
387
+ const channelRef = react.useRef(null);
388
+ react.useEffect(() => {
389
+ if (typeof BroadcastChannel === "undefined") return void 0;
390
+ const channel = new BroadcastChannel(CHANNEL_NAME);
391
+ channel.onmessage = onMessage;
392
+ channelRef.current = channel;
393
+ return () => {
394
+ channelRef.current = null;
395
+ channel.close();
396
+ };
397
+ }, [onMessage]);
398
+ return channelRef;
399
+ }
400
+ function useRoleHint(active, items, optionsRef) {
401
+ return react.useCallback(
402
+ (role, workspaceId) => {
403
+ const target = workspaceId === void 0 ? active : items.find((item) => item.workspace.id === workspaceId) ?? null;
404
+ if (target === null) return false;
405
+ if (target.role === role) return true;
406
+ const included = Object.entries(optionsRef.current.hierarchy ?? {});
407
+ return included.some(([held, covers]) => held === target.role && covers.includes(role));
408
+ },
409
+ [active, items, optionsRef]
410
+ );
411
+ }
412
+ function useRefusalHandler(activeId, optionsRef, refresh) {
413
+ return react.useCallback(
414
+ (workspaceId, error) => {
415
+ const code = refusalCodeOf(error);
416
+ if (code === void 0) return false;
417
+ if (workspaceId !== activeId) return true;
418
+ callHost(
419
+ "onWorkspaceAccessLost",
420
+ () => optionsRef.current.onWorkspaceAccessLost?.(workspaceId, code)
421
+ );
422
+ void refresh();
423
+ return true;
424
+ },
425
+ [activeId, optionsRef, refresh]
426
+ );
427
+ }
428
+ function useSwitch(clientRef, identityRef, setLoaded, channelRef) {
429
+ return react.useCallback(
430
+ async (workspaceId) => {
431
+ const owner = identityRef.current;
432
+ await clientRef.current.switchWorkspace(workspaceId);
433
+ if (identityRef.current !== owner) return;
434
+ setLoaded((current) => ({
435
+ ...current,
436
+ chosen: workspaceId,
437
+ lastActiveWorkspaceId: workspaceId
438
+ }));
439
+ channelRef.current?.postMessage({ type: "workspaces-changed" });
440
+ },
441
+ // Stryker disable next-line ArrayDeclaration: refs and a state setter are stable references, so `[]` re-creates the callback exactly as often
442
+ [clientRef, identityRef, setLoaded, channelRef]
443
+ );
444
+ }
445
+ function WorkspaceProvider({
446
+ client,
447
+ children,
448
+ ...options
449
+ }) {
450
+ const ctx = react.useContext(AuthContext);
451
+ if (ctx === null) {
452
+ throw new Error(
453
+ "WorkspaceProvider must be rendered within an <AuthProvider> \u2014 it follows the session the provider owns."
454
+ );
455
+ }
456
+ const optionsRef = react.useRef(options);
457
+ react.useEffect(() => {
458
+ optionsRef.current = options;
459
+ });
460
+ const identity = ctx.user === null ? null : JSON.stringify([ctx.user.tenantId, ctx.user.id]);
461
+ const { loaded, setLoaded, clientRef, identityRef, statusRef, refresh } = useWorkspaceList(
462
+ client,
463
+ ctx.status,
464
+ identity
465
+ );
466
+ const activeId = options.activeWorkspaceId ?? loaded.chosen ?? loaded.lastActiveWorkspaceId;
467
+ const activeWorkspace = react.useMemo(
468
+ () => loaded.items.find((item) => item.workspace.id === activeId) ?? null,
469
+ [loaded.items, activeId]
470
+ );
471
+ useChangeNotice(loaded.status, activeWorkspace, optionsRef);
472
+ const onBroadcast = useBroadcastReload(ctx.refresh, statusRef, identityRef, refresh);
473
+ const channelRef = useWorkspaceChannel(onBroadcast);
474
+ const hasWorkspaceRole = useRoleHint(activeWorkspace, loaded.items, optionsRef);
475
+ const handleWorkspaceError = useRefusalHandler(activeId, optionsRef, refresh);
476
+ const switchWorkspace = useSwitch(clientRef, identityRef, setLoaded, channelRef);
477
+ const value = react.useMemo(
478
+ () => ({
479
+ memberships: loaded.items,
480
+ activeWorkspace,
481
+ lastActiveWorkspaceId: loaded.lastActiveWorkspaceId,
482
+ status: loaded.status,
483
+ switchWorkspace,
484
+ hasWorkspaceRole,
485
+ handleWorkspaceError,
486
+ refresh
487
+ }),
488
+ [loaded, activeWorkspace, switchWorkspace, hasWorkspaceRole, handleWorkspaceError, refresh]
489
+ );
490
+ return /* @__PURE__ */ jsxRuntime.jsx(WorkspacesContext.Provider, { value, children });
491
+ }
492
+ var DISABLED = {
493
+ memberships: [],
494
+ activeWorkspace: null,
495
+ lastActiveWorkspaceId: null,
496
+ status: "disabled",
497
+ switchWorkspace: () => Promise.reject(
498
+ new Error("useWorkspaces: render a <WorkspaceProvider> inside <AuthProvider> to enable it.")
499
+ ),
500
+ hasWorkspaceRole: () => false,
501
+ handleWorkspaceError: () => false,
502
+ refresh: () => Promise.resolve()
503
+ };
504
+ function useWorkspaces() {
505
+ if (react.useContext(AuthContext) === null) {
506
+ throw new Error(
507
+ "useWorkspaces must be called within an <AuthProvider> \u2014 wrap the consuming tree in a provider built from createAuthClient()."
508
+ );
509
+ }
510
+ return react.useContext(WorkspacesContext) ?? DISABLED;
511
+ }
317
512
 
318
513
  exports.AuthProvider = AuthProvider;
514
+ exports.WorkspaceProvider = WorkspaceProvider;
319
515
  exports.useAuth = useAuth;
320
516
  exports.useAuthStatus = useAuthStatus;
321
517
  exports.useSession = useSession;
518
+ exports.useWorkspaces = useWorkspaces;