@clerk/shared 4.43.1 → 4.43.2-canary.v20261030213133

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/alternativePhoneCode.js +1 -2
  2. package/dist/apiUrlFromPublishableKey.js +1 -2
  3. package/dist/authorization-errors.js +1 -2
  4. package/dist/authorization.js +1 -2
  5. package/dist/browser.js +1 -2
  6. package/dist/buildAccountsBaseUrl.js +1 -2
  7. package/dist/clerkEventBus.js +1 -2
  8. package/dist/color.js +1 -2
  9. package/dist/constants.js +1 -2
  10. package/dist/cookie.js +3 -4
  11. package/dist/date.js +1 -2
  12. package/dist/deprecated.js +2 -3
  13. package/dist/deriveState.js +1 -2
  14. package/dist/devBrowser.js +1 -2
  15. package/dist/dom/waitForElement.js +1 -2
  16. package/dist/error.js +42 -32
  17. package/dist/eventBus.js +1 -2
  18. package/dist/file.js +1 -2
  19. package/dist/getEnvVariable.js +1 -2
  20. package/dist/getToken.js +2 -3
  21. package/dist/globs.js +3 -4
  22. package/dist/handleValueOrFn.js +2 -3
  23. package/dist/htmlSafeJson.js +1 -2
  24. package/dist/index.js +1 -2
  25. package/dist/inert.js +1 -2
  26. package/dist/internal/clerk-js/completeSignUpFlow.js +1 -2
  27. package/dist/internal/clerk-js/componentGuards.js +1 -2
  28. package/dist/internal/clerk-js/constants.js +1 -2
  29. package/dist/internal/clerk-js/email.js +1 -2
  30. package/dist/internal/clerk-js/encoders.js +1 -2
  31. package/dist/internal/clerk-js/enterpriseSSOFactors.js +1 -2
  32. package/dist/internal/clerk-js/errors.js +1 -2
  33. package/dist/internal/clerk-js/hex.js +1 -2
  34. package/dist/internal/clerk-js/injectedWeb3EthProviders.js +1 -2
  35. package/dist/internal/clerk-js/injectedWeb3SolanaProviders.js +2 -3
  36. package/dist/internal/clerk-js/navigateToNextStepSignUp.js +1 -2
  37. package/dist/internal/clerk-js/organization.js +1 -2
  38. package/dist/internal/clerk-js/passkeys.js +10 -10
  39. package/dist/internal/clerk-js/passwords/complexity.js +1 -2
  40. package/dist/internal/clerk-js/passwords/loadZxcvbn.js +1 -2
  41. package/dist/internal/clerk-js/passwords/password.js +2 -3
  42. package/dist/internal/clerk-js/passwords/strength.js +1 -2
  43. package/dist/internal/clerk-js/path.js +1 -2
  44. package/dist/internal/clerk-js/protectCheck.js +3 -4
  45. package/dist/internal/clerk-js/protectCheckRunner.js +5 -5
  46. package/dist/internal/clerk-js/queryParams.js +1 -2
  47. package/dist/internal/clerk-js/queryStateParams.js +1 -2
  48. package/dist/internal/clerk-js/querystring.js +1 -2
  49. package/dist/internal/clerk-js/redirectUrls.js +1 -2
  50. package/dist/internal/clerk-js/runtime.js +1 -2
  51. package/dist/internal/clerk-js/sessionTasks.js +1 -2
  52. package/dist/internal/clerk-js/thirdPartyDomains.js +1 -2
  53. package/dist/internal/clerk-js/url.js +1 -2
  54. package/dist/internal/clerk-js/user.js +1 -2
  55. package/dist/internal/clerk-js/warnings.js +1 -2
  56. package/dist/internal/clerk-js/web3.js +5 -5
  57. package/dist/internal/clerk-js/windowNavigate.js +1 -2
  58. package/dist/isomorphicAtob.js +1 -2
  59. package/dist/isomorphicBtoa.js +1 -2
  60. package/dist/jwtPayloadParser.js +1 -2
  61. package/dist/keyless/index.js +12 -369
  62. package/dist/keys.js +2 -3
  63. package/dist/loadClerkJsScript.js +6 -6
  64. package/dist/loadClerkJsScript.js.map +1 -1
  65. package/dist/loadClerkJsScript.mjs +1 -1
  66. package/dist/loadClerkJsScript.mjs.map +1 -1
  67. package/dist/loadScript.js +1 -2
  68. package/dist/localStorageBroadcastChannel.js +1 -2
  69. package/dist/logger.js +1 -2
  70. package/dist/netlifyCacheHandler.js +1 -2
  71. package/dist/oauth.js +1 -2
  72. package/dist/object.js +1 -2
  73. package/dist/organization.js +1 -2
  74. package/dist/patchRequest.js +1 -2
  75. package/dist/pathMatcher.js +2 -3
  76. package/dist/pathToRegexp.js +23 -3
  77. package/dist/phone/index.js +14 -1649
  78. package/dist/poller.js +3 -4
  79. package/dist/proxy.js +1 -2
  80. package/dist/react/index.js +111 -4379
  81. package/dist/retry.js +1 -2
  82. package/dist/router.js +9 -150
  83. package/dist/safeImport.js +1 -2
  84. package/dist/saml.js +1 -2
  85. package/dist/telemetry.js +16 -11
  86. package/dist/underscore.js +1 -2
  87. package/dist/url.js +2 -3
  88. package/dist/utils/index.js +16 -12
  89. package/dist/versionCheck.js +1 -2
  90. package/dist/versionSelector.js +2 -3
  91. package/dist/versionSelector.js.map +1 -1
  92. package/dist/versionSelector.mjs +1 -1
  93. package/dist/versionSelector.mjs.map +1 -1
  94. package/dist/web3.js +1 -2
  95. package/dist/webauthn.js +1 -2
  96. package/dist/workerTimers/index.js +2 -2
  97. package/package.json +1 -1
@@ -1,4380 +1,112 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_chunk = require('../_chunks/chunk-C_NdSu1c.js');
3
- const require_authorization_errors = require('../authorization-errors.js');
4
- const require_authorization = require('../authorization.js');
5
- const require_deriveState = require('../deriveState.js');
6
- const require_clerkRuntimeError = require('../_chunks/clerkRuntimeError-CYZdTZ_x.js');
7
- const require_error = require('../_chunks/error-Ce3s-kIk.js');
8
- const require_logger = require('../logger.js');
9
- const require_organization = require('../organization.js');
10
- const require_telemetry = require('../_chunks/telemetry-DZp9OI1j.js');
11
- const require_createDeferredPromise = require('../_chunks/createDeferredPromise-BXa3LUQE.js');
12
- const require_internal_clerk_js_errors = require('../internal/clerk-js/errors.js');
13
- let react = require("react");
14
- react = require_chunk.__toESM(react);
15
- let _tanstack_query_core = require("@tanstack/query-core");
16
- let dequal = require("dequal");
17
-
18
- //#region src/react/hooks/createContextAndHook.ts
19
- /**
20
- * Assert that the context value exists, otherwise throw an error.
21
- *
22
- * @internal
23
- */
24
- function assertContextExists(contextVal, msgOrCtx) {
25
- if (!contextVal) throw typeof msgOrCtx === "string" ? new Error(msgOrCtx) : /* @__PURE__ */ new Error(`${msgOrCtx.displayName} not found`);
26
- }
27
- /**
28
- * Create and return a Context and two hooks that return the context value.
29
- * The Context type is derived from the type passed in by the user.
30
- *
31
- * The first hook returned guarantees that the context exists so the returned value is always `CtxValue`
32
- * The second hook makes no guarantees, so the returned value can be `CtxValue | undefined`
33
- *
34
- * @internal
35
- */
36
- const createContextAndHook = (displayName, options) => {
37
- const { assertCtxFn = assertContextExists } = options || {};
38
- const Ctx = react.default.createContext(void 0);
39
- Ctx.displayName = displayName;
40
- const useCtx = () => {
41
- const ctx = react.default.useContext(Ctx);
42
- assertCtxFn(ctx, `${displayName} not found`);
43
- return ctx.value;
44
- };
45
- const useCtxWithoutGuarantee = () => {
46
- const ctx = react.default.useContext(Ctx);
47
- return ctx ? ctx.value : {};
48
- };
49
- return [
50
- Ctx,
51
- useCtx,
52
- useCtxWithoutGuarantee
53
- ];
54
- };
55
-
56
- //#endregion
57
- //#region src/react/contexts.tsx
58
- const [ClerkInstanceContext, useClerkInstanceContext] = createContextAndHook("ClerkInstanceContext");
59
- const [InitialStateContext, _useInitialStateContext] = createContextAndHook("InitialStateContext");
60
- /**
61
- * Provides initial Clerk state (session, user, organization data) from server-side rendering
62
- * to child components via React context.
63
- *
64
- * Passing in a promise is only supported for React >= 19.
65
- *
66
- * The initialState is snapshotted on mount and cannot change during the component lifecycle.
67
- *
68
- * Note that different parts of the React tree can use separate InitialStateProvider instances
69
- * with different initialState values if needed.
70
- */
71
- function InitialStateProvider({ children, initialState }) {
72
- const [initialStateSnapshot] = (0, react.useState)(initialState);
73
- const initialStateCtx = react.default.useMemo(() => ({ value: initialStateSnapshot }), [initialStateSnapshot]);
74
- return /* @__PURE__ */ react.default.createElement(InitialStateContext.Provider, { value: initialStateCtx }, children);
75
- }
76
- function useInitialStateContext() {
77
- const initialState = _useInitialStateContext();
78
- if (initialState instanceof Promise) if ("use" in react.default && typeof react.default.use === "function") return react.default.use(initialState);
79
- else throw new Error("initialState cannot be a promise if React version is less than 19");
80
- return initialState;
81
- }
82
- const OptionsContext = react.default.createContext({});
83
- const [CheckoutContext, useCheckoutContext] = createContextAndHook("CheckoutContext");
84
- const __experimental_CheckoutProvider = ({ children, ...rest }) => {
85
- return /* @__PURE__ */ react.default.createElement(CheckoutContext.Provider, { value: { value: rest } }, children);
86
- };
87
- /**
88
- * @internal
89
- */
90
- function useOptionsContext() {
91
- const context = react.default.useContext(OptionsContext);
92
- if (context === void 0) throw new Error("useOptions must be used within an OptionsContext");
93
- return context;
94
- }
95
- /**
96
- * @internal
97
- */
98
- function useAssertWrappedByClerkProvider(displayNameOrFn) {
99
- if (!react.default.useContext(ClerkInstanceContext)) {
100
- if (typeof displayNameOrFn === "function") {
101
- displayNameOrFn();
102
- return;
103
- }
104
- throw new Error(`${displayNameOrFn} can only be used within the <ClerkProvider /> component.
105
-
106
- Possible fixes:
107
- 1. Ensure that the <ClerkProvider /> is correctly wrapping your application where this component is used.
108
- 2. Check for multiple versions of the \`@clerk/shared\` package in your project. Use a tool like \`npm ls @clerk/shared\` to identify multiple versions, and update your dependencies to only rely on one.
109
-
110
- Learn more: https://clerk.com/docs/components/clerk-provider`.trim());
111
- }
112
- }
113
-
114
- //#endregion
115
- //#region src/react/stable-keys.ts
116
- const USER_MEMBERSHIPS_KEY = "userMemberships";
117
- const USER_INVITATIONS_KEY = "userInvitations";
118
- const USER_SUGGESTIONS_KEY = "userSuggestions";
119
- const DOMAINS_KEY = "domains";
120
- const MEMBERSHIP_REQUESTS_KEY = "membershipRequests";
121
- const MEMBERSHIPS_KEY = "memberships";
122
- const INVITATIONS_KEY = "invitations";
123
- const API_KEYS_KEY = "apiKeys";
124
- const ORGANIZATION_CREATION_DEFAULTS_KEY = "organizationCreationDefaults";
125
- const OAUTH_CONSENT_INFO_KEY = "oauthConsentInfo";
126
- const PLANS_KEY = "billing-plans";
127
- const SUBSCRIPTION_KEY = "billing-subscription";
128
- const PAYMENT_METHODS_KEY = "billing-payment-methods";
129
- const PAYMENT_ATTEMPTS_KEY = "billing-payment-attempts";
130
- const STATEMENTS_KEY = "billing-statements";
131
- const CREDIT_BALANCE_KEY = "billing-credit-balance";
132
- const STABLE_KEYS = {
133
- USER_MEMBERSHIPS_KEY,
134
- USER_INVITATIONS_KEY,
135
- USER_SUGGESTIONS_KEY,
136
- DOMAINS_KEY,
137
- MEMBERSHIP_REQUESTS_KEY,
138
- MEMBERSHIPS_KEY,
139
- INVITATIONS_KEY,
140
- PLANS_KEY,
141
- SUBSCRIPTION_KEY,
142
- PAYMENT_METHODS_KEY,
143
- PAYMENT_ATTEMPTS_KEY,
144
- STATEMENTS_KEY,
145
- API_KEYS_KEY,
146
- ORGANIZATION_CREATION_DEFAULTS_KEY,
147
- OAUTH_CONSENT_INFO_KEY,
148
- CREDIT_BALANCE_KEY
149
- };
150
- /**
151
- * Internal stable keys for queries only used by our UI components.
152
- * These keys are not used by the hooks themselves.
153
- */
154
- const PAYMENT_ATTEMPT_KEY = "billing-payment-attempt";
155
- const BILLING_PLANS_KEY = "billing-plan";
156
- const BILLING_STATEMENTS_KEY = "billing-statement";
157
- const USER_ENTERPRISE_CONNECTIONS_KEY = "userEnterpriseConnections";
158
- const ENTERPRISE_CONNECTION_TEST_RUNS_KEY = "enterpriseConnectionTestRuns";
159
- const ORGANIZATION_ENTERPRISE_CONNECTIONS_KEY = "organizationEnterpriseConnections";
160
- const ORGANIZATION_ENTERPRISE_CONNECTION_TEST_RUNS_KEY = "organizationEnterpriseConnectionTestRuns";
161
- const ORGANIZATION_DOMAINS_KEY = "organizationDomains";
162
- const ORGANIZATION_DIRECTORY_SYNC_KEY = "organizationDirectorySync";
163
- const ORGANIZATION_DIRECTORY_SYNC_USERS_KEY = "organizationDirectorySyncUsers";
164
- const ORGANIZATION_DIRECTORY_SYNC_STATUS_KEY = "organizationDirectorySyncStatus";
165
- const ORGANIZATION_DIRECTORY_SYNC_GROUP_ROLE_MAPPINGS_KEY = "organizationDirectorySyncGroupRoleMappings";
166
- const ORGANIZATION_SSO_BYPASS_ALLOWLIST_KEY = "organizationSSOBypassAllowlist";
167
- const CREDIT_HISTORY_KEY = "billing-credit-history";
168
- const INTERNAL_STABLE_KEYS = {
169
- PAYMENT_ATTEMPT_KEY,
170
- BILLING_PLANS_KEY,
171
- BILLING_STATEMENTS_KEY,
172
- CREDIT_HISTORY_KEY,
173
- USER_ENTERPRISE_CONNECTIONS_KEY,
174
- ENTERPRISE_CONNECTION_TEST_RUNS_KEY,
175
- ORGANIZATION_ENTERPRISE_CONNECTIONS_KEY,
176
- ORGANIZATION_ENTERPRISE_CONNECTION_TEST_RUNS_KEY,
177
- ORGANIZATION_DOMAINS_KEY,
178
- ORGANIZATION_DIRECTORY_SYNC_KEY,
179
- ORGANIZATION_DIRECTORY_SYNC_USERS_KEY,
180
- ORGANIZATION_DIRECTORY_SYNC_STATUS_KEY,
181
- ORGANIZATION_DIRECTORY_SYNC_GROUP_ROLE_MAPPINGS_KEY,
182
- ORGANIZATION_SSO_BYPASS_ALLOWLIST_KEY
183
- };
184
-
185
- //#endregion
186
- //#region src/react/hooks/createCacheKeys.ts
187
- /**
188
- * @internal
189
- */
190
- function createCacheKeys(params) {
191
- return {
192
- queryKey: [
193
- params.stablePrefix,
194
- params.authenticated,
195
- params.tracked,
196
- params.untracked
197
- ],
198
- invalidationKey: [
199
- params.stablePrefix,
200
- params.authenticated,
201
- params.tracked
202
- ],
203
- stableKey: params.stablePrefix,
204
- authenticated: params.authenticated
205
- };
206
- }
207
-
208
- //#endregion
209
- //#region src/react/query/keep-previous-data.ts
210
- /**
211
- * @internal
212
- */
213
- function defineKeepPreviousDataFn(enabled) {
214
- if (enabled) return function KeepPreviousDataFn(previousData) {
215
- return previousData;
216
- };
217
- }
218
-
219
- //#endregion
220
- //#region src/react/query/clerk-query-client.ts
221
- /**
222
- * The QueryClient backing every clerk-query hook. Owned by `@clerk/shared` so the
223
- * `QueryObserver` that observes it and the `Query` objects inside it always
224
- * resolve to the same `@tanstack/query-core` (no cross-bundle drift between
225
- * the consumer-side `@clerk/shared` and the production CDN `clerk-js` bundle).
226
- *
227
- * Lazily instantiated on the client only. Server-side renders return
228
- * `undefined` so per-request renders never share a cache across requests.
229
- */
230
- let clerkQueryClient;
231
- let initialized = false;
232
- function getClerkQueryClient() {
233
- if (typeof window === "undefined") return;
234
- if (!initialized) {
235
- clerkQueryClient = new _tanstack_query_core.QueryClient();
236
- initialized = true;
237
- }
238
- return clerkQueryClient;
239
- }
240
- /**
241
- * Test-only: install a custom client (for deterministic defaults like
242
- * `staleTime: Infinity`) or pass `undefined` to simulate the "no client"
243
- * state without triggering lazy creation on subsequent reads.
244
- */
245
- function __setClerkQueryClientForTest(client) {
246
- clerkQueryClient = client;
247
- initialized = true;
248
- }
249
- /**
250
- * Test-only: build and install a fresh `QueryClient` with deterministic
251
- * defaults (no retries, infinite stale time, no refetching). Returns the
252
- * client so the spec can read/write its cache directly.
253
- *
254
- * Avoids forcing every test consumer to depend on `@tanstack/query-core`.
255
- */
256
- function __createClerkTestQueryClient() {
257
- const client = new _tanstack_query_core.QueryClient({ defaultOptions: { queries: {
258
- retry: false,
259
- staleTime: Infinity,
260
- refetchOnWindowFocus: false,
261
- refetchOnReconnect: false,
262
- refetchOnMount: false
263
- } } });
264
- __setClerkQueryClientForTest(client);
265
- return client;
266
- }
267
- /**
268
- * Test-only: clear both the override and the initialization flag so the
269
- * next read lazy-creates a fresh client.
270
- */
271
- function __resetClerkQueryClientForTest() {
272
- clerkQueryClient = void 0;
273
- initialized = false;
274
- }
275
-
276
- //#endregion
277
- //#region src/react/query/use-clerk-query-client.ts
278
- /**
279
- * Creates a recursively self-referential Proxy that safely handles:
280
- * - Arbitrary property access (e.g., obj.any.prop.path)
281
- * - Function calls at any level (e.g., obj.a().b.c())
282
- * - Construction (e.g., new obj.a.b())
283
- *
284
- * Always returns itself to allow infinite chaining without throwing.
285
- */
286
- function createRecursiveProxy(label) {
287
- const callableTarget = function noop() {};
288
- let self;
289
- self = new Proxy(callableTarget, {
290
- get(_target, prop) {
291
- if (prop === "then") return;
292
- if (prop === "toString") return () => `[${label}]`;
293
- if (prop === Symbol.toPrimitive) return () => 0;
294
- return self;
295
- },
296
- apply() {
297
- return self;
298
- },
299
- construct() {
300
- return self;
301
- },
302
- has() {
303
- return false;
304
- },
305
- set() {
306
- return false;
307
- }
308
- });
309
- return self;
310
- }
311
- const mockQueryClient = createRecursiveProxy("ClerkMockQueryClient");
312
- /**
313
- * Returns `[client, isLoaded]`. The real client is owned by `@clerk/shared`
314
- * and lazily instantiated on the browser only — SSR returns the proxy mock
315
- * + `isLoaded: false` so per-request renders never share a query cache.
316
- */
317
- const useClerkQueryClient = () => {
318
- const client = getClerkQueryClient();
319
- return [client ?? mockQueryClient, Boolean(client)];
320
- };
321
-
322
- //#endregion
323
- //#region src/react/query/useBaseQuery.ts
324
- /**
325
- * Stripped down version of useBaseQuery from @tanstack/query-core.
326
- * This implementation allows for an observer to be created every time a query client changes.
327
- */
328
- /**
329
- * An alternative `useBaseQuery` implementation that allows for an observer to be created every time a query client changes.
330
- *
331
- * @internal
332
- */
333
- function useBaseQuery(options, Observer) {
334
- const [client, isQueryClientLoaded] = useClerkQueryClient();
335
- const defaultedOptions = isQueryClientLoaded ? client.defaultQueryOptions(options) : options;
336
- defaultedOptions._optimisticResults = "optimistic";
337
- const observer = react.useMemo(() => {
338
- return new Observer(client, defaultedOptions);
339
- }, [client]);
340
- const result = observer.getOptimisticResult(defaultedOptions);
341
- const shouldSubscribe = options.subscribed !== false;
342
- react.useSyncExternalStore(react.useCallback((onStoreChange) => {
343
- const unsubscribe = shouldSubscribe ? observer.subscribe(_tanstack_query_core.notifyManager.batchCalls(onStoreChange)) : _tanstack_query_core.noop;
344
- observer.updateResult();
345
- return unsubscribe;
346
- }, [observer, shouldSubscribe]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
347
- react.useEffect(() => {
348
- observer.setOptions(defaultedOptions);
349
- }, [defaultedOptions, observer]);
350
- if (!isQueryClientLoaded) return {
351
- data: void 0,
352
- error: null,
353
- isLoading: options.enabled !== false,
354
- isFetching: false,
355
- status: "pending"
356
- };
357
- return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result;
358
- }
359
-
360
- //#endregion
361
- //#region src/react/query/useInfiniteQuery.ts
362
- /**
363
- *
364
- */
365
- function useClerkInfiniteQuery(options) {
366
- return useBaseQuery(options, _tanstack_query_core.InfiniteQueryObserver);
367
- }
368
-
369
- //#endregion
370
- //#region src/react/query/useQuery.ts
371
- /**
372
- *
373
- */
374
- function useClerkQuery(options) {
375
- return useBaseQuery(options, _tanstack_query_core.QueryObserver);
376
- }
377
-
378
- //#endregion
379
- //#region src/react/hooks/usePreviousValue.ts
380
- /**
381
- * A hook that retains the previous value of a primitive type.
382
- * It uses a ref to prevent causing unnecessary re-renders.
383
- *
384
- * @internal
385
- *
386
- * @example
387
- * ```
388
- * Render 1: value = 'A' → returns null
389
- * Render 2: value = 'B' → returns 'A'
390
- * Render 3: value = 'B' → returns 'A'
391
- * Render 4: value = 'B' → returns 'A'
392
- * Render 5: value = 'C' → returns 'B'
393
- * ```
394
- */
395
- function usePreviousValue(value) {
396
- const currentRef = (0, react.useRef)(value);
397
- const previousRef = (0, react.useRef)(null);
398
- if (currentRef.current !== value) {
399
- previousRef.current = currentRef.current;
400
- currentRef.current = value;
401
- }
402
- return previousRef.current;
403
- }
404
-
405
- //#endregion
406
- //#region src/react/hooks/useClearQueriesOnSignOut.ts
407
- const withInfiniteKey = (key) => [key, `${key}-inf`];
408
- /**
409
- * Clears React Query caches associated with the given stable prefixes when
410
- * the authenticated state transitions from signed-in to signed-out.
411
- *
412
- * @internal
413
- */
414
- function useClearQueriesOnSignOut(options) {
415
- const { isSignedOut, stableKeys, authenticated = true, onCleanup } = options;
416
- const stableKeysRef = (0, react.useRef)(stableKeys);
417
- const [queryClient] = useClerkQueryClient();
418
- const previousIsSignedIn = usePreviousValue(!isSignedOut);
419
- (0, react.useEffect)(() => {
420
- if (authenticated !== true) return;
421
- if (previousIsSignedIn && isSignedOut === true) {
422
- queryClient.removeQueries({ predicate: (query) => {
423
- const [cachedStableKey, queryAuthenticated] = query.queryKey;
424
- return queryAuthenticated === true && typeof cachedStableKey === "string" && (Array.isArray(stableKeysRef.current) ? stableKeysRef.current.includes(cachedStableKey) : stableKeysRef.current === cachedStableKey);
425
- } });
426
- onCleanup?.();
427
- }
428
- }, [
429
- authenticated,
430
- isSignedOut,
431
- previousIsSignedIn,
432
- queryClient
433
- ]);
434
- }
435
-
436
- //#endregion
437
- //#region src/react/hooks/usePagesOrInfinite.shared.ts
438
- /**
439
- * A hook that safely merges user-provided pagination options with default values.
440
- * It caches initial pagination values (page and size) until component unmount to prevent unwanted rerenders.
441
- *
442
- * @internal
443
- *
444
- * @example
445
- * ```typescript
446
- * // Example 1: With user-provided options
447
- * const userOptions = { initialPage: 2, pageSize: 20, infinite: true };
448
- * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
449
- * useWithSafeValues(userOptions, defaults);
450
- * // Returns { initialPage: 2, pageSize: 20, infinite: true }
451
- *
452
- * // Example 2: With boolean true (use defaults)
453
- * const params = true;
454
- * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
455
- * useWithSafeValues(params, defaults);
456
- * // Returns { initialPage: 1, pageSize: 10, infinite: false }
457
- *
458
- * // Example 3: With undefined options (fallback to defaults)
459
- * const params = undefined;
460
- * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
461
- * useWithSafeValues(params, defaults);
462
- * // Returns { initialPage: 1, pageSize: 10, infinite: false }
463
- * ```
464
- */
465
- const useWithSafeValues = (params, defaultValues) => {
466
- const shouldUseDefaults = typeof params === "boolean" && params;
467
- const initialPageRef = (0, react.useRef)(shouldUseDefaults ? defaultValues.initialPage : params?.initialPage ?? defaultValues.initialPage);
468
- const pageSizeRef = (0, react.useRef)(shouldUseDefaults ? defaultValues.pageSize : params?.pageSize ?? defaultValues.pageSize);
469
- const newObj = {};
470
- for (const key of Object.keys(defaultValues)) newObj[key] = shouldUseDefaults ? defaultValues[key] : params?.[key] ?? defaultValues[key];
471
- return {
472
- ...newObj,
473
- initialPage: initialPageRef.current,
474
- pageSize: pageSizeRef.current
475
- };
476
- };
477
- /**
478
- * Calculates the offset count for pagination based on initial page and page size.
479
- * This represents the number of items to skip before the first page.
480
- *
481
- * @param initialPage - The starting page number (1-based)
482
- * @param pageSize - The number of items per page
483
- * @returns The number of items to offset
484
- *
485
- * @example
486
- * ```typescript
487
- * calculateOffsetCount(1, 10); // Returns 0 (no offset for first page)
488
- * calculateOffsetCount(2, 10); // Returns 10 (skip first 10 items)
489
- * calculateOffsetCount(3, 20); // Returns 40 (skip first 40 items)
490
- * ```
491
- */
492
- function calculateOffsetCount(initialPage, pageSize) {
493
- return (initialPage - 1) * pageSize;
494
- }
495
- /**
496
- * Calculates the total number of pages based on total count, offset, and page size.
497
- *
498
- * @param totalCount - The total number of items
499
- * @param offsetCount - The number of items to offset (from calculateOffsetCount)
500
- * @param pageSize - The number of items per page
501
- * @returns The total number of pages
502
- *
503
- * @example
504
- * ```typescript
505
- * calculatePageCount(100, 0, 10); // Returns 10
506
- * calculatePageCount(95, 0, 10); // Returns 10 (rounds up)
507
- * calculatePageCount(100, 20, 10); // Returns 8 (100 - 20 = 80 items, 8 pages)
508
- * ```
509
- */
510
- function calculatePageCount(totalCount, offsetCount, pageSize) {
511
- return Math.ceil((totalCount - offsetCount) / pageSize);
512
- }
513
- /**
514
- * Determines if there is a next page available in non-infinite pagination mode.
515
- *
516
- * @param totalCount - The total number of items
517
- * @param offsetCount - The number of items to offset
518
- * @param currentPage - The current page number (1-based)
519
- * @param pageSize - The number of items per page
520
- * @returns True if there are more items beyond the current page
521
- *
522
- * @example
523
- * ```typescript
524
- * calculateHasNextPage(100, 0, 1, 10); // Returns true (page 1 of 10)
525
- * calculateHasNextPage(100, 0, 10, 10); // Returns false (last page)
526
- * calculateHasNextPage(25, 0, 2, 10); // Returns true (page 2, 5 more items)
527
- * calculateHasNextPage(20, 0, 2, 10); // Returns false (exactly 2 pages)
528
- * ```
529
- */
530
- function calculateHasNextPage(totalCount, offsetCount, currentPage, pageSize) {
531
- return totalCount - offsetCount > currentPage * pageSize;
532
- }
533
- /**
534
- * Determines if there is a previous page available in non-infinite pagination mode.
535
- *
536
- * @param currentPage - The current page number (1-based)
537
- * @param pageSize - The number of items per page
538
- * @param offsetCount - The number of items to offset
539
- * @returns True if there are pages before the current page
540
- *
541
- * @example
542
- * ```typescript
543
- * calculateHasPreviousPage(1, 10, 0); // Returns false (first page)
544
- * calculateHasPreviousPage(2, 10, 0); // Returns true (can go back to page 1)
545
- * calculateHasPreviousPage(1, 10, 10); // Returns false (first page with offset)
546
- * ```
547
- */
548
- function calculateHasPreviousPage(currentPage, pageSize, offsetCount) {
549
- return (currentPage - 1) * pageSize > offsetCount;
550
- }
551
-
552
- //#endregion
553
- //#region src/react/hooks/usePagesOrInfinite.tsx
554
- const usePagesOrInfinite = (params) => {
555
- const { fetcher, config, keys } = params;
556
- const [paginatedPage, setPaginatedPage] = (0, react.useState)(config.initialPage ?? 1);
557
- const initialPageRef = (0, react.useRef)(config.initialPage ?? 1);
558
- const pageSizeRef = (0, react.useRef)(config.pageSize ?? 10);
559
- const enabled = config.enabled ?? true;
560
- const isSignedIn = config.isSignedIn;
561
- const triggerInfinite = config.infinite ?? false;
562
- const cacheMode = config.__experimental_mode === "cache";
563
- const keepPreviousData = config.keepPreviousData ?? false;
564
- const [queryClient] = useClerkQueryClient();
565
- const queriesEnabled = enabled && Boolean(fetcher) && !cacheMode && isSignedIn !== false;
566
- const [forceUpdateCounter, setForceUpdateCounter] = (0, react.useState)(0);
567
- const forceUpdate = (0, react.useCallback)((updater) => {
568
- setForceUpdateCounter(updater);
569
- }, []);
570
- const pagesQueryKey = (0, react.useMemo)(() => {
571
- const [stablePrefix, authenticated, tracked, untracked] = keys.queryKey;
572
- return [
573
- stablePrefix,
574
- authenticated,
575
- tracked,
576
- {
577
- ...untracked,
578
- args: {
579
- ...untracked.args,
580
- initialPage: paginatedPage,
581
- pageSize: pageSizeRef.current
582
- }
583
- }
584
- ];
585
- }, [keys.queryKey, paginatedPage]);
586
- const singlePageQuery = useClerkQuery({
587
- queryKey: pagesQueryKey,
588
- queryFn: ({ queryKey }) => {
589
- const { args } = queryKey[3];
590
- if (!fetcher) return;
591
- return fetcher(args);
592
- },
593
- staleTime: 6e4,
594
- enabled: queriesEnabled && !triggerInfinite,
595
- placeholderData: defineKeepPreviousDataFn(keepPreviousData)
596
- });
597
- const infiniteQueryKey = (0, react.useMemo)(() => {
598
- const [stablePrefix, authenticated, tracked, untracked] = keys.queryKey;
599
- return [
600
- stablePrefix + "-inf",
601
- authenticated,
602
- tracked,
603
- untracked
604
- ];
605
- }, [keys.queryKey]);
606
- const infiniteQuery = useClerkInfiniteQuery({
607
- queryKey: infiniteQueryKey,
608
- initialPageParam: config.initialPage ?? 1,
609
- getNextPageParam: (lastPage, allPages, lastPageParam) => {
610
- const total = lastPage?.total_count ?? 0;
611
- return (allPages.length + (config.initialPage ? config.initialPage - 1 : 0)) * (config.pageSize ?? 10) < total ? lastPageParam + 1 : void 0;
612
- },
613
- queryFn: ({ pageParam, queryKey }) => {
614
- const { args } = queryKey[3];
615
- if (!fetcher) return;
616
- return fetcher({
617
- ...args,
618
- initialPage: pageParam,
619
- pageSize: pageSizeRef.current
620
- });
621
- },
622
- staleTime: 6e4,
623
- enabled: queriesEnabled && triggerInfinite
624
- });
625
- useClearQueriesOnSignOut({
626
- isSignedOut: isSignedIn === false,
627
- authenticated: keys.authenticated,
628
- stableKeys: withInfiniteKey(keys.stableKey),
629
- onCleanup: () => {
630
- setPaginatedPage(initialPageRef.current);
631
- Promise.resolve().then(() => forceUpdate((n) => n + 1));
632
- }
633
- });
634
- const { data, count, page } = (0, react.useMemo)(() => {
635
- if (triggerInfinite) {
636
- const cachedData = queryClient.getQueryData(infiniteQueryKey);
637
- const pages = queriesEnabled ? infiniteQuery.data?.pages ?? cachedData?.pages ?? [] : cachedData?.pages ?? [];
638
- const validPages = Array.isArray(pages) ? pages.filter(Boolean) : [];
639
- return {
640
- data: validPages.map((a) => a?.data).flat().filter(Boolean) ?? [],
641
- count: validPages[validPages.length - 1]?.total_count ?? 0,
642
- page: validPages.length > 0 ? validPages.length : initialPageRef.current
643
- };
644
- }
645
- const pageData = queriesEnabled ? singlePageQuery.data ?? queryClient.getQueryData(pagesQueryKey) : queryClient.getQueryData(pagesQueryKey);
646
- return {
647
- data: Array.isArray(pageData?.data) ? pageData.data : [],
648
- count: typeof pageData?.total_count === "number" ? pageData.total_count : 0,
649
- page: paginatedPage
650
- };
651
- }, [
652
- queriesEnabled,
653
- forceUpdateCounter,
654
- triggerInfinite,
655
- infiniteQuery.data?.pages,
656
- singlePageQuery.data,
657
- queryClient,
658
- infiniteQueryKey,
659
- pagesQueryKey,
660
- paginatedPage
661
- ]);
662
- const fetchPage = (0, react.useCallback)((numberOrgFn) => {
663
- if (triggerInfinite) {
664
- const next = typeof numberOrgFn === "function" ? numberOrgFn(page) : numberOrgFn;
665
- const targetCount = Math.max(0, next);
666
- const cachedData = queryClient.getQueryData(infiniteQueryKey);
667
- if (targetCount - (infiniteQuery.data?.pages ?? cachedData?.pages ?? []).length > 0) infiniteQuery.fetchNextPage({ cancelRefetch: false });
668
- return;
669
- }
670
- return setPaginatedPage(numberOrgFn);
671
- }, [
672
- infiniteQuery,
673
- page,
674
- triggerInfinite,
675
- queryClient,
676
- infiniteQueryKey
677
- ]);
678
- const isLoading = triggerInfinite ? infiniteQuery.isLoading : singlePageQuery.isLoading;
679
- const isFetching = triggerInfinite ? infiniteQuery.isFetching : singlePageQuery.isFetching;
680
- const error = (triggerInfinite ? infiniteQuery.error : singlePageQuery.error) ?? null;
681
- const isError = !!error;
682
- const fetchNext = (0, react.useCallback)(() => {
683
- if (triggerInfinite) {
684
- infiniteQuery.fetchNextPage({ cancelRefetch: false });
685
- return;
686
- }
687
- setPaginatedPage((n) => Math.max(0, n + 1));
688
- }, [infiniteQuery, triggerInfinite]);
689
- const fetchPrevious = (0, react.useCallback)(() => {
690
- if (triggerInfinite) return;
691
- setPaginatedPage((n) => Math.max(0, n - 1));
692
- }, [triggerInfinite]);
693
- const offsetCount = calculateOffsetCount(initialPageRef.current, pageSizeRef.current);
694
- const pageCount = calculatePageCount(count, offsetCount, pageSizeRef.current);
695
- const hasNextPage = triggerInfinite ? Boolean(infiniteQuery.hasNextPage) : calculateHasNextPage(count, offsetCount, page, pageSizeRef.current);
696
- const hasPreviousPage = triggerInfinite ? Boolean(infiniteQuery.hasPreviousPage) : calculateHasPreviousPage(page, pageSizeRef.current, offsetCount);
697
- const setData = (value) => {
698
- if (triggerInfinite) {
699
- queryClient.setQueryData(infiniteQueryKey, (prevValue = {}) => {
700
- const prevPages = Array.isArray(prevValue?.pages) ? prevValue.pages : [];
701
- const nextPages = typeof value === "function" ? value(prevPages) : value;
702
- return {
703
- ...prevValue,
704
- pages: nextPages
705
- };
706
- });
707
- forceUpdate((n) => n + 1);
708
- return Promise.resolve();
709
- }
710
- queryClient.setQueryData(pagesQueryKey, (prevValue = {
711
- data: [],
712
- total_count: 0
713
- }) => {
714
- return typeof value === "function" ? value(prevValue) : value;
715
- });
716
- forceUpdate((n) => n + 1);
717
- return Promise.resolve();
718
- };
719
- const revalidate = async () => {
720
- await queryClient.invalidateQueries({ queryKey: keys.invalidationKey });
721
- const [stablePrefix, ...rest] = keys.invalidationKey;
722
- return queryClient.invalidateQueries({ queryKey: [stablePrefix + "-inf", ...rest] });
723
- };
724
- return {
725
- data,
726
- count,
727
- error,
728
- isLoading,
729
- isFetching,
730
- isError,
731
- page,
732
- pageCount,
733
- fetchPage,
734
- fetchNext,
735
- fetchPrevious,
736
- hasNextPage,
737
- hasPreviousPage,
738
- revalidate,
739
- setData
740
- };
741
- };
742
-
743
- //#endregion
744
- //#region src/react/hooks/useAPIKeys.tsx
745
- /**
746
- * The `useAPIKeys()` hook provides access to paginated API keys for the current user or organization.
747
- *
748
- * @example
749
- * ### Basic usage with default pagination
750
- *
751
- * ```tsx
752
- * const { data, isLoading, page, pageCount, fetchNext, fetchPrevious } = useAPIKeys({
753
- * subject: 'user_123',
754
- * pageSize: 10,
755
- * initialPage: 1,
756
- * });
757
- * ```
758
- *
759
- * @example
760
- * ### With search query
761
- *
762
- * ```tsx
763
- * const [searchValue, setSearchValue] = useState('');
764
- * const debouncedSearch = useDebounce(searchValue, 500);
765
- *
766
- * const { data, isLoading } = useAPIKeys({
767
- * subject: 'user_123',
768
- * query: debouncedSearch.trim(),
769
- * pageSize: 10,
770
- * });
771
- * ```
772
- *
773
- * @example
774
- * ### Infinite scroll
775
- *
776
- * ```tsx
777
- * const { data, isLoading, fetchNext, hasNextPage } = useAPIKeys({
778
- * subject: 'user_123',
779
- * infinite: true,
780
- * });
781
- * ```
782
- */
783
- function useAPIKeys(params) {
784
- useAssertWrappedByClerkProvider("useAPIKeys");
785
- const safeValues = useWithSafeValues(params, {
786
- initialPage: 1,
787
- pageSize: 10,
788
- keepPreviousData: false,
789
- infinite: false,
790
- subject: "",
791
- query: "",
792
- enabled: true
793
- });
794
- const clerk = useClerkInstanceContext();
795
- clerk.telemetry?.record(require_telemetry.eventMethodCalled("useAPIKeys"));
796
- const hookParams = {
797
- initialPage: safeValues.initialPage,
798
- pageSize: safeValues.pageSize,
799
- ...safeValues.subject ? { subject: safeValues.subject } : {},
800
- ...safeValues.query ? { query: safeValues.query } : {}
801
- };
802
- const isEnabled = (safeValues.enabled ?? true) && clerk.loaded;
803
- return usePagesOrInfinite({
804
- fetcher: clerk.apiKeys?.getAll ? (params) => clerk.apiKeys.getAll({
805
- ...params,
806
- subject: safeValues.subject
807
- }) : void 0,
808
- config: {
809
- keepPreviousData: safeValues.keepPreviousData,
810
- infinite: safeValues.infinite,
811
- enabled: isEnabled,
812
- isSignedIn: clerk.user !== null,
813
- initialPage: safeValues.initialPage,
814
- pageSize: safeValues.pageSize
815
- },
816
- keys: createCacheKeys({
817
- stablePrefix: STABLE_KEYS.API_KEYS_KEY,
818
- authenticated: true,
819
- tracked: { subject: safeValues.subject },
820
- untracked: { args: hookParams }
821
- })
822
- });
823
- }
824
-
825
- //#endregion
826
- //#region src/react/hooks/base/useUserBase.ts
827
- function useUserBase() {
828
- const clerk = useClerkInstanceContext();
829
- const initialState = useInitialStateContext();
830
- const getInitialState = (0, react.useCallback)(() => initialState?.user, [initialState?.user]);
831
- return (0, react.useSyncExternalStore)((0, react.useCallback)((callback) => {
832
- return clerk.addListener(callback, { skipInitialEmit: true });
833
- }, [clerk]), (0, react.useCallback)(() => {
834
- if (!clerk.loaded || !clerk.__internal_lastEmittedResources) return getInitialState();
835
- return clerk.__internal_lastEmittedResources.user;
836
- }, [clerk, getInitialState]), getInitialState);
837
- }
838
-
839
- //#endregion
840
- //#region src/react/hooks/useOAuthConsent.shared.ts
841
- function useOAuthConsentCacheKeys(params) {
842
- const { userId, oauthClientId, scope, redirectUri } = params;
843
- return (0, react.useMemo)(() => {
844
- const args = {
845
- oauthClientId,
846
- ...scope !== void 0 && { scope },
847
- ...redirectUri !== void 0 && { redirectUri }
848
- };
849
- return createCacheKeys({
850
- stablePrefix: STABLE_KEYS.OAUTH_CONSENT_INFO_KEY,
851
- authenticated: true,
852
- tracked: { userId: userId ?? null },
853
- untracked: { args }
854
- });
855
- }, [
856
- userId,
857
- oauthClientId,
858
- scope,
859
- redirectUri
860
- ]);
861
- }
862
-
863
- //#endregion
864
- //#region src/react/hooks/useOAuthConsent.tsx
865
- const HOOK_NAME$5 = "useOAuthConsent";
866
- /**
867
- * The `useOAuthConsent()` hook loads OAuth application consent metadata for the **signed-in** user
868
- * (`GET /me/oauth/consent/{oauthClientId}`). Ensure the user is authenticated before relying on this hook
869
- * (e.g., redirect to sign-in on your custom consent route).
870
- *
871
- * @example
872
- * ```tsx
873
- * import { useOAuthConsent } from '@clerk/react/internal'
874
- *
875
- * const { data, isLoading, error } = useOAuthConsent({
876
- * oauthClientId: clientIdFromProps,
877
- * scope: scopeFromProps,
878
- * })
879
- * ```
880
- */
881
- function useOAuthConsent(params) {
882
- useAssertWrappedByClerkProvider(HOOK_NAME$5);
883
- const { oauthClientId: oauthClientIdParam, scope, redirectUri, keepPreviousData = true, enabled = true } = params;
884
- const clerk = useClerkInstanceContext();
885
- const user = useUserBase();
886
- const oauthClientId = (oauthClientIdParam ?? "").trim();
887
- clerk.telemetry?.record(require_telemetry.eventMethodCalled(HOOK_NAME$5));
888
- const { queryKey } = useOAuthConsentCacheKeys({
889
- userId: user?.id ?? null,
890
- oauthClientId,
891
- scope,
892
- redirectUri
893
- });
894
- const hasClientId = oauthClientId.length > 0;
895
- const queryEnabled = Boolean(user) && hasClientId && enabled && clerk.loaded;
896
- const query = useClerkQuery({
897
- queryKey,
898
- queryFn: () => fetchConsentInfo(clerk, {
899
- oauthClientId,
900
- scope,
901
- redirectUri
902
- }),
903
- enabled: queryEnabled,
904
- placeholderData: defineKeepPreviousDataFn(keepPreviousData && queryEnabled)
905
- });
906
- return {
907
- data: query.data,
908
- error: query.error ?? null,
909
- isLoading: query.isLoading,
910
- isFetching: query.isFetching
911
- };
912
- }
913
- function fetchConsentInfo(clerk, params) {
914
- return clerk.oauthApplication.getConsentInfo(params);
915
- }
916
-
917
- //#endregion
918
- //#region src/react/hooks/useOAuthDeviceVerification.tsx
919
- const HOOK_NAME$4 = "useOAuthDeviceVerification";
920
- const normalizeUserCode = (userCode) => userCode.toUpperCase().replace(/[-\p{White_Space}]/gu, "");
921
- const createNotReadyError = () => new require_clerkRuntimeError.ClerkRuntimeError("Clerk must be loaded before using OAuth device verification.", { code: "oauth_device_verification_not_ready" });
922
- const createLookupInProgressError = () => new require_clerkRuntimeError.ClerkRuntimeError("An OAuth device verification lookup is already in progress for another code.", { code: "oauth_device_verification_lookup_in_progress" });
923
- const createSubmissionInProgressError = () => new require_clerkRuntimeError.ClerkRuntimeError("Another OAuth device verification decision is already in progress.", { code: "oauth_device_verification_submission_in_progress" });
924
- /**
925
- * Provides state and actions for building a custom OAuth device verification flow.
926
- *
927
- * @returns The current verification state and methods for looking up, approving, denying, or resetting a request.
928
- *
929
- * @example
930
- * ### Look up a device authorization request
931
- *
932
- * ```tsx
933
- * import { useOAuthDeviceVerification } from '@clerk/react';
934
- *
935
- * function CustomDeviceVerification({ userCode }: { userCode: string }) {
936
- * const { data, isLoading, lookup } = useOAuthDeviceVerification();
937
- *
938
- * const handleLookup = async () => {
939
- * await lookup({ userCode });
940
- * };
941
- *
942
- * return (
943
- * <>
944
- * <button disabled={isLoading} onClick={handleLookup}>Verify code</button>
945
- * {data && <p>Authorize {data.oauthApplicationName}?</p>}
946
- * </>
947
- * );
948
- * }
949
- * ```
950
- */
951
- function useOAuthDeviceVerification() {
952
- useAssertWrappedByClerkProvider(HOOK_NAME$4);
953
- const clerk = useClerkInstanceContext();
954
- const [data, setData] = (0, react.useState)();
955
- const [result, setResult] = (0, react.useState)();
956
- const [error, setError] = (0, react.useState)(null);
957
- const [isLoading, setIsLoading] = (0, react.useState)(false);
958
- const [isSubmitting, setIsSubmitting] = (0, react.useState)(false);
959
- const pendingLookup = (0, react.useRef)(null);
960
- const pendingSubmit = (0, react.useRef)(null);
961
- const generation = (0, react.useRef)(0);
962
- clerk.telemetry?.record(require_telemetry.eventMethodCalled(HOOK_NAME$4));
963
- const lookup = (0, react.useCallback)((params) => {
964
- const oauthApplication = clerk.loaded ? clerk.oauthApplication : void 0;
965
- if (!oauthApplication) return Promise.reject(createNotReadyError());
966
- const key = normalizeUserCode(params.userCode);
967
- if (pendingLookup.current) {
968
- if (pendingLookup.current.key === key) return pendingLookup.current.promise;
969
- return Promise.reject(createLookupInProgressError());
970
- }
971
- const requestGeneration = generation.current;
972
- setError(null);
973
- setData(void 0);
974
- setResult(void 0);
975
- setIsLoading(true);
976
- const request = oauthApplication.lookupDeviceVerification({
977
- ...params,
978
- userCode: key
979
- }).then((info) => {
980
- if (generation.current === requestGeneration) setData(info);
981
- return info;
982
- }).catch((err) => {
983
- if (generation.current === requestGeneration) setError(err);
984
- throw err;
985
- }).finally(() => {
986
- if (pendingLookup.current?.promise === request) pendingLookup.current = null;
987
- if (generation.current === requestGeneration) setIsLoading(false);
988
- });
989
- pendingLookup.current = {
990
- key,
991
- promise: request
992
- };
993
- return request;
994
- }, [clerk]);
995
- const submit = (0, react.useCallback)((params, approved) => {
996
- const oauthApplication = clerk.loaded ? clerk.oauthApplication : void 0;
997
- if (!oauthApplication) return Promise.reject(createNotReadyError());
998
- const userCode = normalizeUserCode(params.userCode);
999
- const key = JSON.stringify([
1000
- userCode,
1001
- params.organizationId ?? null,
1002
- approved
1003
- ]);
1004
- if (pendingSubmit.current) {
1005
- if (pendingSubmit.current.key === key) return pendingSubmit.current.promise;
1006
- return Promise.reject(createSubmissionInProgressError());
1007
- }
1008
- const requestGeneration = generation.current;
1009
- setError(null);
1010
- setIsSubmitting(true);
1011
- const request = oauthApplication.submitDeviceVerification({
1012
- ...params,
1013
- userCode,
1014
- approved
1015
- }).then((decision) => {
1016
- if (generation.current === requestGeneration) setResult(decision);
1017
- return decision;
1018
- }).catch((err) => {
1019
- if (generation.current === requestGeneration) setError(err);
1020
- throw err;
1021
- }).finally(() => {
1022
- if (pendingSubmit.current?.promise === request) pendingSubmit.current = null;
1023
- if (generation.current === requestGeneration) setIsSubmitting(false);
1024
- });
1025
- pendingSubmit.current = {
1026
- key,
1027
- promise: request
1028
- };
1029
- return request;
1030
- }, [clerk]);
1031
- return {
1032
- data,
1033
- result,
1034
- error,
1035
- isLoading,
1036
- isSubmitting,
1037
- lookup,
1038
- approve: (0, react.useCallback)((params) => submit(params, true), [submit]),
1039
- deny: (0, react.useCallback)((params) => submit(params, false), [submit]),
1040
- reset: (0, react.useCallback)(() => {
1041
- generation.current += 1;
1042
- pendingLookup.current = null;
1043
- setData(void 0);
1044
- setResult(void 0);
1045
- setError(null);
1046
- setIsLoading(false);
1047
- setIsSubmitting(false);
1048
- }, [])
1049
- };
1050
- }
1051
-
1052
- //#endregion
1053
- //#region src/react/hooks/base/useOrganizationBase.ts
1054
- function useOrganizationBase() {
1055
- const clerk = useClerkInstanceContext();
1056
- const initialState = useInitialStateContext();
1057
- const getInitialState = (0, react.useCallback)(() => initialState?.organization, [initialState?.organization]);
1058
- return (0, react.useSyncExternalStore)((0, react.useCallback)((callback) => clerk.addListener(callback, { skipInitialEmit: true }), [clerk]), (0, react.useCallback)(() => {
1059
- if (!clerk.loaded || !clerk.__internal_lastEmittedResources) return getInitialState();
1060
- return clerk.__internal_lastEmittedResources.organization;
1061
- }, [clerk, getInitialState]), getInitialState);
1062
- }
1063
-
1064
- //#endregion
1065
- //#region src/react/hooks/base/useSessionBase.ts
1066
- function useSessionBase() {
1067
- const clerk = useClerkInstanceContext();
1068
- const initialState = useInitialStateContext();
1069
- const getInitialState = (0, react.useCallback)(() => {
1070
- return initialState ? require_deriveState.deriveFromSsrInitialState(initialState)?.session : void 0;
1071
- }, [initialState]);
1072
- return (0, react.useSyncExternalStore)((0, react.useCallback)((callback) => clerk.addListener(callback, { skipInitialEmit: true }), [clerk]), (0, react.useCallback)(() => {
1073
- if (!clerk.loaded || !clerk.__internal_lastEmittedResources) return getInitialState();
1074
- return clerk.__internal_lastEmittedResources.session;
1075
- }, [clerk, getInitialState]), getInitialState);
1076
- }
1077
-
1078
- //#endregion
1079
- //#region src/react/hooks/useClerk.ts
1080
- /**
1081
- * > [!WARNING]
1082
- * > This hook should only be used for advanced use cases, such as building a completely custom OAuth flow or as an escape hatch to access to the `Clerk` object.
1083
- *
1084
- * The `useClerk()` hook provides access to the [`Clerk`](https://clerk.com/docs/reference/objects/clerk) object, allowing you to build alternatives to any Clerk Component.
1085
- *
1086
- * @function
1087
- *
1088
- * @returns The `useClerk()` hook returns the `Clerk` object, which includes all the methods and properties listed in the [`Clerk` reference](https://clerk.com/docs/reference/objects/clerk).
1089
- *
1090
- * @example
1091
- *
1092
- * The following example uses the `useClerk()` hook to access the `clerk` object. The `clerk` object is used to call the [`openSignIn()`](https://clerk.com/docs/reference/objects/clerk#opensignin) method to open the sign-in modal.
1093
- *
1094
- * <Tabs items='React,Next.js'>
1095
- * <Tab>
1096
- *
1097
- * ```tsx {{ filename: 'src/Home.tsx' }}
1098
- * import { useClerk } from '@clerk/react'
1099
- *
1100
- * export default function Home() {
1101
- * const clerk = useClerk()
1102
- *
1103
- * return <button onClick={() => clerk.openSignIn({})}>Sign in</button>
1104
- * }
1105
- * ```
1106
- *
1107
- * </Tab>
1108
- * <Tab>
1109
- *
1110
- * ```tsx {{ filename: 'app/page.tsx' }}
1111
- * 'use client';
1112
- *
1113
- * import { useClerk } from '@clerk/nextjs';
1114
- *
1115
- * export default function HomePage() {
1116
- * const clerk = useClerk();
1117
- *
1118
- * return <button onClick={() => clerk.openSignIn({})}>Sign in</button>;
1119
- * }
1120
- * ```
1121
- *
1122
- * </Tab>
1123
- * </Tabs>
1124
- */
1125
- const useClerk = () => {
1126
- useAssertWrappedByClerkProvider("useClerk");
1127
- return useClerkInstanceContext();
1128
- };
1129
-
1130
- //#endregion
1131
- //#region src/react/hooks/useAttemptToEnableOrganizations.ts
1132
- /**
1133
- * Attempts to enable the organizations environment setting for a given caller
1134
- *
1135
- * @internal
1136
- */
1137
- function useAttemptToEnableOrganizations(caller, { enabled = true } = {}) {
1138
- const clerk = useClerk();
1139
- const hasAttempted = (0, react.useRef)(false);
1140
- (0, react.useEffect)(() => {
1141
- if (!enabled || hasAttempted.current) return;
1142
- hasAttempted.current = true;
1143
- clerk.__internal_attemptToEnableEnvironmentSetting?.({
1144
- for: "organizations",
1145
- caller
1146
- });
1147
- }, [
1148
- clerk,
1149
- caller,
1150
- enabled
1151
- ]);
1152
- }
1153
-
1154
- //#endregion
1155
- //#region src/react/hooks/useOrganization.tsx
1156
- const undefinedPaginatedResource$1 = {
1157
- data: void 0,
1158
- count: void 0,
1159
- error: void 0,
1160
- isLoading: false,
1161
- isFetching: false,
1162
- isError: false,
1163
- page: void 0,
1164
- pageCount: void 0,
1165
- fetchPage: void 0,
1166
- fetchNext: void 0,
1167
- fetchPrevious: void 0,
1168
- hasNextPage: false,
1169
- hasPreviousPage: false,
1170
- revalidate: void 0,
1171
- setData: void 0
1172
- };
1173
- /**
1174
- * The `useOrganization()` hook retrieves attributes of the currently Active Organization.
1175
- *
1176
- * @example
1177
- * ### Expand and paginate attributes
1178
- *
1179
- * To keep network usage to a minimum, developers are required to opt-in by specifying which resource they need to fetch and paginate through. By default, the `memberships`, `invitations`, `membershipRequests`, and `domains` attributes are not populated. You must pass `true` or an object with the desired properties to fetch and paginate the data.
1180
- *
1181
- * ```tsx
1182
- * // invitations.data will never be populated.
1183
- * const { invitations } = useOrganization()
1184
- *
1185
- * // Use default values to fetch invitations, such as initialPage = 1 and pageSize = 10
1186
- * const { invitations } = useOrganization({
1187
- * invitations: true,
1188
- * })
1189
- *
1190
- * // Pass your own values to fetch invitations
1191
- * const { invitations } = useOrganization({
1192
- * invitations: {
1193
- * pageSize: 20,
1194
- * initialPage: 2, // skips the first page
1195
- * },
1196
- * })
1197
- *
1198
- * // Aggregate pages in order to render an infinite list
1199
- * const { invitations } = useOrganization({
1200
- * invitations: {
1201
- * infinite: true,
1202
- * },
1203
- * })
1204
- * ```
1205
- *
1206
- * @example
1207
- * ### Infinite pagination
1208
- *
1209
- * The following example demonstrates how to use the `infinite` property to fetch and append new data to the existing list. The `memberships` attribute will be populated with the first page of the Organization's memberships. When the "Load more" button is clicked, the `fetchNext` helper function will be called to append the next page of memberships to the list.
1210
- *
1211
- * ```tsx
1212
- * import { useOrganization } from '@clerk/react'
1213
- *
1214
- * export default function MemberList() {
1215
- * const { memberships } = useOrganization({
1216
- * memberships: {
1217
- * infinite: true, // Append new data to the existing list
1218
- * keepPreviousData: true, // Persist the cached data until the new data has been fetched
1219
- * },
1220
- * })
1221
- *
1222
- * if (!memberships) {
1223
- * // Handle loading state
1224
- * return null
1225
- * }
1226
- *
1227
- * return (
1228
- * <div>
1229
- * <h2>Organization members</h2>
1230
- * <ul>
1231
- * {memberships.data?.map((membership) => (
1232
- * <li key={membership.id}>
1233
- * {membership.publicUserData.firstName} {membership.publicUserData.lastName} <
1234
- * {membership.publicUserData.identifier}> :: {membership.role}
1235
- * </li>
1236
- * ))}
1237
- * </ul>
1238
- *
1239
- * <button
1240
- * disabled={!memberships.hasNextPage} // Disable the button if there are no more available pages to be fetched
1241
- * onClick={memberships.fetchNext}
1242
- * >
1243
- * Load more
1244
- * </button>
1245
- * </div>
1246
- * )
1247
- * }
1248
- * ```
1249
- *
1250
- * @example
1251
- * ### Simple pagination
1252
- *
1253
- * The following example demonstrates how to use the `fetchPrevious` and `fetchNext` helper functions to paginate through the data. The `memberships` attribute will be populated with the first page of the Organization's memberships. When the "Previous page" or "Next page" button is clicked, the `fetchPrevious` or `fetchNext` helper function will be called to fetch the previous or next page of memberships.
1254
- *
1255
- * Notice the difference between this example's pagination and the infinite pagination example above.
1256
- *
1257
- * ```tsx
1258
- * import { useOrganization } from '@clerk/react'
1259
- *
1260
- * export default function MemberList() {
1261
- * const { memberships } = useOrganization({
1262
- * memberships: {
1263
- * keepPreviousData: true, // Persist the cached data until the new data has been fetched
1264
- * },
1265
- * })
1266
- *
1267
- * if (!memberships) {
1268
- * // Handle loading state
1269
- * return null
1270
- * }
1271
- *
1272
- * return (
1273
- * <div>
1274
- * <h2>Organization members</h2>
1275
- * <ul>
1276
- * {memberships.data?.map((membership) => (
1277
- * <li key={membership.id}>
1278
- * {membership.publicUserData.firstName} {membership.publicUserData.lastName} <
1279
- * {membership.publicUserData.identifier}> :: {membership.role}
1280
- * </li>
1281
- * ))}
1282
- * </ul>
1283
- *
1284
- * <button disabled={!memberships.hasPreviousPage} onClick={memberships.fetchPrevious}>
1285
- * Previous page
1286
- * </button>
1287
- *
1288
- * <button disabled={!memberships.hasNextPage} onClick={memberships.fetchNext}>
1289
- * Next page
1290
- * </button>
1291
- * </div>
1292
- * )
1293
- * }
1294
- * ```
1295
- */
1296
- function useOrganization(params) {
1297
- const { domains: domainListParams, membershipRequests: membershipRequestsListParams, memberships: membersListParams, invitations: invitationsListParams, __internal_skipAttemptToEnableOrganizations } = params || {};
1298
- useAssertWrappedByClerkProvider("useOrganization");
1299
- useAttemptToEnableOrganizations("useOrganization", { enabled: !__internal_skipAttemptToEnableOrganizations });
1300
- const organization = useOrganizationBase();
1301
- const session = useSessionBase();
1302
- const domainSafeValues = useWithSafeValues(domainListParams, {
1303
- initialPage: 1,
1304
- pageSize: 10,
1305
- keepPreviousData: false,
1306
- infinite: false,
1307
- enrollmentMode: void 0
1308
- });
1309
- const membershipRequestSafeValues = useWithSafeValues(membershipRequestsListParams, {
1310
- initialPage: 1,
1311
- pageSize: 10,
1312
- status: "pending",
1313
- keepPreviousData: false,
1314
- infinite: false
1315
- });
1316
- const membersSafeValues = useWithSafeValues(membersListParams, {
1317
- initialPage: 1,
1318
- pageSize: 10,
1319
- role: void 0,
1320
- keepPreviousData: false,
1321
- infinite: false,
1322
- query: void 0
1323
- });
1324
- const invitationsSafeValues = useWithSafeValues(invitationsListParams, {
1325
- initialPage: 1,
1326
- pageSize: 10,
1327
- status: ["pending"],
1328
- keepPreviousData: false,
1329
- infinite: false
1330
- });
1331
- const clerk = useClerkInstanceContext();
1332
- clerk.telemetry?.record(require_telemetry.eventMethodCalled("useOrganization"));
1333
- const domainParams = typeof domainListParams === "undefined" ? void 0 : {
1334
- initialPage: domainSafeValues.initialPage,
1335
- pageSize: domainSafeValues.pageSize,
1336
- enrollmentMode: domainSafeValues.enrollmentMode
1337
- };
1338
- const membershipRequestParams = typeof membershipRequestsListParams === "undefined" ? void 0 : {
1339
- initialPage: membershipRequestSafeValues.initialPage,
1340
- pageSize: membershipRequestSafeValues.pageSize,
1341
- status: membershipRequestSafeValues.status
1342
- };
1343
- const membersParams = typeof membersListParams === "undefined" ? void 0 : {
1344
- initialPage: membersSafeValues.initialPage,
1345
- pageSize: membersSafeValues.pageSize,
1346
- role: membersSafeValues.role,
1347
- query: membersSafeValues.query
1348
- };
1349
- const invitationsParams = typeof invitationsListParams === "undefined" ? void 0 : {
1350
- initialPage: invitationsSafeValues.initialPage,
1351
- pageSize: invitationsSafeValues.pageSize,
1352
- status: invitationsSafeValues.status
1353
- };
1354
- const domains = usePagesOrInfinite({
1355
- fetcher: organization?.getDomains,
1356
- config: {
1357
- keepPreviousData: domainSafeValues.keepPreviousData,
1358
- infinite: domainSafeValues.infinite,
1359
- enabled: !!domainParams,
1360
- isSignedIn: organization !== null,
1361
- initialPage: domainSafeValues.initialPage,
1362
- pageSize: domainSafeValues.pageSize
1363
- },
1364
- keys: createCacheKeys({
1365
- stablePrefix: STABLE_KEYS.DOMAINS_KEY,
1366
- authenticated: true,
1367
- tracked: { organizationId: organization?.id },
1368
- untracked: { args: domainParams }
1369
- })
1370
- });
1371
- const membershipRequests = usePagesOrInfinite({
1372
- fetcher: organization?.getMembershipRequests,
1373
- config: {
1374
- keepPreviousData: membershipRequestSafeValues.keepPreviousData,
1375
- infinite: membershipRequestSafeValues.infinite,
1376
- enabled: !!membershipRequestParams,
1377
- isSignedIn: organization !== null,
1378
- initialPage: membershipRequestSafeValues.initialPage,
1379
- pageSize: membershipRequestSafeValues.pageSize
1380
- },
1381
- keys: createCacheKeys({
1382
- stablePrefix: STABLE_KEYS.MEMBERSHIP_REQUESTS_KEY,
1383
- authenticated: true,
1384
- tracked: { organizationId: organization?.id },
1385
- untracked: { args: membershipRequestParams }
1386
- })
1387
- });
1388
- const memberships = usePagesOrInfinite({
1389
- fetcher: organization?.getMemberships,
1390
- config: {
1391
- keepPreviousData: membersSafeValues.keepPreviousData,
1392
- infinite: membersSafeValues.infinite,
1393
- enabled: !!membersParams,
1394
- isSignedIn: organization !== null,
1395
- initialPage: membersSafeValues.initialPage,
1396
- pageSize: membersSafeValues.pageSize
1397
- },
1398
- keys: createCacheKeys({
1399
- stablePrefix: STABLE_KEYS.MEMBERSHIPS_KEY,
1400
- authenticated: true,
1401
- tracked: { organizationId: organization?.id },
1402
- untracked: { args: membersParams }
1403
- })
1404
- });
1405
- const invitations = usePagesOrInfinite({
1406
- fetcher: organization?.getInvitations,
1407
- config: {
1408
- keepPreviousData: invitationsSafeValues.keepPreviousData,
1409
- infinite: invitationsSafeValues.infinite,
1410
- enabled: !!invitationsParams,
1411
- isSignedIn: organization !== null,
1412
- initialPage: invitationsSafeValues.initialPage,
1413
- pageSize: invitationsSafeValues.pageSize
1414
- },
1415
- keys: createCacheKeys({
1416
- stablePrefix: STABLE_KEYS.INVITATIONS_KEY,
1417
- authenticated: true,
1418
- tracked: { organizationId: organization?.id },
1419
- untracked: { args: invitationsParams }
1420
- })
1421
- });
1422
- if (organization === void 0) return {
1423
- isLoaded: false,
1424
- organization: void 0,
1425
- membership: void 0,
1426
- domains: undefinedPaginatedResource$1,
1427
- membershipRequests: undefinedPaginatedResource$1,
1428
- memberships: undefinedPaginatedResource$1,
1429
- invitations: undefinedPaginatedResource$1
1430
- };
1431
- if (organization === null) return {
1432
- isLoaded: true,
1433
- organization: null,
1434
- membership: null,
1435
- domains: null,
1436
- membershipRequests: null,
1437
- memberships: null,
1438
- invitations: null
1439
- };
1440
- /** In SSR context we include only the organization object when loadOrg is set to true. */
1441
- if (!clerk.loaded && organization) return {
1442
- isLoaded: true,
1443
- organization,
1444
- membership: void 0,
1445
- domains: undefinedPaginatedResource$1,
1446
- membershipRequests: undefinedPaginatedResource$1,
1447
- memberships: undefinedPaginatedResource$1,
1448
- invitations: undefinedPaginatedResource$1
1449
- };
1450
- return {
1451
- isLoaded: clerk.loaded,
1452
- organization,
1453
- membership: require_organization.getCurrentOrganizationMembership(session.user.organizationMemberships, organization.id),
1454
- domains,
1455
- membershipRequests,
1456
- memberships,
1457
- invitations
1458
- };
1459
- }
1460
-
1461
- //#endregion
1462
- //#region src/react/hooks/useOrganizationCreationDefaults.shared.ts
1463
- function useOrganizationCreationDefaultsCacheKeys(params) {
1464
- const { userId } = params;
1465
- return (0, react.useMemo)(() => {
1466
- return createCacheKeys({
1467
- stablePrefix: STABLE_KEYS.ORGANIZATION_CREATION_DEFAULTS_KEY,
1468
- authenticated: Boolean(userId),
1469
- tracked: { userId: userId ?? null },
1470
- untracked: { args: {} }
1471
- });
1472
- }, [userId]);
1473
- }
1474
-
1475
- //#endregion
1476
- //#region src/react/hooks/useOrganizationCreationDefaults.tsx
1477
- const HOOK_NAME$3 = "useOrganizationCreationDefaults";
1478
- /**
1479
- * The `useOrganizationCreationDefaults()` hook retrieves the organization creation defaults for the current user.
1480
- *
1481
- * @example
1482
- * ### Basic usage
1483
- *
1484
- * ```tsx
1485
- * import { useOrganizationCreationDefaults } from '@clerk/clerk-react'
1486
- *
1487
- * export default function CreateOrganizationForm() {
1488
- * const { data, isLoading } = useOrganizationCreationDefaults()
1489
- *
1490
- * if (isLoading) return <div>Loading...</div>
1491
- *
1492
- * return (
1493
- * <form>
1494
- * <input defaultValue={data?.form.name} placeholder="Organization name" />
1495
- * <input defaultValue={data?.form.slug} placeholder="Slug" />
1496
- * <button type="submit">Create</button>
1497
- * </form>
1498
- * )
1499
- * }
1500
- * ```
1501
- */
1502
- function useOrganizationCreationDefaults(params = {}) {
1503
- useAssertWrappedByClerkProvider(HOOK_NAME$3);
1504
- const { keepPreviousData = true, enabled = true } = params;
1505
- const clerk = useClerkInstanceContext();
1506
- const user = useUserBase();
1507
- const featureEnabled = clerk.__internal_environment?.organizationSettings?.organizationCreationDefaults?.enabled ?? false;
1508
- clerk.telemetry?.record(require_telemetry.eventMethodCalled(HOOK_NAME$3));
1509
- const { queryKey } = useOrganizationCreationDefaultsCacheKeys({ userId: user?.id ?? null });
1510
- const queryEnabled = Boolean(user) && enabled && featureEnabled && clerk.loaded;
1511
- const query = useClerkQuery({
1512
- queryKey,
1513
- queryFn: user?.getOrganizationCreationDefaults,
1514
- enabled: queryEnabled,
1515
- placeholderData: defineKeepPreviousDataFn(keepPreviousData)
1516
- });
1517
- return {
1518
- data: query.data,
1519
- error: query.error ?? null,
1520
- isLoading: query.isLoading,
1521
- isFetching: query.isFetching
1522
- };
1523
- }
1524
-
1525
- //#endregion
1526
- //#region src/react/hooks/useOrganizationList.tsx
1527
- const undefinedPaginatedResource = {
1528
- data: void 0,
1529
- count: void 0,
1530
- error: void 0,
1531
- isLoading: false,
1532
- isFetching: false,
1533
- isError: false,
1534
- page: void 0,
1535
- pageCount: void 0,
1536
- fetchPage: void 0,
1537
- fetchNext: void 0,
1538
- fetchPrevious: void 0,
1539
- hasNextPage: false,
1540
- hasPreviousPage: false,
1541
- revalidate: void 0,
1542
- setData: void 0
1543
- };
1544
- /**
1545
- * The `useOrganizationList()` hook provides access to the current user's organization memberships, invitations, and suggestions. It also includes methods for creating new organizations and managing the active organization.
1546
- *
1547
- * @example
1548
- * ### Expanding and paginating attributes
1549
- *
1550
- * To keep network usage to a minimum, developers are required to opt-in by specifying which resource they need to fetch and paginate through. So by default, the `userMemberships`, `userInvitations`, and `userSuggestions` attributes are not populated. You must pass true or an object with the desired properties to fetch and paginate the data.
1551
- *
1552
- * ```tsx
1553
- * // userMemberships.data will never be populated
1554
- * const { userMemberships } = useOrganizationList()
1555
- *
1556
- * // Use default values to fetch userMemberships, such as initialPage = 1 and pageSize = 10
1557
- * const { userMemberships } = useOrganizationList({
1558
- * userMemberships: true,
1559
- * })
1560
- *
1561
- * // Pass your own values to fetch userMemberships
1562
- * const { userMemberships } = useOrganizationList({
1563
- * userMemberships: {
1564
- * pageSize: 20,
1565
- * initialPage: 2, // skips the first page
1566
- * },
1567
- * })
1568
- *
1569
- * // Aggregate pages in order to render an infinite list
1570
- * const { userMemberships } = useOrganizationList({
1571
- * userMemberships: {
1572
- * infinite: true,
1573
- * },
1574
- * })
1575
- * ```
1576
- *
1577
- * @example
1578
- * ### Infinite pagination
1579
- *
1580
- * The following example demonstrates how to use the `infinite` property to fetch and append new data to the existing list. The `userMemberships` attribute will be populated with the first page of the user's Organization memberships. When the "Load more" button is clicked, the `fetchNext` helper function will be called to append the next page of memberships to the list.
1581
- *
1582
- * ```tsx {{ filename: 'src/components/JoinedOrganizations.tsx' }}
1583
- * import { useOrganizationList } from '@clerk/react'
1584
- * import React from 'react'
1585
- *
1586
- * const JoinedOrganizations = () => {
1587
- * const { isLoaded, setActive, userMemberships } = useOrganizationList({
1588
- * userMemberships: {
1589
- * infinite: true,
1590
- * },
1591
- * })
1592
- *
1593
- * if (!isLoaded) {
1594
- * return <>Loading</>
1595
- * }
1596
- *
1597
- * return (
1598
- * <>
1599
- * <ul>
1600
- * {userMemberships.data?.map((mem) => (
1601
- * <li key={mem.id}>
1602
- * <span>{mem.organization.name}</span>
1603
- * <button onClick={() => setActive({ organization: mem.organization.id })}>Select</button>
1604
- * </li>
1605
- * ))}
1606
- * </ul>
1607
- *
1608
- * <button disabled={!userMemberships.hasNextPage} onClick={() => userMemberships.fetchNext()}>
1609
- * Load more
1610
- * </button>
1611
- * </>
1612
- * )
1613
- * }
1614
- *
1615
- * export default JoinedOrganizations
1616
- * ```
1617
- *
1618
- * @example
1619
- * ### Simple pagination
1620
- *
1621
- * The following example demonstrates how to use the `fetchPrevious` and `fetchNext` helper functions to paginate through the data. The `userInvitations` attribute will be populated with the first page of invitations. When the "Previous page" or "Next page" button is clicked, the `fetchPrevious` or `fetchNext` helper function will be called to fetch the previous or next page of invitations.
1622
- *
1623
- * Notice the difference between this example's pagination and the infinite pagination example above.
1624
- *
1625
- * ```tsx {{ filename: 'src/components/UserInvitationsTable.tsx' }}
1626
- * import { useOrganizationList } from '@clerk/react'
1627
- * import React from 'react'
1628
- *
1629
- * const UserInvitationsTable = () => {
1630
- * const { isLoaded, userInvitations } = useOrganizationList({
1631
- * userInvitations: {
1632
- * infinite: true,
1633
- * keepPreviousData: true,
1634
- * },
1635
- * })
1636
- *
1637
- * if (!isLoaded || userInvitations.isLoading) {
1638
- * return <>Loading</>
1639
- * }
1640
- *
1641
- * return (
1642
- * <>
1643
- * <table>
1644
- * <thead>
1645
- * <tr>
1646
- * <th>Email</th>
1647
- * <th>Org name</th>
1648
- * </tr>
1649
- * </thead>
1650
- *
1651
- * <tbody>
1652
- * {userInvitations.data?.map((inv) => (
1653
- * <tr key={inv.id}>
1654
- * <th>{inv.emailAddress}</th>
1655
- * <th>{inv.publicOrganizationData.name}</th>
1656
- * </tr>
1657
- * ))}
1658
- * </tbody>
1659
- * </table>
1660
- *
1661
- * <button disabled={!userInvitations.hasPreviousPage} onClick={userInvitations.fetchPrevious}>
1662
- * Prev
1663
- * </button>
1664
- * <button disabled={!userInvitations.hasNextPage} onClick={userInvitations.fetchNext}>
1665
- * Next
1666
- * </button>
1667
- * </>
1668
- * )
1669
- * }
1670
- *
1671
- * export default UserInvitationsTable
1672
- * ```
1673
- */
1674
- function useOrganizationList(params) {
1675
- const { userMemberships, userInvitations, userSuggestions } = params || {};
1676
- useAssertWrappedByClerkProvider("useOrganizationList");
1677
- useAttemptToEnableOrganizations("useOrganizationList", { enabled: userMemberships !== void 0 || userInvitations !== void 0 || userSuggestions !== void 0 });
1678
- const userMembershipsSafeValues = useWithSafeValues(userMemberships, {
1679
- initialPage: 1,
1680
- pageSize: 10,
1681
- keepPreviousData: false,
1682
- infinite: false
1683
- });
1684
- const userInvitationsSafeValues = useWithSafeValues(userInvitations, {
1685
- initialPage: 1,
1686
- pageSize: 10,
1687
- status: "pending",
1688
- keepPreviousData: false,
1689
- infinite: false
1690
- });
1691
- const userSuggestionsSafeValues = useWithSafeValues(userSuggestions, {
1692
- initialPage: 1,
1693
- pageSize: 10,
1694
- status: "pending",
1695
- keepPreviousData: false,
1696
- infinite: false
1697
- });
1698
- const clerk = useClerkInstanceContext();
1699
- const user = useUserBase();
1700
- clerk.telemetry?.record(require_telemetry.eventMethodCalled("useOrganizationList"));
1701
- const userMembershipsParams = typeof userMemberships === "undefined" ? void 0 : {
1702
- initialPage: userMembershipsSafeValues.initialPage,
1703
- pageSize: userMembershipsSafeValues.pageSize
1704
- };
1705
- const userInvitationsParams = typeof userInvitations === "undefined" ? void 0 : {
1706
- initialPage: userInvitationsSafeValues.initialPage,
1707
- pageSize: userInvitationsSafeValues.pageSize,
1708
- status: userInvitationsSafeValues.status
1709
- };
1710
- const userSuggestionsParams = typeof userSuggestions === "undefined" ? void 0 : {
1711
- initialPage: userSuggestionsSafeValues.initialPage,
1712
- pageSize: userSuggestionsSafeValues.pageSize,
1713
- status: userSuggestionsSafeValues.status
1714
- };
1715
- const isClerkLoaded = !!(clerk.loaded && user);
1716
- const memberships = usePagesOrInfinite({
1717
- fetcher: user?.getOrganizationMemberships,
1718
- config: {
1719
- keepPreviousData: userMembershipsSafeValues.keepPreviousData,
1720
- infinite: userMembershipsSafeValues.infinite,
1721
- enabled: !!userMembershipsParams,
1722
- isSignedIn: user !== null,
1723
- initialPage: userMembershipsSafeValues.initialPage,
1724
- pageSize: userMembershipsSafeValues.pageSize
1725
- },
1726
- keys: createCacheKeys({
1727
- stablePrefix: STABLE_KEYS.USER_MEMBERSHIPS_KEY,
1728
- authenticated: true,
1729
- tracked: { userId: user?.id },
1730
- untracked: { args: userMembershipsParams }
1731
- })
1732
- });
1733
- const invitations = usePagesOrInfinite({
1734
- fetcher: user?.getOrganizationInvitations,
1735
- config: {
1736
- keepPreviousData: userInvitationsSafeValues.keepPreviousData,
1737
- infinite: userInvitationsSafeValues.infinite,
1738
- enabled: !!userInvitationsParams,
1739
- isSignedIn: user !== null,
1740
- initialPage: userInvitationsSafeValues.initialPage,
1741
- pageSize: userInvitationsSafeValues.pageSize
1742
- },
1743
- keys: createCacheKeys({
1744
- stablePrefix: STABLE_KEYS.USER_INVITATIONS_KEY,
1745
- authenticated: true,
1746
- tracked: { userId: user?.id },
1747
- untracked: { args: userInvitationsParams }
1748
- })
1749
- });
1750
- const suggestions = usePagesOrInfinite({
1751
- fetcher: user?.getOrganizationSuggestions,
1752
- config: {
1753
- keepPreviousData: userSuggestionsSafeValues.keepPreviousData,
1754
- infinite: userSuggestionsSafeValues.infinite,
1755
- enabled: !!userSuggestionsParams,
1756
- isSignedIn: user !== null,
1757
- initialPage: userSuggestionsSafeValues.initialPage,
1758
- pageSize: userSuggestionsSafeValues.pageSize
1759
- },
1760
- keys: createCacheKeys({
1761
- stablePrefix: STABLE_KEYS.USER_SUGGESTIONS_KEY,
1762
- authenticated: true,
1763
- tracked: { userId: user?.id },
1764
- untracked: { args: userSuggestionsParams }
1765
- })
1766
- });
1767
- if (!isClerkLoaded) return {
1768
- isLoaded: false,
1769
- createOrganization: void 0,
1770
- setActive: void 0,
1771
- userMemberships: undefinedPaginatedResource,
1772
- userInvitations: undefinedPaginatedResource,
1773
- userSuggestions: undefinedPaginatedResource
1774
- };
1775
- return {
1776
- isLoaded: isClerkLoaded,
1777
- setActive: clerk.setActive,
1778
- createOrganization: clerk.createOrganization,
1779
- userMemberships: memberships,
1780
- userInvitations: invitations,
1781
- userSuggestions: suggestions
1782
- };
1783
- }
1784
-
1785
- //#endregion
1786
- //#region src/react/hooks/useSafeLayoutEffect.tsx
1787
- /**
1788
- * @internal
1789
- */
1790
- const useSafeLayoutEffect = typeof window !== "undefined" ? react.default.useLayoutEffect : react.default.useEffect;
1791
-
1792
- //#endregion
1793
- //#region src/react/hooks/useSession.ts
1794
- const hookName$2 = `useSession`;
1795
- /**
1796
- * The `useSession()` hook provides access to the current user's [`Session`](https://clerk.com/docs/reference/objects/session) object, as well as helpers for setting the active session.
1797
- *
1798
- * @unionReturnHeadings
1799
- * ["Loading", "Signed out", "Signed in"]
1800
- *
1801
- * @function
1802
- *
1803
- * @param [options] - An object containing options for the `useSession()` hook.
1804
- * @example
1805
- * ### Access the `Session` object
1806
- *
1807
- * The following example uses the `useSession()` hook to access the `Session` object, which has the `lastActiveAt` property. The `lastActiveAt` property is a `Date` object used to show the time the session was last active.
1808
- *
1809
- * <Tabs items='React,Next.js'>
1810
- * <Tab>
1811
- *
1812
- * ```tsx {{ filename: 'src/Home.tsx' }}
1813
- * import { useSession } from '@clerk/react'
1814
- *
1815
- * export default function Home() {
1816
- * const { isLoaded, session, isSignedIn } = useSession()
1817
- *
1818
- * if (!isLoaded) {
1819
- * // Handle loading state
1820
- * return null
1821
- * }
1822
- * if (!isSignedIn) {
1823
- * // Handle signed out state
1824
- * return null
1825
- * }
1826
- *
1827
- * return (
1828
- * <div>
1829
- * <p>This session has been active since {session.lastActiveAt.toLocaleString()}</p>
1830
- * </div>
1831
- * )
1832
- * }
1833
- * ```
1834
- *
1835
- * </Tab>
1836
- * <Tab>
1837
- *
1838
- * ```tsx {{ filename: 'app/page.tsx' }}
1839
- * 'use client';
1840
- *
1841
- * import { useSession } from '@clerk/nextjs';
1842
- *
1843
- * export default function HomePage() {
1844
- * const { isLoaded, session, isSignedIn } = useSession();
1845
- *
1846
- * if (!isLoaded) {
1847
- * // Handle loading state
1848
- * return null;
1849
- * }
1850
- * if (!isSignedIn) {
1851
- * // Handle signed out state
1852
- * return null;
1853
- * }
1854
- *
1855
- * return (
1856
- * <div>
1857
- * <p>This session has been active since {session.lastActiveAt.toLocaleString()}</p>
1858
- * </div>
1859
- * );
1860
- * }
1861
- * ```
1862
- *
1863
- * </Tab>
1864
- * </Tabs>
1865
- */
1866
- const useSession = () => {
1867
- useAssertWrappedByClerkProvider(hookName$2);
1868
- const session = useSessionBase();
1869
- const clerk = useClerkInstanceContext();
1870
- clerk.telemetry?.record(require_telemetry.eventMethodCalled(hookName$2));
1871
- if (session === void 0) return {
1872
- isLoaded: false,
1873
- isSignedIn: void 0,
1874
- session: void 0
1875
- };
1876
- if (session === null) return {
1877
- isLoaded: true,
1878
- isSignedIn: false,
1879
- session: null
1880
- };
1881
- return {
1882
- isLoaded: true,
1883
- isSignedIn: clerk.isSignedIn,
1884
- session
1885
- };
1886
- };
1887
-
1888
- //#endregion
1889
- //#region src/react/hooks/base/useClientBase.ts
1890
- const initialSnapshot = void 0;
1891
- const getInitialSnapshot = () => initialSnapshot;
1892
- function useClientBase() {
1893
- const clerk = useClerkInstanceContext();
1894
- return (0, react.useSyncExternalStore)((0, react.useCallback)((callback) => clerk.addListener(callback, { skipInitialEmit: true }), [clerk]), (0, react.useCallback)(() => {
1895
- if (!clerk.loaded || !clerk.__internal_lastEmittedResources) return;
1896
- return clerk.__internal_lastEmittedResources.client;
1897
- }, [clerk]), getInitialSnapshot);
1898
- }
1899
-
1900
- //#endregion
1901
- //#region src/react/hooks/useSessionList.ts
1902
- const hookName$1 = "useSessionList";
1903
- /**
1904
- * The `useSessionList()` hook returns an array of [`Session`](https://clerk.com/docs/reference/objects/session) objects that have been registered on the client device.
1905
- *
1906
- * @unionReturnHeadings
1907
- * ["Initialization", "Loaded"]
1908
- *
1909
- * @function
1910
- *
1911
- * @example
1912
- * ### Get a list of sessions
1913
- *
1914
- * The following example uses `useSessionList()` to get a list of sessions that have been registered on the client device. The `sessions` property is used to show the number of times the user has visited the page.
1915
- *
1916
- * <Tabs items='React,Next.js'>
1917
- * <Tab>
1918
- *
1919
- * ```tsx {{ filename: 'src/Home.tsx' }}
1920
- * import { useSessionList } from '@clerk/react'
1921
- *
1922
- * export default function Home() {
1923
- * const { isLoaded, sessions } = useSessionList()
1924
- *
1925
- * if (!isLoaded) {
1926
- * // Handle loading state
1927
- * return null
1928
- * }
1929
- *
1930
- * return (
1931
- * <div>
1932
- * <p>Welcome back. You've been here {sessions.length} times before.</p>
1933
- * </div>
1934
- * )
1935
- * }
1936
- * ```
1937
- *
1938
- * </Tab>
1939
- * <Tab>
1940
- *
1941
- * ```tsx {{ filename: 'app/page.tsx' }}
1942
- * 'use client';
1943
- *
1944
- * import { useSessionList } from '@clerk/nextjs';
1945
- *
1946
- * export default function HomePage() {
1947
- * const { isLoaded, sessions } = useSessionList();
1948
- *
1949
- * if (!isLoaded) {
1950
- * // Handle loading state
1951
- * return null;
1952
- * }
1953
- *
1954
- * return (
1955
- * <div>
1956
- * <p>Welcome back. You've been here {sessions.length} times before.</p>
1957
- * </div>
1958
- * );
1959
- * }
1960
- * ```
1961
- *
1962
- * </Tab>
1963
- * </Tabs>
1964
- */
1965
- const useSessionList = () => {
1966
- useAssertWrappedByClerkProvider(hookName$1);
1967
- const isomorphicClerk = useClerkInstanceContext();
1968
- const client = useClientBase();
1969
- useClerkInstanceContext().telemetry?.record(require_telemetry.eventMethodCalled(hookName$1));
1970
- if (!client) return {
1971
- isLoaded: false,
1972
- sessions: void 0,
1973
- setActive: void 0
1974
- };
1975
- return {
1976
- isLoaded: true,
1977
- sessions: client.sessions,
1978
- setActive: isomorphicClerk.setActive
1979
- };
1980
- };
1981
-
1982
- //#endregion
1983
- //#region src/react/hooks/useUser.ts
1984
- const hookName = "useUser";
1985
- /**
1986
- * The `useUser()` hook provides access to the current user's [`User`](https://clerk.com/docs/reference/objects/user) object, which contains all the data for a single user in your application and provides methods to manage their account. This hook also allows you to check if the user is signed in and if Clerk has loaded.
1987
- *
1988
- * @unionReturnHeadings
1989
- * ["Loading", "Signed out", "Signed in"]
1990
- *
1991
- * @example
1992
- * ### Get the current user
1993
- *
1994
- * The following example uses the `useUser()` hook to access the [`User`](https://clerk.com/docs/reference/objects/user) object, which contains the current user's data such as their full name. The `isLoaded` and `isSignedIn` properties are used to handle the loading state and to check if the user is signed in, respectively.
1995
- *
1996
- * ```tsx {{ filename: 'src/Example.tsx' }}
1997
- * import { useUser } from '@clerk/react'
1998
- *
1999
- * export default function Example() {
2000
- * const { isSignedIn, user, isLoaded } = useUser()
2001
- *
2002
- * if (!isLoaded) {
2003
- * return <div>Loading...</div>
2004
- * }
2005
- *
2006
- * if (!isSignedIn) {
2007
- * return <div>Sign in to view this page</div>
2008
- * }
2009
- *
2010
- * return <div>Hello {user.firstName}!</div>
2011
- * }
2012
- * ```
2013
- *
2014
- * @example
2015
- * ### Update user data
2016
- *
2017
- * The following example uses the `useUser()` hook to access the [`User`](https://clerk.com/docs/reference/objects/user) object, which calls the [`update()`](https://clerk.com/docs/reference/objects/user#update) method to update the current user's information.
2018
- *
2019
- * <Tabs items='React,Next.js'>
2020
- * <Tab>
2021
- *
2022
- * ```tsx {{ filename: 'src/Home.tsx' }}
2023
- * import { useUser } from '@clerk/react'
2024
- *
2025
- * export default function Home() {
2026
- * const { isSignedIn, isLoaded, user } = useUser()
2027
- *
2028
- * if (!isLoaded) {
2029
- * // Handle loading state
2030
- * return null
2031
- * }
2032
- *
2033
- * if (!isSignedIn) return null
2034
- *
2035
- * const updateUser = async () => {
2036
- * await user.update({
2037
- * firstName: 'John',
2038
- * lastName: 'Doe',
2039
- * })
2040
- * }
2041
- *
2042
- * return (
2043
- * <>
2044
- * <button onClick={updateUser}>Update your name</button>
2045
- * <p>user.firstName: {user.firstName}</p>
2046
- * <p>user.lastName: {user.lastName}</p>
2047
- * </>
2048
- * )
2049
- * }
2050
- * ```
2051
- * </Tab>
2052
- * <Tab>
2053
- *
2054
- * ```tsx {{ filename: 'app/page.tsx' }}
2055
- * 'use client';
2056
- *
2057
- * import { useUser } from '@clerk/nextjs';
2058
- *
2059
- * export default function HomePage() {
2060
- * const { isSignedIn, isLoaded, user } = useUser();
2061
- *
2062
- * if (!isLoaded) {
2063
- * // Handle loading state
2064
- * return null;
2065
- * }
2066
- *
2067
- * if (!isSignedIn) return null;
2068
- *
2069
- * const updateUser = async () => {
2070
- * await user.update({
2071
- * firstName: 'John',
2072
- * lastName: 'Doe',
2073
- * });
2074
- * };
2075
- *
2076
- * return (
2077
- * <>
2078
- * <button onClick={updateUser}>Update your name</button>
2079
- * <p>user.firstName: {user.firstName}</p>
2080
- * <p>user.lastName: {user.lastName}</p>
2081
- * </>
2082
- * );
2083
- * }
2084
- * ```
2085
- *
2086
- * </Tab>
2087
- * </Tabs>
2088
- *
2089
- * @example
2090
- * ### Reload user data
2091
- *
2092
- * The following example uses the `useUser()` hook to access the [`User`](https://clerk.com/docs/reference/objects/user) object, which calls the [`reload()`](https://clerk.com/docs/reference/objects/user#reload) method to get the latest user's information.
2093
- *
2094
- * <Tabs items='React,Next.js'>
2095
- * <Tab>
2096
- *
2097
- * ```tsx {{ filename: 'src/Home.tsx' }}
2098
- * import { useUser } from '@clerk/react'
2099
- *
2100
- * export default function Home() {
2101
- * const { isSignedIn, isLoaded, user } = useUser();
2102
- *
2103
- * if (!isLoaded) {
2104
- * // Handle loading state
2105
- * return null;
2106
- * }
2107
- *
2108
- * if (!isSignedIn) return null;
2109
- *
2110
- * const updateUser = async () => {
2111
- * // Update data via an API endpoint
2112
- * const updateMetadata = await fetch('/api/updateMetadata', {
2113
- * method: 'POST',
2114
- * body: JSON.stringify({
2115
- * role: 'admin'
2116
- * })
2117
- * });
2118
- *
2119
- * // Check if the update was successful
2120
- * if ((await updateMetadata.json()).message !== 'success') {
2121
- * throw new Error('Error updating');
2122
- * }
2123
- *
2124
- * // If the update was successful, reload the user data
2125
- * await user.reload();
2126
- * };
2127
- *
2128
- * return (
2129
- * <>
2130
- * <button onClick={updateUser}>Update your metadata</button>
2131
- * <p>user role: {user.publicMetadata.role}</p>
2132
- * </>
2133
- * );
2134
- * }
2135
- * ```
2136
- *
2137
- * </Tab>
2138
- * <Tab>
2139
- *
2140
- * ```tsx {{ filename: 'app/page.tsx' }}
2141
- * 'use client';
2142
- *
2143
- * import { useUser } from '@clerk/nextjs';
2144
- *
2145
- * export default function HomePage() {
2146
- * const { isSignedIn, isLoaded, user } = useUser();
2147
- *
2148
- * if (!isLoaded) {
2149
- * // Handle loading state
2150
- * return null;
2151
- * }
2152
- *
2153
- * if (!isSignedIn) return null;
2154
- *
2155
- * const updateUser = async () => {
2156
- * // Update data via an API endpoint
2157
- * const updateMetadata = await fetch('/api/updateMetadata', {
2158
- * method: 'POST',
2159
- * body: JSON.stringify({
2160
- * role: 'admin',
2161
- * }),
2162
- * });
2163
- *
2164
- * // Check if the update was successful
2165
- * if ((await updateMetadata.json()).message !== 'success') {
2166
- * throw new Error('Error updating');
2167
- * }
2168
- *
2169
- * // If the update was successful, reload the user data
2170
- * await user.reload();
2171
- * };
2172
- *
2173
- * return (
2174
- * <>
2175
- * <button onClick={updateUser}>Update your metadata</button>
2176
- * <p>user role: {user.publicMetadata.role}</p>
2177
- * </>
2178
- * );
2179
- * }
2180
- * ```
2181
- *
2182
- * </Tab>
2183
- * </Tabs>
2184
- */
2185
- function useUser() {
2186
- useAssertWrappedByClerkProvider(hookName);
2187
- const user = useUserBase();
2188
- useClerkInstanceContext().telemetry?.record(require_telemetry.eventMethodCalled(hookName));
2189
- if (user === void 0) return {
2190
- isLoaded: false,
2191
- isSignedIn: void 0,
2192
- user: void 0
2193
- };
2194
- if (user === null) return {
2195
- isLoaded: true,
2196
- isSignedIn: false,
2197
- user: null
2198
- };
2199
- return {
2200
- isLoaded: true,
2201
- isSignedIn: true,
2202
- user
2203
- };
2204
- }
2205
-
2206
- //#endregion
2207
- //#region src/react/hooks/useDeepEqualMemo.ts
2208
- const useDeepEqualMemoize = (value) => {
2209
- const ref = react.default.useRef(value);
2210
- if (!(0, dequal.dequal)(value, ref.current)) ref.current = value;
2211
- return react.default.useMemo(() => ref.current, [ref.current]);
2212
- };
2213
- /**
2214
- * @internal
2215
- */
2216
- const useDeepEqualMemo = (factory, dependencyArray) => {
2217
- return react.default.useMemo(factory, useDeepEqualMemoize(dependencyArray));
2218
- };
2219
- /**
2220
- * @internal
2221
- */
2222
- const isDeeplyEqual = dequal.dequal;
2223
-
2224
- //#endregion
2225
- //#region src/react/hooks/useReverification.ts
2226
- const CLERK_API_REVERIFICATION_ERROR_CODE = "session_reverification_required";
2227
- /**
2228
- *
2229
- */
2230
- async function resolveResult(result) {
2231
- try {
2232
- const r = await result;
2233
- if (r instanceof Response) return r.json();
2234
- return r;
2235
- } catch (e) {
2236
- if (require_error.isClerkAPIResponseError(e) && e.errors.find(({ code }) => code === CLERK_API_REVERIFICATION_ERROR_CODE)) return require_authorization_errors.reverificationError();
2237
- throw e;
2238
- }
2239
- }
2240
- /**
2241
- *
2242
- */
2243
- function createReverificationHandler(params) {
2244
- /**
2245
- *
2246
- */
2247
- function assertReverification(fetcher) {
2248
- return (async (...args) => {
2249
- let result = await resolveResult(fetcher(...args));
2250
- if (require_authorization_errors.isReverificationHint(result)) {
2251
- /**
2252
- * Create a promise
2253
- */
2254
- const resolvers = require_createDeferredPromise.createDeferredPromise();
2255
- const isValidMetadata = require_authorization.validateReverificationConfig(result.clerk_error.metadata?.reverification);
2256
- const level = isValidMetadata ? isValidMetadata().level : void 0;
2257
- const cancel = () => {
2258
- resolvers.reject(new require_clerkRuntimeError.ClerkRuntimeError("User cancelled attempted verification", { code: "reverification_cancelled" }));
2259
- };
2260
- const complete = () => {
2261
- resolvers.resolve(true);
2262
- };
2263
- if (params.onNeedsReverification === void 0)
2264
- /**
2265
- * On success resolve the pending promise
2266
- * On cancel reject the pending promise
2267
- */
2268
- params.openUIComponent?.({
2269
- level,
2270
- afterVerification: complete,
2271
- afterVerificationCancelled: cancel
2272
- });
2273
- else params.onNeedsReverification({
2274
- cancel,
2275
- complete,
2276
- level
2277
- });
2278
- /**
2279
- * Wait until the promise from above have been resolved or rejected
2280
- */
2281
- await resolvers.promise;
2282
- /**
2283
- * After the promise resolved successfully try the original request one more time
2284
- */
2285
- result = await resolveResult(fetcher(...args));
2286
- }
2287
- return result;
2288
- });
2289
- }
2290
- return assertReverification;
2291
- }
2292
- /**
2293
- * > [!WARNING]
2294
- * >
2295
- * > Depending on the SDK you're using, this feature requires `@clerk/nextjs@6.12.7` or later, `@clerk/react@5.25.1` or later, and `@clerk/clerk-js@5.57.1` or later.
2296
- *
2297
- * The `useReverification()` hook is used to handle a session's reverification flow. If a request requires reverification, a modal will display, prompting the user to verify their credentials. Upon successful verification, the original request will automatically retry.
2298
- *
2299
- * @function
2300
- *
2301
- * @returns The `useReverification()` hook returns an array with the "enhanced" fetcher.
2302
- *
2303
- * @example
2304
- * ### Handle cancellation of the reverification process
2305
- *
2306
- * The following example demonstrates how to handle scenarios where a user cancels the reverification flow, such as closing the modal, which might result in `myData` being `null`.
2307
- *
2308
- * In the following example, `myFetcher` would be a function in your backend that fetches data from the route that requires reverification. See the [guide on how to require reverification](https://clerk.com/docs/guides/secure/reverification) for more information.
2309
- *
2310
- * ```tsx {{ filename: 'src/components/MyButton.tsx' }}
2311
- * import { useReverification } from '@clerk/react'
2312
- * import { isReverificationCancelledError } from '@clerk/react/error'
2313
- *
2314
- * type MyData = {
2315
- * balance: number
2316
- * }
2317
- *
2318
- * export function MyButton() {
2319
- * const fetchMyData = () => fetch('/api/balance').then(res=> res.json() as Promise<MyData>)
2320
- * const enhancedFetcher = useReverification(fetchMyData);
2321
- *
2322
- * const handleClick = async () => {
2323
- * try {
2324
- * const myData = await enhancedFetcher()
2325
- * // ^ is types as `MyData`
2326
- * } catch (e) {
2327
- * // Handle error returned from the fetcher here
2328
- *
2329
- * // You can also handle cancellation with the following
2330
- * if (isReverificationCancelledError(err)) {
2331
- * // Handle the cancellation error here
2332
- * }
2333
- * }
2334
- * }
2335
- *
2336
- * return <button onClick={handleClick}>Update User</button>
2337
- * }
2338
- * ```
2339
- */
2340
- const useReverification = (fetcher, options) => {
2341
- const { __internal_openReverification, telemetry } = useClerk();
2342
- const fetcherRef = (0, react.useRef)(fetcher);
2343
- const optionsRef = (0, react.useRef)(options);
2344
- telemetry?.record(require_telemetry.eventMethodCalled("useReverification", { onNeedsReverification: Boolean(options?.onNeedsReverification) }));
2345
- useSafeLayoutEffect(() => {
2346
- fetcherRef.current = fetcher;
2347
- optionsRef.current = options;
2348
- });
2349
- return (0, react.useCallback)((...args) => {
2350
- return createReverificationHandler({
2351
- openUIComponent: __internal_openReverification,
2352
- telemetry,
2353
- ...optionsRef.current
2354
- })(fetcherRef.current)(...args);
2355
- }, [__internal_openReverification, telemetry]);
2356
- };
2357
-
2358
- //#endregion
2359
- //#region src/react/hooks/useBillingIsEnabled.ts
2360
- /**
2361
- * @internal
2362
- */
2363
- function useBillingIsEnabled(params) {
2364
- const clerk = useClerkInstanceContext();
2365
- const enabledFromParam = params?.enabled ?? true;
2366
- const environment = clerk.__internal_environment;
2367
- const user = useUserBase();
2368
- const organization = useOrganizationBase();
2369
- const userBillingEnabled = environment?.commerceSettings.billing.user.enabled;
2370
- const orgBillingEnabled = environment?.commerceSettings.billing.organization.enabled;
2371
- const billingEnabled = params?.for === "organization" ? orgBillingEnabled : params?.for === "user" ? userBillingEnabled : userBillingEnabled || orgBillingEnabled;
2372
- const isOrganization = params?.for === "organization";
2373
- const requireUserAndOrganizationWhenAuthenticated = params?.authenticated ?? true ? (isOrganization ? Boolean(organization?.id) : true) && Boolean(user?.id) : true;
2374
- return billingEnabled && enabledFromParam && clerk.loaded && requireUserAndOrganizationWhenAuthenticated;
2375
- }
2376
-
2377
- //#endregion
2378
- //#region src/react/hooks/createBillingPaginatedHook.tsx
2379
- /**
2380
- * A hook factory that creates paginated data fetching hooks for commerce-related resources.
2381
- * It provides a standardized way to create hooks that can fetch either user or Organization resources
2382
- * with built-in pagination support.
2383
- *
2384
- * The generated hooks handle:
2385
- * - Clerk authentication context
2386
- * - Resource-specific data fetching
2387
- * - Pagination (both traditional and infinite scroll)
2388
- * - Telemetry tracking
2389
- * - Type safety for the specific resource.
2390
- *
2391
- * @internal
2392
- */
2393
- function createBillingPaginatedHook({ hookName, resourceType, useFetcher, options }) {
2394
- return function useBillingHook(params) {
2395
- const { for: _for, enabled: externalEnabled, ...paginationParams } = params || {};
2396
- const safeFor = _for || "user";
2397
- useAssertWrappedByClerkProvider(hookName);
2398
- const fetchFn = useFetcher(safeFor);
2399
- const safeValues = useWithSafeValues(paginationParams, {
2400
- initialPage: 1,
2401
- pageSize: 10,
2402
- keepPreviousData: false,
2403
- infinite: false,
2404
- __experimental_mode: void 0
2405
- });
2406
- const clerk = useClerkInstanceContext();
2407
- const user = useUserBase();
2408
- const organization = useOrganizationBase();
2409
- clerk.telemetry?.record(require_telemetry.eventMethodCalled(hookName));
2410
- const isForOrganization = safeFor === "organization";
2411
- const billingEnabled = useBillingIsEnabled({
2412
- for: safeFor,
2413
- enabled: externalEnabled,
2414
- authenticated: !options?.unauthenticated
2415
- });
2416
- const hookParams = typeof paginationParams === "undefined" ? void 0 : {
2417
- initialPage: safeValues.initialPage,
2418
- pageSize: safeValues.pageSize,
2419
- ...options?.unauthenticated ? {} : isForOrganization ? { orgId: organization?.id } : {}
2420
- };
2421
- const isEnabled = !!hookParams && clerk.loaded && !!billingEnabled;
2422
- return usePagesOrInfinite({
2423
- fetcher: fetchFn,
2424
- config: {
2425
- keepPreviousData: safeValues.keepPreviousData,
2426
- infinite: safeValues.infinite,
2427
- enabled: isEnabled,
2428
- ...options?.unauthenticated ? {} : { isSignedIn: user !== null },
2429
- __experimental_mode: safeValues.__experimental_mode,
2430
- initialPage: safeValues.initialPage,
2431
- pageSize: safeValues.pageSize
2432
- },
2433
- keys: createCacheKeys({
2434
- stablePrefix: resourceType,
2435
- authenticated: !options?.unauthenticated,
2436
- tracked: options?.unauthenticated ? { for: safeFor } : {
2437
- userId: user?.id,
2438
- ...isForOrganization ? { orgId: organization?.id } : {}
2439
- },
2440
- untracked: { args: hookParams }
2441
- })
2442
- });
2443
- };
2444
- }
2445
-
2446
- //#endregion
2447
- //#region src/react/hooks/useStatements.tsx
2448
- /**
2449
- * @internal
2450
- */
2451
- const useStatements = createBillingPaginatedHook({
2452
- hookName: "useStatements",
2453
- resourceType: STABLE_KEYS.STATEMENTS_KEY,
2454
- useFetcher: () => {
2455
- const clerk = useClerkInstanceContext();
2456
- if (clerk.loaded) return clerk.billing.getStatements;
2457
- }
2458
- });
2459
-
2460
- //#endregion
2461
- //#region src/react/hooks/usePaymentAttempts.tsx
2462
- /**
2463
- * @internal
2464
- */
2465
- const usePaymentAttempts = createBillingPaginatedHook({
2466
- hookName: "usePaymentAttempts",
2467
- resourceType: STABLE_KEYS.PAYMENT_ATTEMPTS_KEY,
2468
- useFetcher: () => {
2469
- const clerk = useClerkInstanceContext();
2470
- if (clerk.loaded) return clerk.billing.getPaymentAttempts;
2471
- }
2472
- });
2473
-
2474
- //#endregion
2475
- //#region src/react/hooks/usePaymentMethods.tsx
2476
- /**
2477
- * @internal
2478
- */
2479
- const usePaymentMethods = createBillingPaginatedHook({
2480
- hookName: "usePaymentMethods",
2481
- resourceType: STABLE_KEYS.PAYMENT_METHODS_KEY,
2482
- useFetcher: (resource) => {
2483
- const organization = useOrganizationBase();
2484
- const user = useUserBase();
2485
- if (resource === "organization") return organization?.getPaymentMethods;
2486
- return user?.getPaymentMethods;
2487
- }
2488
- });
2489
-
2490
- //#endregion
2491
- //#region src/react/hooks/usePlans.tsx
2492
- /**
2493
- * @internal
2494
- */
2495
- const usePlans = createBillingPaginatedHook({
2496
- hookName: "usePlans",
2497
- resourceType: STABLE_KEYS.PLANS_KEY,
2498
- useFetcher: (_for) => {
2499
- const clerk = useClerkInstanceContext();
2500
- if (!clerk.loaded) return;
2501
- return (params) => clerk.billing.getPlans({
2502
- ...params,
2503
- for: _for
2504
- });
2505
- },
2506
- options: { unauthenticated: true }
2507
- });
2508
-
2509
- //#endregion
2510
- //#region src/react/hooks/useSubscription.shared.ts
2511
- function useSubscriptionCacheKeys(params) {
2512
- const { userId, orgId, for: forType } = params;
2513
- return (0, react.useMemo)(() => {
2514
- const safeOrgId = forType === "organization" ? orgId : void 0;
2515
- return createCacheKeys({
2516
- stablePrefix: STABLE_KEYS.SUBSCRIPTION_KEY,
2517
- authenticated: true,
2518
- tracked: {
2519
- userId,
2520
- orgId: safeOrgId
2521
- },
2522
- untracked: { args: { orgId: safeOrgId } }
2523
- });
2524
- }, [
2525
- userId,
2526
- orgId,
2527
- forType
2528
- ]);
2529
- }
2530
-
2531
- //#endregion
2532
- //#region src/react/hooks/useSubscription.tsx
2533
- const HOOK_NAME$2 = "useSubscription";
2534
- /**
2535
- * @internal
2536
- */
2537
- function useSubscription(params) {
2538
- useAssertWrappedByClerkProvider(HOOK_NAME$2);
2539
- const clerk = useClerkInstanceContext();
2540
- const user = useUserBase();
2541
- const organization = useOrganizationBase();
2542
- const billingEnabled = useBillingIsEnabled(params);
2543
- const recordedRef = (0, react.useRef)(false);
2544
- (0, react.useEffect)(() => {
2545
- if (!recordedRef.current && clerk?.telemetry) {
2546
- clerk.telemetry.record(require_telemetry.eventMethodCalled(HOOK_NAME$2));
2547
- recordedRef.current = true;
2548
- }
2549
- }, [clerk]);
2550
- const keepPreviousData = params?.keepPreviousData ?? false;
2551
- const [queryClient] = useClerkQueryClient();
2552
- const { queryKey, invalidationKey, stableKey, authenticated } = useSubscriptionCacheKeys({
2553
- userId: user?.id,
2554
- orgId: organization?.id,
2555
- for: params?.for
2556
- });
2557
- const queriesEnabled = Boolean(user?.id && billingEnabled);
2558
- useClearQueriesOnSignOut({
2559
- isSignedOut: user === null,
2560
- authenticated,
2561
- stableKeys: stableKey
2562
- });
2563
- const query = useClerkQuery({
2564
- queryKey,
2565
- queryFn: ({ queryKey }) => {
2566
- const obj = queryKey[3];
2567
- return clerk.billing.getSubscription(obj.args);
2568
- },
2569
- staleTime: 1e3 * 60,
2570
- enabled: queriesEnabled,
2571
- placeholderData: defineKeepPreviousDataFn(keepPreviousData && queriesEnabled)
2572
- });
2573
- const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: invalidationKey }), [queryClient, invalidationKey]);
2574
- return {
2575
- data: query.data,
2576
- error: query.error ?? void 0,
2577
- isLoading: query.isLoading,
2578
- isFetching: query.isFetching,
2579
- revalidate
2580
- };
2581
- }
2582
-
2583
- //#endregion
2584
- //#region src/react/hooks/useCheckout.ts
2585
- /**
2586
- * @function
2587
- *
2588
- * @param [options] - An object containing the configuration for the checkout flow.
2589
- *
2590
- * **Required** if the hook is used without a `<CheckoutProvider />` wrapping the component tree.
2591
- */
2592
- const useCheckout = (options) => {
2593
- const contextOptions = useCheckoutContext();
2594
- const { for: forOrganization, planId, planPeriod, seatsQuantity, priceId } = options || contextOptions;
2595
- const organization = useOrganizationBase();
2596
- const { isLoaded, user } = useUser();
2597
- const clerk = useClerkInstanceContext();
2598
- if (user === null && isLoaded) throw new Error("Clerk: Ensure that `useCheckout` is inside a component wrapped with `<Show when=\"signed-in\" />`.");
2599
- if (isLoaded && forOrganization === "organization" && organization === null) throw new Error("Clerk: Ensure your flow checks for an active organization. Retrieve `orgId` from `useAuth()` and confirm it is defined. For SSR, see: https://clerk.com/docs/reference/backend/types/auth-object#how-to-access-the-auth-object");
2600
- const signal = (0, react.useCallback)(() => {
2601
- return clerk.__experimental_checkout({
2602
- planId,
2603
- planPeriod,
2604
- for: forOrganization,
2605
- seatsQuantity,
2606
- priceId
2607
- });
2608
- }, [
2609
- user?.id,
2610
- organization?.id,
2611
- planId,
2612
- planPeriod,
2613
- forOrganization,
2614
- seatsQuantity,
2615
- priceId
2616
- ]);
2617
- const subscribe = (0, react.useCallback)((callback) => {
2618
- if (!clerk.loaded) return () => {};
2619
- return clerk.__internal_state.__internal_effect(() => {
2620
- signal();
2621
- callback();
2622
- });
2623
- }, [
2624
- signal,
2625
- clerk.loaded,
2626
- clerk.__internal_state
2627
- ]);
2628
- const getSnapshot = (0, react.useCallback)(() => {
2629
- return signal();
2630
- }, [signal]);
2631
- return (0, react.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
2632
- };
2633
-
2634
- //#endregion
2635
- //#region src/react/hooks/useCreditBalance.tsx
2636
- const HOOK_NAME$1 = "useCreditBalance";
2637
- /**
2638
- * @internal
2639
- */
2640
- function __internal_useCreditBalanceQuery(params) {
2641
- useAssertWrappedByClerkProvider(HOOK_NAME$1);
2642
- const clerk = useClerkInstanceContext();
2643
- const user = useUserBase();
2644
- const organization = useOrganizationBase();
2645
- const billingEnabled = useBillingIsEnabled(params);
2646
- const recordedRef = (0, react.useRef)(false);
2647
- (0, react.useEffect)(() => {
2648
- if (!recordedRef.current && clerk?.telemetry) {
2649
- clerk.telemetry.record(require_telemetry.eventMethodCalled(HOOK_NAME$1));
2650
- recordedRef.current = true;
2651
- }
2652
- }, [clerk]);
2653
- const keepPreviousData = params?.keepPreviousData ?? false;
2654
- const [queryClient] = useClerkQueryClient();
2655
- const { queryKey, invalidationKey, stableKey, authenticated } = (0, react.useMemo)(() => {
2656
- const safeOrgId = params?.for === "organization" ? organization?.id : void 0;
2657
- return createCacheKeys({
2658
- stablePrefix: STABLE_KEYS.CREDIT_BALANCE_KEY,
2659
- authenticated: true,
2660
- tracked: {
2661
- userId: user?.id,
2662
- orgId: safeOrgId
2663
- },
2664
- untracked: { args: { orgId: safeOrgId } }
2665
- });
2666
- }, [
2667
- user?.id,
2668
- organization?.id,
2669
- params?.for
2670
- ]);
2671
- const queriesEnabled = Boolean(user?.id && billingEnabled && (params?.enabled ?? true));
2672
- useClearQueriesOnSignOut({
2673
- isSignedOut: user === null,
2674
- authenticated,
2675
- stableKeys: stableKey
2676
- });
2677
- const query = useClerkQuery({
2678
- queryKey,
2679
- queryFn: ({ queryKey }) => {
2680
- const obj = queryKey[3];
2681
- return clerk.billing.getCreditBalance(obj.args);
2682
- },
2683
- staleTime: 1e3 * 60,
2684
- enabled: queriesEnabled,
2685
- placeholderData: defineKeepPreviousDataFn(keepPreviousData && queriesEnabled)
2686
- });
2687
- const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: invalidationKey }), [queryClient, invalidationKey]);
2688
- return {
2689
- data: query.data,
2690
- error: query.error ?? void 0,
2691
- isLoading: query.isLoading,
2692
- isFetching: query.isFetching,
2693
- revalidate
2694
- };
2695
- }
2696
-
2697
- //#endregion
2698
- //#region src/react/hooks/useCreditHistory.tsx
2699
- const HOOK_NAME = "useCreditHistory";
2700
- /**
2701
- * @internal
2702
- */
2703
- function __internal_useCreditHistoryQuery(params) {
2704
- useAssertWrappedByClerkProvider(HOOK_NAME);
2705
- const clerk = useClerkInstanceContext();
2706
- const user = useUserBase();
2707
- const organization = useOrganizationBase();
2708
- const billingEnabled = useBillingIsEnabled(params);
2709
- const recordedRef = (0, react.useRef)(false);
2710
- (0, react.useEffect)(() => {
2711
- if (!recordedRef.current && clerk?.telemetry) {
2712
- clerk.telemetry.record(require_telemetry.eventMethodCalled(HOOK_NAME));
2713
- recordedRef.current = true;
2714
- }
2715
- }, [clerk]);
2716
- const [queryClient] = useClerkQueryClient();
2717
- const { queryKey, invalidationKey, stableKey, authenticated } = (0, react.useMemo)(() => {
2718
- const safeOrgId = params?.for === "organization" ? organization?.id : void 0;
2719
- return createCacheKeys({
2720
- stablePrefix: INTERNAL_STABLE_KEYS.CREDIT_HISTORY_KEY,
2721
- authenticated: true,
2722
- tracked: {
2723
- userId: user?.id,
2724
- orgId: safeOrgId
2725
- },
2726
- untracked: { args: { orgId: safeOrgId } }
2727
- });
2728
- }, [
2729
- user?.id,
2730
- organization?.id,
2731
- params?.for
2732
- ]);
2733
- const queriesEnabled = Boolean(user?.id && billingEnabled && (params?.enabled ?? true));
2734
- useClearQueriesOnSignOut({
2735
- isSignedOut: user === null,
2736
- authenticated,
2737
- stableKeys: stableKey
2738
- });
2739
- const query = useClerkQuery({
2740
- queryKey,
2741
- queryFn: ({ queryKey }) => {
2742
- const obj = queryKey[3];
2743
- return clerk.billing.getCreditHistory(obj.args);
2744
- },
2745
- staleTime: 1e3 * 60,
2746
- enabled: queriesEnabled
2747
- });
2748
- const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: invalidationKey }), [queryClient, invalidationKey]);
2749
- return {
2750
- data: query.data,
2751
- error: query.error ?? void 0,
2752
- isLoading: query.isLoading,
2753
- isFetching: query.isFetching,
2754
- revalidate
2755
- };
2756
- }
2757
-
2758
- //#endregion
2759
- //#region src/react/hooks/useStatementQuery.shared.ts
2760
- function useStatementQueryCacheKeys(params) {
2761
- const { statementId, userId, orgId, for: forType } = params;
2762
- return (0, react.useMemo)(() => {
2763
- return createCacheKeys({
2764
- stablePrefix: INTERNAL_STABLE_KEYS.BILLING_STATEMENTS_KEY,
2765
- authenticated: true,
2766
- tracked: {
2767
- statementId,
2768
- forType,
2769
- userId,
2770
- orgId
2771
- },
2772
- untracked: { args: {
2773
- id: statementId ?? void 0,
2774
- orgId: orgId ?? void 0
2775
- } }
2776
- });
2777
- }, [
2778
- statementId,
2779
- forType,
2780
- userId,
2781
- orgId
2782
- ]);
2783
- }
2784
-
2785
- //#endregion
2786
- //#region src/react/hooks/useStatementQuery.tsx
2787
- /**
2788
- * @internal
2789
- */
2790
- function useStatementQuery(params = {}) {
2791
- const { statementId = null, keepPreviousData = false, for: forType = "user" } = params;
2792
- const clerk = useClerkInstanceContext();
2793
- const user = useUserBase();
2794
- const organization = useOrganizationBase();
2795
- const organizationId = forType === "organization" ? organization?.id ?? null : null;
2796
- const { queryKey, stableKey, authenticated } = useStatementQueryCacheKeys({
2797
- statementId,
2798
- userId: user?.id ?? null,
2799
- orgId: organizationId,
2800
- for: forType
2801
- });
2802
- const billingEnabled = useBillingIsEnabled(params);
2803
- const queryEnabled = Boolean(statementId) && billingEnabled;
2804
- useClearQueriesOnSignOut({
2805
- isSignedOut: user === null,
2806
- authenticated,
2807
- stableKeys: stableKey
2808
- });
2809
- const query = useClerkQuery({
2810
- queryKey,
2811
- queryFn: () => {
2812
- if (!statementId) throw new Error("statementId is required to fetch a statement");
2813
- return clerk.billing.getStatement({
2814
- id: statementId,
2815
- orgId: organizationId ?? void 0
2816
- });
2817
- },
2818
- enabled: queryEnabled,
2819
- placeholderData: defineKeepPreviousDataFn(keepPreviousData),
2820
- staleTime: 1e3 * 60
2821
- });
2822
- return {
2823
- data: query.data,
2824
- error: query.error ?? null,
2825
- isLoading: query.isLoading,
2826
- isFetching: query.isFetching
2827
- };
2828
- }
2829
-
2830
- //#endregion
2831
- //#region src/react/hooks/usePlanDetailsQuery.shared.ts
2832
- function usePlanDetailsQueryCacheKeys(params) {
2833
- const { planId } = params;
2834
- return (0, react.useMemo)(() => {
2835
- return createCacheKeys({
2836
- stablePrefix: INTERNAL_STABLE_KEYS.BILLING_PLANS_KEY,
2837
- authenticated: false,
2838
- tracked: { planId: planId ?? null },
2839
- untracked: { args: { id: planId ?? void 0 } }
2840
- });
2841
- }, [planId]);
2842
- }
2843
-
2844
- //#endregion
2845
- //#region src/react/hooks/usePlanDetailsQuery.tsx
2846
- /**
2847
- * @internal
2848
- */
2849
- function __internal_usePlanDetailsQuery(params = {}) {
2850
- const { planId, initialPlan = null, keepPreviousData = true } = params;
2851
- const clerk = useClerkInstanceContext();
2852
- const targetPlanId = planId ?? initialPlan?.id ?? null;
2853
- const { queryKey } = usePlanDetailsQueryCacheKeys({ planId: targetPlanId });
2854
- const billingEnabled = useBillingIsEnabled({ authenticated: false });
2855
- const query = useClerkQuery({
2856
- queryKey,
2857
- queryFn: () => {
2858
- if (!targetPlanId) throw new Error("planId is required to fetch plan details");
2859
- return clerk.billing.getPlan({ id: targetPlanId });
2860
- },
2861
- enabled: Boolean(targetPlanId) && billingEnabled,
2862
- initialData: initialPlan ?? void 0,
2863
- placeholderData: defineKeepPreviousDataFn(keepPreviousData),
2864
- initialDataUpdatedAt: 0
2865
- });
2866
- return {
2867
- data: query.data,
2868
- error: query.error ?? null,
2869
- isLoading: query.isLoading,
2870
- isFetching: query.isFetching
2871
- };
2872
- }
2873
-
2874
- //#endregion
2875
- //#region src/react/hooks/usePaymentAttemptQuery.shared.ts
2876
- function usePaymentAttemptQueryCacheKeys(params) {
2877
- const { paymentAttemptId, userId, orgId, for: forType } = params;
2878
- return (0, react.useMemo)(() => {
2879
- return createCacheKeys({
2880
- stablePrefix: INTERNAL_STABLE_KEYS.PAYMENT_ATTEMPT_KEY,
2881
- authenticated: true,
2882
- tracked: {
2883
- paymentAttemptId,
2884
- forType,
2885
- userId,
2886
- orgId
2887
- },
2888
- untracked: { args: {
2889
- id: paymentAttemptId ?? void 0,
2890
- orgId: orgId ?? void 0
2891
- } }
2892
- });
2893
- }, [
2894
- paymentAttemptId,
2895
- forType,
2896
- userId,
2897
- orgId
2898
- ]);
2899
- }
2900
-
2901
- //#endregion
2902
- //#region src/react/hooks/usePaymentAttemptQuery.tsx
2903
- /**
2904
- * @internal
2905
- */
2906
- function usePaymentAttemptQuery(params) {
2907
- const { paymentAttemptId, keepPreviousData = false, for: forType = "user" } = params;
2908
- const clerk = useClerkInstanceContext();
2909
- const user = useUserBase();
2910
- const organization = useOrganizationBase();
2911
- const organizationId = forType === "organization" ? organization?.id ?? null : null;
2912
- const { queryKey, stableKey, authenticated } = usePaymentAttemptQueryCacheKeys({
2913
- paymentAttemptId,
2914
- userId: user?.id ?? null,
2915
- orgId: organizationId,
2916
- for: forType
2917
- });
2918
- const billingEnabled = useBillingIsEnabled(params);
2919
- const queryEnabled = Boolean(paymentAttemptId) && billingEnabled;
2920
- useClearQueriesOnSignOut({
2921
- isSignedOut: user === null,
2922
- authenticated,
2923
- stableKeys: stableKey
2924
- });
2925
- const query = useClerkQuery({
2926
- queryKey,
2927
- queryFn: ({ queryKey }) => {
2928
- const args = queryKey[3].args;
2929
- return clerk.billing.getPaymentAttempt(args);
2930
- },
2931
- enabled: queryEnabled,
2932
- placeholderData: defineKeepPreviousDataFn(keepPreviousData),
2933
- staleTime: 1e3 * 60
2934
- });
2935
- return {
2936
- data: query.data,
2937
- error: query.error ?? null,
2938
- isLoading: query.isLoading,
2939
- isFetching: query.isFetching
2940
- };
2941
- }
2942
-
2943
- //#endregion
2944
- //#region src/react/hooks/useUserEnterpriseConnections.shared.ts
2945
- /**
2946
- * @internal
2947
- */
2948
- function useUserEnterpriseConnectionsCacheKeys(params) {
2949
- const { userId, withOrganizationAccountLinking = false } = params;
2950
- return (0, react.useMemo)(() => {
2951
- return createCacheKeys({
2952
- stablePrefix: INTERNAL_STABLE_KEYS.USER_ENTERPRISE_CONNECTIONS_KEY,
2953
- authenticated: Boolean(userId),
2954
- tracked: {
2955
- userId: userId ?? null,
2956
- withOrganizationAccountLinking
2957
- },
2958
- untracked: { args: {} }
2959
- });
2960
- }, [userId, withOrganizationAccountLinking]);
2961
- }
2962
-
2963
- //#endregion
2964
- //#region src/react/hooks/useUserEnterpriseConnections.tsx
2965
- /**
2966
- * Enterprise connections for the signed-in user
2967
- *
2968
- * @internal
2969
- */
2970
- function useUserEnterpriseConnections(params = {}) {
2971
- const { keepPreviousData = true, enabled = true, withOrganizationAccountLinking = false } = params;
2972
- const clerk = useClerkInstanceContext();
2973
- const user = useUserBase();
2974
- const [queryClient] = useClerkQueryClient();
2975
- const { queryKey, stableKey, authenticated } = useUserEnterpriseConnectionsCacheKeys({
2976
- userId: user?.id ?? null,
2977
- withOrganizationAccountLinking
2978
- });
2979
- const queryEnabled = enabled && clerk.loaded && Boolean(user);
2980
- useClearQueriesOnSignOut({
2981
- isSignedOut: user === null,
2982
- authenticated,
2983
- stableKeys: stableKey
2984
- });
2985
- const query = useClerkQuery({
2986
- queryKey,
2987
- queryFn: () => user?.getEnterpriseConnections({ withOrganizationAccountLinking }),
2988
- enabled: queryEnabled,
2989
- placeholderData: defineKeepPreviousDataFn(keepPreviousData)
2990
- });
2991
- const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: [stableKey] }), [queryClient, stableKey]);
2992
- return {
2993
- data: query.data,
2994
- error: query.error ?? null,
2995
- isLoading: query.isLoading,
2996
- isFetching: query.isFetching,
2997
- revalidate
2998
- };
2999
- }
3000
-
3001
- //#endregion
3002
- //#region src/react/hooks/useOrganizationEnterpriseConnections.shared.ts
3003
- /**
3004
- * @internal
3005
- */
3006
- function useOrganizationEnterpriseConnectionsCacheKeys(params) {
3007
- const { organizationId, withOrganizationAccountLinking = false } = params;
3008
- return (0, react.useMemo)(() => {
3009
- return createCacheKeys({
3010
- stablePrefix: INTERNAL_STABLE_KEYS.ORGANIZATION_ENTERPRISE_CONNECTIONS_KEY,
3011
- authenticated: Boolean(organizationId),
3012
- tracked: {
3013
- organizationId: organizationId ?? null,
3014
- withOrganizationAccountLinking
3015
- },
3016
- untracked: { args: {} }
3017
- });
3018
- }, [organizationId, withOrganizationAccountLinking]);
3019
- }
3020
-
3021
- //#endregion
3022
- //#region src/react/hooks/useOrganizationEnterpriseConnections.tsx
3023
- /**
3024
- * Enterprise connections for the active organization
3025
- *
3026
- * @internal
3027
- */
3028
- function useOrganizationEnterpriseConnections(params = {}) {
3029
- const { keepPreviousData = true, enabled = true, withOrganizationAccountLinking = false } = params;
3030
- const clerk = useClerkInstanceContext();
3031
- const organization = useOrganizationBase();
3032
- const [queryClient] = useClerkQueryClient();
3033
- const { queryKey, stableKey, authenticated } = useOrganizationEnterpriseConnectionsCacheKeys({
3034
- organizationId: organization?.id ?? null,
3035
- withOrganizationAccountLinking
3036
- });
3037
- const queryEnabled = enabled && clerk.loaded && Boolean(organization);
3038
- useClearQueriesOnSignOut({
3039
- isSignedOut: organization === null,
3040
- authenticated,
3041
- stableKeys: stableKey
3042
- });
3043
- const query = useClerkQuery({
3044
- queryKey,
3045
- queryFn: () => organization?.getEnterpriseConnections({ withOrganizationAccountLinking }),
3046
- enabled: queryEnabled,
3047
- placeholderData: defineKeepPreviousDataFn(keepPreviousData)
3048
- });
3049
- const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: [stableKey] }), [queryClient, stableKey]);
3050
- const createEnterpriseConnection = (0, react.useCallback)(async (createParams) => {
3051
- const created = await organization?.createEnterpriseConnection(createParams);
3052
- await revalidate();
3053
- return created;
3054
- }, [organization, revalidate]);
3055
- const updateEnterpriseConnection = (0, react.useCallback)(async (enterpriseConnectionId, updateParams) => {
3056
- const updated = await organization?.updateEnterpriseConnection(enterpriseConnectionId, updateParams);
3057
- await revalidate();
3058
- return updated;
3059
- }, [organization, revalidate]);
3060
- const deleteEnterpriseConnection = (0, react.useCallback)(async (enterpriseConnectionId) => {
3061
- const deleted = await organization?.deleteEnterpriseConnection(enterpriseConnectionId);
3062
- await revalidate();
3063
- return deleted;
3064
- }, [organization, revalidate]);
3065
- return {
3066
- data: query.data,
3067
- error: query.error ?? null,
3068
- isLoading: query.isLoading,
3069
- isFetching: query.isFetching,
3070
- createEnterpriseConnection,
3071
- updateEnterpriseConnection,
3072
- deleteEnterpriseConnection,
3073
- revalidate
3074
- };
3075
- }
3076
-
3077
- //#endregion
3078
- //#region src/react/hooks/useOrganizationDomains.shared.ts
3079
- /**
3080
- * @internal
3081
- */
3082
- function useOrganizationDomainsCacheKeys(params) {
3083
- const { organizationId, enrollmentMode } = params;
3084
- return (0, react.useMemo)(() => {
3085
- return createCacheKeys({
3086
- stablePrefix: INTERNAL_STABLE_KEYS.ORGANIZATION_DOMAINS_KEY,
3087
- authenticated: Boolean(organizationId),
3088
- tracked: {
3089
- organizationId: organizationId ?? null,
3090
- enrollmentMode: enrollmentMode ?? null
3091
- },
3092
- untracked: { args: {} }
3093
- });
3094
- }, [organizationId, enrollmentMode]);
3095
- }
3096
-
3097
- //#endregion
3098
- //#region src/react/hooks/useOrganizationDomains.tsx
3099
- const OWNERSHIP_VERIFICATION_POLL_INTERVAL_MS = 1e4;
3100
- /**
3101
- * Domains for the active organization.
3102
- *
3103
- * @internal
3104
- */
3105
- function useOrganizationDomains(params = {}) {
3106
- const { keepPreviousData = true, enabled = true, enrollmentMode, onOwnershipVerified } = params;
3107
- const clerk = useClerkInstanceContext();
3108
- const organization = useOrganizationBase();
3109
- const [queryClient] = useClerkQueryClient();
3110
- const onOwnershipVerifiedRef = (0, react.useRef)(onOwnershipVerified);
3111
- onOwnershipVerifiedRef.current = onOwnershipVerified;
3112
- const { queryKey, stableKey, authenticated } = useOrganizationDomainsCacheKeys({
3113
- organizationId: organization?.id ?? null,
3114
- enrollmentMode
3115
- });
3116
- const queryEnabled = enabled && clerk.loaded && Boolean(organization);
3117
- useClearQueriesOnSignOut({
3118
- isSignedOut: organization === null,
3119
- authenticated,
3120
- stableKeys: stableKey
3121
- });
3122
- const fetchParams = enrollmentMode ? { enrollmentMode } : void 0;
3123
- const query = useClerkQuery({
3124
- queryKey,
3125
- queryFn: () => organization?.getDomains(fetchParams),
3126
- enabled: queryEnabled,
3127
- placeholderData: defineKeepPreviousDataFn(keepPreviousData)
3128
- });
3129
- const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: [stableKey] }), [queryClient, stableKey]);
3130
- const createDomain = (0, react.useCallback)(async (name) => {
3131
- let created = await organization?.createDomain(name, enrollmentMode ? { enrollmentMode } : void 0);
3132
- if (created && enrollmentMode === "enterprise_sso") created = (await organization?.prepareOwnershipVerification([created.id]))?.data[0] ?? created;
3133
- await revalidate();
3134
- return created;
3135
- }, [
3136
- organization,
3137
- revalidate,
3138
- enrollmentMode
3139
- ]);
3140
- const prepareOwnershipVerification = (0, react.useCallback)(async (domains) => {
3141
- const prepared = await organization?.prepareOwnershipVerification(domains.map((domain) => domain.id));
3142
- await revalidate();
3143
- return prepared;
3144
- }, [organization, revalidate]);
3145
- const attemptOwnershipVerification = (0, react.useCallback)(async (domains) => {
3146
- const attempted = await organization?.attemptOwnershipVerification(domains.map((domain) => domain.id));
3147
- await revalidate();
3148
- return attempted;
3149
- }, [organization, revalidate]);
3150
- const response = query.data;
3151
- const unverifiedOwnershipKey = (0, react.useMemo)(() => (response?.data ?? []).filter((domain) => domain.ownershipVerification?.status === "unverified").map((domain) => domain.id), [response?.data]).join(",");
3152
- (0, react.useEffect)(() => {
3153
- if (!queryEnabled || !organization || !unverifiedOwnershipKey) return;
3154
- let cancelled = false;
3155
- let timeoutId;
3156
- const scheduleNext = () => {
3157
- timeoutId = setTimeout(() => void runAttempt(), OWNERSHIP_VERIFICATION_POLL_INTERVAL_MS);
3158
- };
3159
- const domainIds = unverifiedOwnershipKey.split(",");
3160
- const runAttempt = async () => {
3161
- const result = await organization.attemptOwnershipVerification(domainIds).catch((error) => {
3162
- require_logger.logger.warnOnce(`Clerk: failed to attempt organization domain ownership verification: ${error}`);
3163
- });
3164
- if (cancelled) return;
3165
- await revalidate();
3166
- if (cancelled) return;
3167
- const verifiedDomains = result?.data.filter((domain) => domain.ownershipVerification?.status === "verified") ?? [];
3168
- if (verifiedDomains.length) await onOwnershipVerifiedRef.current?.(verifiedDomains);
3169
- if (cancelled) return;
3170
- if (!!result?.data.length && result.data.every((domain) => domain.ownershipVerification?.status === "verified")) return;
3171
- scheduleNext();
3172
- };
3173
- scheduleNext();
3174
- return () => {
3175
- cancelled = true;
3176
- clearTimeout(timeoutId);
3177
- };
3178
- }, [unverifiedOwnershipKey, queryEnabled]);
3179
- return {
3180
- data: response?.data,
3181
- totalCount: response?.total_count,
3182
- error: query.error ?? null,
3183
- isLoading: query.isLoading,
3184
- isFetching: query.isFetching,
3185
- createDomain,
3186
- prepareOwnershipVerification,
3187
- attemptOwnershipVerification,
3188
- revalidate
3189
- };
3190
- }
3191
-
3192
- //#endregion
3193
- //#region src/react/hooks/useOrganizationDirectorySync.shared.ts
3194
- /**
3195
- * @internal
3196
- */
3197
- function useOrganizationDirectorySyncCacheKeys(params) {
3198
- const { organizationId, enterpriseConnectionId } = params;
3199
- return (0, react.useMemo)(() => {
3200
- return createCacheKeys({
3201
- stablePrefix: INTERNAL_STABLE_KEYS.ORGANIZATION_DIRECTORY_SYNC_KEY,
3202
- authenticated: Boolean(organizationId),
3203
- tracked: {
3204
- organizationId: organizationId ?? null,
3205
- enterpriseConnectionId: enterpriseConnectionId ?? null
3206
- },
3207
- untracked: { args: {} }
3208
- });
3209
- }, [organizationId, enterpriseConnectionId]);
3210
- }
3211
- /**
3212
- * @internal
3213
- */
3214
- function useOrganizationDirectorySyncUsersCacheKeys(params) {
3215
- const { organizationId, enterpriseConnectionId, directoryId, args } = params;
3216
- return (0, react.useMemo)(() => {
3217
- return createCacheKeys({
3218
- stablePrefix: INTERNAL_STABLE_KEYS.ORGANIZATION_DIRECTORY_SYNC_USERS_KEY,
3219
- authenticated: Boolean(organizationId),
3220
- tracked: {
3221
- organizationId: organizationId ?? null,
3222
- enterpriseConnectionId: enterpriseConnectionId ?? null,
3223
- directoryId: directoryId ?? null
3224
- },
3225
- untracked: { args }
3226
- });
3227
- }, [
3228
- organizationId,
3229
- enterpriseConnectionId,
3230
- directoryId,
3231
- JSON.stringify(args)
3232
- ]);
3233
- }
3234
- /**
3235
- * @internal
3236
- */
3237
- function useOrganizationDirectorySyncStatusCacheKeys(params) {
3238
- const { organizationId, enterpriseConnectionId, directoryId } = params;
3239
- return (0, react.useMemo)(() => {
3240
- return createCacheKeys({
3241
- stablePrefix: INTERNAL_STABLE_KEYS.ORGANIZATION_DIRECTORY_SYNC_STATUS_KEY,
3242
- authenticated: Boolean(organizationId),
3243
- tracked: {
3244
- organizationId: organizationId ?? null,
3245
- enterpriseConnectionId: enterpriseConnectionId ?? null,
3246
- directoryId: directoryId ?? null
3247
- },
3248
- untracked: { args: {} }
3249
- });
3250
- }, [
3251
- organizationId,
3252
- enterpriseConnectionId,
3253
- directoryId
3254
- ]);
3255
- }
3256
- /**
3257
- * @internal
3258
- */
3259
- function useOrganizationDirectorySyncGroupRoleMappingsCacheKeys(params) {
3260
- const { organizationId, enterpriseConnectionId, directoryId } = params;
3261
- return (0, react.useMemo)(() => {
3262
- return createCacheKeys({
3263
- stablePrefix: INTERNAL_STABLE_KEYS.ORGANIZATION_DIRECTORY_SYNC_GROUP_ROLE_MAPPINGS_KEY,
3264
- authenticated: Boolean(organizationId),
3265
- tracked: {
3266
- organizationId: organizationId ?? null,
3267
- enterpriseConnectionId: enterpriseConnectionId ?? null,
3268
- directoryId: directoryId ?? null
3269
- },
3270
- untracked: { args: {} }
3271
- });
3272
- }, [
3273
- organizationId,
3274
- enterpriseConnectionId,
3275
- directoryId
3276
- ]);
3277
- }
3278
-
3279
- //#endregion
3280
- //#region src/react/hooks/useOrganizationDirectorySync.tsx
3281
- /**
3282
- * The Directory Sync directory bound to an enterprise connection of the active organization.
3283
- *
3284
- * @internal
3285
- */
3286
- function useOrganizationDirectorySync(params) {
3287
- const { enterpriseConnectionId, enabled = true } = params;
3288
- const clerk = useClerkInstanceContext();
3289
- const organization = useOrganizationBase();
3290
- const [queryClient] = useClerkQueryClient();
3291
- const { queryKey, invalidationKey, stableKey, authenticated } = useOrganizationDirectorySyncCacheKeys({
3292
- organizationId: organization?.id ?? null,
3293
- enterpriseConnectionId
3294
- });
3295
- const queryEnabled = enabled && clerk.loaded && Boolean(organization) && Boolean(enterpriseConnectionId);
3296
- useClearQueriesOnSignOut({
3297
- isSignedOut: organization === null,
3298
- authenticated,
3299
- stableKeys: stableKey
3300
- });
3301
- const query = useClerkQuery({
3302
- queryKey,
3303
- queryFn: async () => {
3304
- if (!enterpriseConnectionId) throw new Error("enterpriseConnectionId is required to fetch the directory");
3305
- try {
3306
- return await organization?.getDirectorySync(enterpriseConnectionId) ?? null;
3307
- } catch (err) {
3308
- if (require_error.isClerkAPIResponseError(err) && err.status === 404) return null;
3309
- throw err;
3310
- }
3311
- },
3312
- enabled: queryEnabled
3313
- });
3314
- const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: invalidationKey }), [queryClient, invalidationKey]);
3315
- const createDirectorySync = (0, react.useCallback)(async (createParams) => {
3316
- if (!enterpriseConnectionId) return;
3317
- const created = await organization?.createDirectorySync(enterpriseConnectionId, createParams);
3318
- await revalidate();
3319
- return created;
3320
- }, [
3321
- organization,
3322
- enterpriseConnectionId,
3323
- revalidate
3324
- ]);
3325
- const directory = query.data;
3326
- const updateDirectorySync = (0, react.useCallback)(async (updateParams) => {
3327
- if (!directory) return;
3328
- const updated = await directory.update(updateParams);
3329
- await revalidate();
3330
- return updated;
3331
- }, [directory, revalidate]);
3332
- const rotateDirectorySyncToken = (0, react.useCallback)(async () => {
3333
- if (!directory) return;
3334
- const rotated = await directory.rotateToken();
3335
- await revalidate();
3336
- return rotated;
3337
- }, [directory, revalidate]);
3338
- const setDirectorySyncCredentials = (0, react.useCallback)(async (credentialsParams) => {
3339
- if (!directory) return;
3340
- const updated = await directory.setCredentials(credentialsParams);
3341
- await revalidate();
3342
- return updated;
3343
- }, [directory, revalidate]);
3344
- const syncDirectory = (0, react.useCallback)(async () => {
3345
- if (!directory) return;
3346
- await directory.sync();
3347
- }, [directory]);
3348
- const deleteDirectorySync = (0, react.useCallback)(async () => {
3349
- if (!directory) return;
3350
- const deleted = await directory.delete();
3351
- await revalidate();
3352
- return deleted;
3353
- }, [directory, revalidate]);
3354
- return {
3355
- data: query.data,
3356
- error: query.error ?? null,
3357
- isLoading: query.isLoading,
3358
- isFetching: query.isFetching,
3359
- createDirectorySync,
3360
- updateDirectorySync,
3361
- rotateDirectorySyncToken,
3362
- setDirectorySyncCredentials,
3363
- syncDirectory,
3364
- deleteDirectorySync,
3365
- revalidate
3366
- };
3367
- }
3368
-
3369
- //#endregion
3370
- //#region src/react/hooks/useOrganizationDirectorySyncUsers.tsx
3371
- const DEFAULT_POLL_INTERVAL_MS$2 = 2e3;
3372
- /**
3373
- * The users provisioned into an enterprise connection's Directory Sync
3374
- * directory, most recently touched first. Polling is opt-in via `poll`, which
3375
- * lets the setup flow use the list as a live activity feed.
3376
- *
3377
- * @internal
3378
- */
3379
- function useOrganizationDirectorySyncUsers(params) {
3380
- const { directory, params: fetchParams = {
3381
- initialPage: 1,
3382
- pageSize: 10
3383
- }, poll = false, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS$2, enabled = true, keepPreviousData = true } = params;
3384
- const clerk = useClerkInstanceContext();
3385
- const organization = useOrganizationBase();
3386
- const [queryClient] = useClerkQueryClient();
3387
- const enterpriseConnectionId = directory?.enterpriseConnectionId ?? null;
3388
- const directoryId = directory?.id ?? null;
3389
- const { queryKey, invalidationKey, stableKey, authenticated } = useOrganizationDirectorySyncUsersCacheKeys({
3390
- organizationId: organization?.id ?? null,
3391
- enterpriseConnectionId,
3392
- directoryId,
3393
- args: fetchParams
3394
- });
3395
- useClearQueriesOnSignOut({
3396
- isSignedOut: organization === null,
3397
- authenticated,
3398
- stableKeys: stableKey
3399
- });
3400
- const queryEnabled = enabled && clerk.loaded && Boolean(organization) && Boolean(directory);
3401
- const currentTracked = queryKey[2];
3402
- const query = useClerkQuery({
3403
- queryKey,
3404
- queryFn: () => {
3405
- if (!directory) throw new Error("directory is required to fetch directory users");
3406
- return directory.getUsers(fetchParams);
3407
- },
3408
- refetchInterval: () => poll ? pollIntervalMs : false,
3409
- enabled: queryEnabled,
3410
- refetchIntervalInBackground: false,
3411
- placeholderData: keepPreviousData ? (previousData, previousQuery) => {
3412
- const previousTracked = previousQuery?.queryKey[2];
3413
- return Boolean(currentTracked.organizationId) && Boolean(currentTracked.directoryId) && previousTracked?.organizationId === currentTracked.organizationId && previousTracked?.directoryId === currentTracked.directoryId ? previousData : void 0;
3414
- } : void 0
3415
- });
3416
- const revalidate = (0, react.useCallback)(async () => {
3417
- await queryClient.invalidateQueries({ queryKey: invalidationKey });
3418
- }, [queryClient, invalidationKey]);
3419
- const isPolling = queryEnabled && poll;
3420
- return {
3421
- data: queryEnabled ? query.data?.data : void 0,
3422
- totalCount: queryEnabled ? query.data?.total_count : void 0,
3423
- error: query.error ?? null,
3424
- isLoading: query.isLoading,
3425
- isFetching: query.isFetching,
3426
- isPolling,
3427
- revalidate
3428
- };
3429
- }
3430
-
3431
- //#endregion
3432
- //#region src/react/hooks/useOrganizationDirectorySyncStatus.tsx
3433
- const DEFAULT_POLL_INTERVAL_MS$1 = 2e3;
3434
- /**
3435
- * The result of a Directory Sync directory's most recent sync.
3436
- *
3437
- * Only pull-based directories sync, so this stays dormant for push providers,
3438
- * which are driven by the identity provider and have no sync to report.
3439
- *
3440
- * @internal
3441
- */
3442
- function useOrganizationDirectorySyncStatus(params) {
3443
- const { directory, poll = false, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS$1, enabled = true } = params;
3444
- const clerk = useClerkInstanceContext();
3445
- const organization = useOrganizationBase();
3446
- const [queryClient] = useClerkQueryClient();
3447
- const enterpriseConnectionId = directory?.enterpriseConnectionId ?? null;
3448
- const directoryId = directory?.id ?? null;
3449
- const { queryKey, invalidationKey, stableKey, authenticated } = useOrganizationDirectorySyncStatusCacheKeys({
3450
- organizationId: organization?.id ?? null,
3451
- enterpriseConnectionId,
3452
- directoryId
3453
- });
3454
- useClearQueriesOnSignOut({
3455
- isSignedOut: organization === null,
3456
- authenticated,
3457
- stableKeys: stableKey
3458
- });
3459
- const belongsToActiveOrganization = Boolean(organization) && directory?.organizationId === organization?.id;
3460
- const queryEnabled = enabled && clerk.loaded && belongsToActiveOrganization && Boolean(directory);
3461
- const query = useClerkQuery({
3462
- queryKey,
3463
- queryFn: () => {
3464
- if (!directory) throw new Error("directory is required to fetch sync status");
3465
- return directory.getSyncStatus();
3466
- },
3467
- refetchInterval: () => poll ? pollIntervalMs : false,
3468
- enabled: queryEnabled,
3469
- refetchIntervalInBackground: false
3470
- });
3471
- const revalidate = (0, react.useCallback)(async () => {
3472
- await queryClient.invalidateQueries({ queryKey: invalidationKey });
3473
- }, [queryClient, invalidationKey]);
3474
- return {
3475
- data: queryEnabled ? query.data : void 0,
3476
- error: query.error ?? null,
3477
- isLoading: query.isLoading,
3478
- isFetching: query.isFetching,
3479
- isPolling: queryEnabled && poll,
3480
- revalidate
3481
- };
3482
- }
3483
-
3484
- //#endregion
3485
- //#region src/react/hooks/useOrganizationDirectorySyncGroupRoleMappings.tsx
3486
- const GROUPS_PAGE_SIZE = 500;
3487
- const fetchAllGroups = async (directory) => {
3488
- const groups = [];
3489
- let startingAfter;
3490
- do {
3491
- const page = await directory.getGroups({
3492
- limit: GROUPS_PAGE_SIZE,
3493
- startingAfter
3494
- });
3495
- groups.push(...page.data);
3496
- startingAfter = page.hasNextPage && page.startingAfter ? page.startingAfter : void 0;
3497
- } while (startingAfter);
3498
- return groups;
3499
- };
3500
- /**
3501
- * The groups a Directory Sync directory has received, its group role mappings, and the organization's
3502
- * default role, loaded together because the mapping editor needs all three.
3503
- *
3504
- * @internal
3505
- */
3506
- function useOrganizationDirectorySyncGroupRoleMappings(params) {
3507
- const { directory, enabled = true } = params;
3508
- const clerk = useClerkInstanceContext();
3509
- const organization = useOrganizationBase();
3510
- const [queryClient] = useClerkQueryClient();
3511
- const { queryKey, invalidationKey, stableKey, authenticated } = useOrganizationDirectorySyncGroupRoleMappingsCacheKeys({
3512
- organizationId: organization?.id ?? null,
3513
- enterpriseConnectionId: directory?.enterpriseConnectionId ?? null,
3514
- directoryId: directory?.id ?? null
3515
- });
3516
- useClearQueriesOnSignOut({
3517
- isSignedOut: organization === null,
3518
- authenticated,
3519
- stableKeys: stableKey
3520
- });
3521
- const belongsToActiveOrganization = Boolean(organization) && directory?.organizationId === organization?.id;
3522
- const queryEnabled = enabled && clerk.loaded && belongsToActiveOrganization && Boolean(directory);
3523
- const query = useClerkQuery({
3524
- queryKey,
3525
- queryFn: async () => {
3526
- if (!directory) throw new Error("directory is required to fetch group role mappings");
3527
- const [groups, mappings] = await Promise.all([fetchAllGroups(directory), directory.getGroupRoleMappings()]);
3528
- return {
3529
- groups,
3530
- mappings: mappings.data,
3531
- defaultRole: mappings.defaultRole
3532
- };
3533
- },
3534
- enabled: queryEnabled
3535
- });
3536
- const revalidate = (0, react.useCallback)(async () => {
3537
- await queryClient.invalidateQueries({ queryKey: invalidationKey });
3538
- }, [queryClient, invalidationKey]);
3539
- const replaceGroupRoleMappings = (0, react.useCallback)(async (replaceParams) => {
3540
- if (!directory) return;
3541
- const replaced = await directory.replaceGroupRoleMappings(replaceParams);
3542
- queryClient.setQueryData(queryKey, (previous) => previous ? {
3543
- ...previous,
3544
- mappings: replaced.data,
3545
- defaultRole: replaced.defaultRole
3546
- } : previous);
3547
- return replaced.data;
3548
- }, [
3549
- directory,
3550
- queryClient,
3551
- queryKey
3552
- ]);
3553
- return {
3554
- data: queryEnabled ? query.data : void 0,
3555
- error: query.error ?? null,
3556
- isLoading: query.isLoading,
3557
- isFetching: query.isFetching,
3558
- replaceGroupRoleMappings,
3559
- revalidate
3560
- };
3561
- }
3562
-
3563
- //#endregion
3564
- //#region src/react/hooks/useOrganizationEnterpriseConnectionTestRuns.shared.ts
3565
- /**
3566
- * @internal
3567
- */
3568
- function useOrganizationEnterpriseConnectionTestRunsCacheKeys(params) {
3569
- const { organizationId, enterpriseConnectionId, args } = params;
3570
- return (0, react.useMemo)(() => {
3571
- return createCacheKeys({
3572
- stablePrefix: INTERNAL_STABLE_KEYS.ORGANIZATION_ENTERPRISE_CONNECTION_TEST_RUNS_KEY,
3573
- authenticated: Boolean(organizationId),
3574
- tracked: {
3575
- organizationId: organizationId ?? null,
3576
- enterpriseConnectionId: enterpriseConnectionId ?? null
3577
- },
3578
- untracked: { args }
3579
- });
3580
- }, [
3581
- organizationId,
3582
- enterpriseConnectionId,
3583
- JSON.stringify(args)
3584
- ]);
3585
- }
3586
-
3587
- //#endregion
3588
- //#region src/react/hooks/useOrganizationEnterpriseConnectionTestRuns.tsx
3589
- const DEFAULT_POLL_INTERVAL_MS = 2e3;
3590
- /**
3591
- * Subscribes to the list of enterprise-connection test runs for the active organization
3592
- *
3593
- * @internal
3594
- */
3595
- function useOrganizationEnterpriseConnectionTestRuns(params) {
3596
- const { enterpriseConnectionId, params: fetchParams = {
3597
- initialPage: 1,
3598
- pageSize: 10
3599
- }, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, enabled = true, keepPreviousData = false } = params;
3600
- const clerk = useClerkInstanceContext();
3601
- const organization = useOrganizationBase();
3602
- const [queryClient] = useClerkQueryClient();
3603
- const { queryKey, invalidationKey, stableKey, authenticated } = useOrganizationEnterpriseConnectionTestRunsCacheKeys({
3604
- organizationId: organization?.id ?? null,
3605
- enterpriseConnectionId,
3606
- args: fetchParams
3607
- });
3608
- useClearQueriesOnSignOut({
3609
- isSignedOut: organization === null,
3610
- authenticated,
3611
- stableKeys: stableKey
3612
- });
3613
- const queryEnabled = enabled && clerk.loaded && Boolean(organization) && Boolean(enterpriseConnectionId);
3614
- const [pollingConnectionId, setPollingConnectionId] = (0, react.useState)(null);
3615
- const shouldPoll = pollingConnectionId !== null && pollingConnectionId === enterpriseConnectionId;
3616
- (0, react.useEffect)(() => {
3617
- setPollingConnectionId((current) => current !== null && current !== enterpriseConnectionId ? null : current);
3618
- }, [enterpriseConnectionId]);
3619
- const query = useClerkQuery({
3620
- queryKey,
3621
- queryFn: () => {
3622
- if (!enterpriseConnectionId) throw new Error("enterpriseConnectionId is required to fetch test runs");
3623
- return organization?.getEnterpriseConnectionTestRuns(enterpriseConnectionId, fetchParams);
3624
- },
3625
- refetchInterval: (q) => {
3626
- if (!shouldPoll) return false;
3627
- return (q.state.data?.data?.length ?? 0) > 0 ? false : pollIntervalMs;
3628
- },
3629
- enabled: queryEnabled,
3630
- refetchIntervalInBackground: false,
3631
- placeholderData: defineKeepPreviousDataFn(keepPreviousData)
3632
- });
3633
- const hasRows = (query.data?.data?.length ?? 0) > 0;
3634
- (0, react.useEffect)(() => {
3635
- if (shouldPoll && hasRows) setPollingConnectionId(null);
3636
- }, [shouldPoll, hasRows]);
3637
- const revalidate = (0, react.useCallback)(async (options) => {
3638
- if ((options?.armPolling ?? true) && !hasRows) setPollingConnectionId(enterpriseConnectionId);
3639
- if (options?.exact) await queryClient.invalidateQueries({
3640
- queryKey,
3641
- exact: true
3642
- });
3643
- else await queryClient.invalidateQueries({ queryKey: invalidationKey });
3644
- const fresh = queryClient.getQueryData(queryKey);
3645
- return {
3646
- data: fresh?.data,
3647
- totalCount: fresh?.total_count
3648
- };
3649
- }, [
3650
- queryClient,
3651
- invalidationKey,
3652
- queryKey,
3653
- hasRows,
3654
- enterpriseConnectionId
3655
- ]);
3656
- const isPolling = queryEnabled && shouldPoll && !hasRows;
3657
- return {
3658
- data: query.data?.data,
3659
- totalCount: query.data?.total_count,
3660
- error: query.error ?? null,
3661
- isLoading: query.isLoading,
3662
- isFetching: query.isFetching,
3663
- isPolling,
3664
- revalidate
3665
- };
3666
- }
3667
-
3668
- //#endregion
3669
- //#region src/react/hooks/useOrganizationSSOBypassAllowlist.shared.ts
3670
- /**
3671
- * @internal
3672
- */
3673
- function useOrganizationSSOBypassAllowlistCacheKeys(params) {
3674
- const { organizationId } = params;
3675
- return (0, react.useMemo)(() => {
3676
- return createCacheKeys({
3677
- stablePrefix: INTERNAL_STABLE_KEYS.ORGANIZATION_SSO_BYPASS_ALLOWLIST_KEY,
3678
- authenticated: Boolean(organizationId),
3679
- tracked: { organizationId: organizationId ?? null },
3680
- untracked: { args: {} }
3681
- });
3682
- }, [organizationId]);
3683
- }
3684
-
3685
- //#endregion
3686
- //#region src/react/hooks/useOrganizationSSOBypassAllowlist.tsx
3687
- /**
3688
- * The SSO bypass allowlist of the active organization
3689
- *
3690
- * @internal
3691
- */
3692
- function useOrganizationSSOBypassAllowlist(params = {}) {
3693
- const { keepPreviousData = false, enabled = true } = params;
3694
- const clerk = useClerkInstanceContext();
3695
- const organization = useOrganizationBase();
3696
- const [queryClient] = useClerkQueryClient();
3697
- const { queryKey, stableKey, authenticated } = useOrganizationSSOBypassAllowlistCacheKeys({ organizationId: organization?.id ?? null });
3698
- const queryEnabled = enabled && clerk.loaded && Boolean(organization);
3699
- useClearQueriesOnSignOut({
3700
- isSignedOut: organization === null,
3701
- authenticated,
3702
- stableKeys: stableKey
3703
- });
3704
- const query = useClerkQuery({
3705
- queryKey,
3706
- queryFn: () => organization?.ssoBypassAllowlist.getUsers(),
3707
- enabled: queryEnabled,
3708
- placeholderData: defineKeepPreviousDataFn(keepPreviousData)
3709
- });
3710
- const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: [stableKey] }), [queryClient, stableKey]);
3711
- const addUser = (0, react.useCallback)(async (addParams) => {
3712
- const added = await organization?.ssoBypassAllowlist.addUser(addParams);
3713
- await revalidate();
3714
- return added;
3715
- }, [organization, revalidate]);
3716
- const addUsers = (0, react.useCallback)(async (addParams) => {
3717
- try {
3718
- return await organization?.ssoBypassAllowlist.addUsers(addParams);
3719
- } finally {
3720
- await revalidate();
3721
- }
3722
- }, [organization, revalidate]);
3723
- const removeUser = (0, react.useCallback)(async (userId) => {
3724
- const removed = await organization?.ssoBypassAllowlist.removeUser(userId);
3725
- await revalidate();
3726
- return removed;
3727
- }, [organization, revalidate]);
3728
- return {
3729
- data: query.data,
3730
- error: query.error ?? null,
3731
- isLoading: query.isLoading,
3732
- isFetching: query.isFetching,
3733
- addUser,
3734
- addUsers,
3735
- removeUser,
3736
- revalidate
3737
- };
3738
- }
3739
-
3740
- //#endregion
3741
- //#region src/react/utils.ts
3742
- function assertClerkSingletonExists(clerk) {
3743
- if (!clerk) require_internal_clerk_js_errors.clerkCoreErrorNoClerkSingleton();
3744
- }
3745
-
3746
- //#endregion
3747
- //#region src/react/ClerkContextProvider.tsx
3748
- function ClerkContextProvider(props) {
3749
- const clerk = props.clerk;
3750
- assertClerkSingletonExists(clerk);
3751
- if (props.initialState instanceof Promise && !("use" in react.default && typeof react.default.use === "function")) throw new Error("initialState cannot be a promise if React version is less than 19");
3752
- const clerkCtx = react.default.useMemo(() => ({ value: clerk }), [props.clerkStatus]);
3753
- return /* @__PURE__ */ react.default.createElement(InitialStateProvider, { initialState: props.initialState }, /* @__PURE__ */ react.default.createElement(ClerkInstanceContext.Provider, { value: clerkCtx }, /* @__PURE__ */ react.default.createElement(__experimental_CheckoutProvider, { value: void 0 }, props.children)));
3754
- }
3755
-
3756
- //#endregion
3757
- //#region src/react/stripe-react/utils.ts
3758
- const usePrevious = (value) => {
3759
- const ref = (0, react.useRef)(value);
3760
- (0, react.useEffect)(() => {
3761
- ref.current = value;
3762
- }, [value]);
3763
- return ref.current;
3764
- };
3765
- const useAttachEvent = (element, event, cb) => {
3766
- const cbDefined = !!cb;
3767
- const cbRef = (0, react.useRef)(cb);
3768
- (0, react.useEffect)(() => {
3769
- cbRef.current = cb;
3770
- }, [cb]);
3771
- (0, react.useEffect)(() => {
3772
- if (!cbDefined || !element) return () => {};
3773
- const decoratedCb = (...args) => {
3774
- if (cbRef.current) cbRef.current(...args);
3775
- };
3776
- element.on(event, decoratedCb);
3777
- return () => {
3778
- element.off(event, decoratedCb);
3779
- };
3780
- }, [
3781
- cbDefined,
3782
- event,
3783
- element,
3784
- cbRef
3785
- ]);
3786
- };
3787
-
3788
- //#endregion
3789
- //#region src/react/stripe-react/index.tsx
3790
- const ElementsContext = react.default.createContext(null);
3791
- ElementsContext.displayName = "ElementsContext";
3792
- const parseElementsContext = (ctx, useCase) => {
3793
- if (!ctx) throw new Error(`Could not find Elements context; You need to wrap the part of your app that ${useCase} in an <Elements> provider.`);
3794
- return ctx;
3795
- };
3796
- /**
3797
- * The `Elements` provider allows you to use [Element components](https://stripe.com/docs/stripe-js/react#element-components) and access the [Stripe object](https://stripe.com/docs/js/initializing) in any nested component.
3798
- * Render an `Elements` provider at the root of your React app so that it is available everywhere you need it.
3799
- *
3800
- * To use the `Elements` provider, call `loadStripe` from `@stripe/stripe-js` with your publishable key.
3801
- * The `loadStripe` function will asynchronously load the Stripe.js script and initialize a `Stripe` object.
3802
- * Pass the returned `Promise` to `Elements`.
3803
- *
3804
- * @docs https://stripe.com/docs/stripe-js/react#elements-provider
3805
- */
3806
- const Elements = (({ stripe: rawStripeProp, options, children }) => {
3807
- const parsed = react.default.useMemo(() => parseStripeProp(rawStripeProp), [rawStripeProp]);
3808
- const [ctx, setContext] = react.default.useState(() => ({
3809
- stripe: parsed.tag === "sync" ? parsed.stripe : null,
3810
- elements: parsed.tag === "sync" ? parsed.stripe.elements(options) : null
3811
- }));
3812
- react.default.useEffect(() => {
3813
- let isMounted = true;
3814
- const safeSetContext = (stripe) => {
3815
- setContext((ctx) => {
3816
- if (ctx.stripe) return ctx;
3817
- return {
3818
- stripe,
3819
- elements: stripe.elements(options)
3820
- };
3821
- });
3822
- };
3823
- if (parsed.tag === "async" && !ctx.stripe) parsed.stripePromise.then((stripe) => {
3824
- if (stripe && isMounted) safeSetContext(stripe);
3825
- });
3826
- else if (parsed.tag === "sync" && !ctx.stripe) safeSetContext(parsed.stripe);
3827
- return () => {
3828
- isMounted = false;
3829
- };
3830
- }, [
3831
- parsed,
3832
- ctx,
3833
- options
3834
- ]);
3835
- const prevStripe = usePrevious(rawStripeProp);
3836
- react.default.useEffect(() => {
3837
- if (prevStripe !== null && prevStripe !== rawStripeProp) console.warn("Unsupported prop change on Elements: You cannot change the `stripe` prop after setting it.");
3838
- }, [prevStripe, rawStripeProp]);
3839
- const prevOptions = usePrevious(options);
3840
- react.default.useEffect(() => {
3841
- if (!ctx.elements) return;
3842
- const updates = extractAllowedOptionsUpdates(options, prevOptions, ["clientSecret", "fonts"]);
3843
- if (updates) ctx.elements.update(updates);
3844
- }, [
3845
- options,
3846
- prevOptions,
3847
- ctx.elements
3848
- ]);
3849
- return /* @__PURE__ */ react.default.createElement(ElementsContext.Provider, { value: ctx }, children);
3850
- });
3851
- const useElementsContextWithUseCase = (useCaseMessage) => {
3852
- return parseElementsContext(react.default.useContext(ElementsContext), useCaseMessage);
3853
- };
3854
- const useElements = () => {
3855
- const { elements } = useElementsContextWithUseCase("calls useElements()");
3856
- return elements;
3857
- };
3858
- const INVALID_STRIPE_ERROR = "Invalid prop `stripe` supplied to `Elements`. We recommend using the `loadStripe` utility from `@stripe/stripe-js`. See https://stripe.com/docs/stripe-js/react#elements-props-stripe for details.";
3859
- const validateStripe = (maybeStripe, errorMsg = INVALID_STRIPE_ERROR) => {
3860
- if (maybeStripe === null || isStripe(maybeStripe)) return maybeStripe;
3861
- throw new Error(errorMsg);
3862
- };
3863
- const parseStripeProp = (raw, errorMsg = INVALID_STRIPE_ERROR) => {
3864
- if (isPromise(raw)) return {
3865
- tag: "async",
3866
- stripePromise: Promise.resolve(raw).then((result) => validateStripe(result, errorMsg))
3867
- };
3868
- const stripe = validateStripe(raw, errorMsg);
3869
- if (stripe === null) return { tag: "empty" };
3870
- return {
3871
- tag: "sync",
3872
- stripe
3873
- };
3874
- };
3875
- const isUnknownObject = (raw) => {
3876
- return raw !== null && typeof raw === "object";
3877
- };
3878
- const isPromise = (raw) => {
3879
- return isUnknownObject(raw) && typeof raw.then === "function";
3880
- };
3881
- const isStripe = (raw) => {
3882
- return isUnknownObject(raw) && typeof raw.elements === "function" && typeof raw.createToken === "function" && typeof raw.createPaymentMethod === "function" && typeof raw.confirmCardPayment === "function";
3883
- };
3884
- const extractAllowedOptionsUpdates = (options, prevOptions, immutableKeys) => {
3885
- if (!isUnknownObject(options)) return null;
3886
- return Object.keys(options).reduce((newOptions, key) => {
3887
- const isUpdated = !isUnknownObject(prevOptions) || !isEqual(options[key], prevOptions[key]);
3888
- if (immutableKeys.includes(key)) {
3889
- if (isUpdated) console.warn(`Unsupported prop change: options.${key} is not a mutable property.`);
3890
- return newOptions;
3891
- }
3892
- if (!isUpdated) return newOptions;
3893
- return {
3894
- ...newOptions || {},
3895
- [key]: options[key]
3896
- };
3897
- }, null);
3898
- };
3899
- const PLAIN_OBJECT_STR = "[object Object]";
3900
- const isEqual = (left, right) => {
3901
- if (!isUnknownObject(left) || !isUnknownObject(right)) return left === right;
3902
- const leftArray = Array.isArray(left);
3903
- if (leftArray !== Array.isArray(right)) return false;
3904
- const leftPlainObject = Object.prototype.toString.call(left) === PLAIN_OBJECT_STR;
3905
- if (leftPlainObject !== (Object.prototype.toString.call(right) === PLAIN_OBJECT_STR)) return false;
3906
- if (!leftPlainObject && !leftArray) return left === right;
3907
- const leftKeys = Object.keys(left);
3908
- const rightKeys = Object.keys(right);
3909
- if (leftKeys.length !== rightKeys.length) return false;
3910
- const keySet = {};
3911
- for (let i = 0; i < leftKeys.length; i += 1) keySet[leftKeys[i]] = true;
3912
- for (let i = 0; i < rightKeys.length; i += 1) keySet[rightKeys[i]] = true;
3913
- const allKeys = Object.keys(keySet);
3914
- if (allKeys.length !== leftKeys.length) return false;
3915
- const l = left;
3916
- const r = right;
3917
- const pred = (key) => {
3918
- return isEqual(l[key], r[key]);
3919
- };
3920
- return allKeys.every(pred);
3921
- };
3922
- const useStripe = () => {
3923
- const { stripe } = useElementsOrCheckoutSdkContextWithUseCase("calls useStripe()");
3924
- return stripe;
3925
- };
3926
- const useElementsOrCheckoutSdkContextWithUseCase = (useCaseString) => {
3927
- return parseElementsContext(react.default.useContext(ElementsContext), useCaseString);
3928
- };
3929
- const capitalized = (str) => str.charAt(0).toUpperCase() + str.slice(1);
3930
- const createElementComponent = (type, isServer) => {
3931
- const displayName = `${capitalized(type)}Element`;
3932
- const ClientElement = ({ id, className, fallback, options = {}, onBlur, onFocus, onReady, onChange, onEscape, onClick, onLoadError, onLoaderStart, onNetworksChange, onConfirm, onCancel, onShippingAddressChange, onShippingRateChange }) => {
3933
- const ctx = useElementsOrCheckoutSdkContextWithUseCase(`mounts <${displayName}>`);
3934
- const elements = "elements" in ctx ? ctx.elements : null;
3935
- const [element, setElement] = react.default.useState(null);
3936
- const elementRef = react.default.useRef(null);
3937
- const domNode = react.default.useRef(null);
3938
- const [isReady, setReady] = (0, react.useState)(false);
3939
- useAttachEvent(element, "blur", onBlur);
3940
- useAttachEvent(element, "focus", onFocus);
3941
- useAttachEvent(element, "escape", onEscape);
3942
- useAttachEvent(element, "click", onClick);
3943
- useAttachEvent(element, "loaderror", onLoadError);
3944
- useAttachEvent(element, "loaderstart", onLoaderStart);
3945
- useAttachEvent(element, "networkschange", onNetworksChange);
3946
- useAttachEvent(element, "confirm", onConfirm);
3947
- useAttachEvent(element, "cancel", onCancel);
3948
- useAttachEvent(element, "shippingaddresschange", onShippingAddressChange);
3949
- useAttachEvent(element, "shippingratechange", onShippingRateChange);
3950
- useAttachEvent(element, "change", onChange);
3951
- let readyCallback;
3952
- if (onReady) readyCallback = () => {
3953
- setReady(true);
3954
- onReady(element);
3955
- };
3956
- useAttachEvent(element, "ready", readyCallback);
3957
- react.default.useLayoutEffect(() => {
3958
- if (elementRef.current === null && domNode.current !== null && elements) {
3959
- let newElement = null;
3960
- if (elements) newElement = elements.create(type, options);
3961
- elementRef.current = newElement;
3962
- setElement(newElement);
3963
- if (newElement) newElement.mount(domNode.current);
3964
- }
3965
- }, [elements, options]);
3966
- const prevOptions = usePrevious(options);
3967
- react.default.useEffect(() => {
3968
- if (!elementRef.current) return;
3969
- const updates = extractAllowedOptionsUpdates(options, prevOptions, ["paymentRequest"]);
3970
- if (updates && "update" in elementRef.current) elementRef.current.update(updates);
3971
- }, [options, prevOptions]);
3972
- react.default.useLayoutEffect(() => {
3973
- return () => {
3974
- if (elementRef.current && typeof elementRef.current.destroy === "function") try {
3975
- elementRef.current.destroy();
3976
- elementRef.current = null;
3977
- } catch {}
3978
- };
3979
- }, []);
3980
- return /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, !isReady && fallback, /* @__PURE__ */ react.default.createElement("div", {
3981
- id,
3982
- style: {
3983
- height: isReady ? "unset" : "0px",
3984
- visibility: isReady ? "visible" : "hidden"
3985
- },
3986
- className,
3987
- ref: domNode
3988
- }));
3989
- };
3990
- const ServerElement = (props) => {
3991
- useElementsOrCheckoutSdkContextWithUseCase(`mounts <${displayName}>`);
3992
- const { id, className } = props;
3993
- return /* @__PURE__ */ react.default.createElement("div", {
3994
- id,
3995
- className
3996
- });
3997
- };
3998
- const Element = isServer ? ServerElement : ClientElement;
3999
- Element.displayName = displayName;
4000
- Element.__elementType = type;
4001
- return Element;
4002
- };
4003
- const PaymentElement$1 = createElementComponent("payment", typeof window === "undefined");
4004
-
4005
- //#endregion
4006
- //#region src/react/billing/useInitializePaymentMethod.tsx
4007
- /**
4008
- * @internal
4009
- */
4010
- function useInitializePaymentMethod(options) {
4011
- const { for: forType } = options ?? {};
4012
- const organization = useOrganizationBase();
4013
- const user = useUserBase();
4014
- const resource = forType === "organization" ? organization : user;
4015
- const billingEnabled = useBillingIsEnabled(options);
4016
- const stableKey = "billing-payment-method-initialize";
4017
- const authenticated = true;
4018
- const queryKey = (0, react.useMemo)(() => {
4019
- return [
4020
- stableKey,
4021
- authenticated,
4022
- { resourceId: resource?.id },
4023
- {}
4024
- ];
4025
- }, [resource?.id]);
4026
- const isEnabled = Boolean(resource?.id) && billingEnabled;
4027
- useClearQueriesOnSignOut({
4028
- isSignedOut: user === null,
4029
- authenticated,
4030
- stableKeys: stableKey
4031
- });
4032
- const query = useClerkQuery({
4033
- queryKey,
4034
- queryFn: async () => {
4035
- if (!resource) return;
4036
- return resource.initializePaymentMethod({ gateway: "stripe" });
4037
- },
4038
- enabled: isEnabled,
4039
- staleTime: 1e3 * 60,
4040
- refetchOnWindowFocus: false,
4041
- placeholderData: defineKeepPreviousDataFn(isEnabled)
4042
- });
4043
- const [queryClient] = useClerkQueryClient();
4044
- const initializePaymentMethod = (0, react.useCallback)(async () => {
4045
- if (!resource) return;
4046
- const result = await resource.initializePaymentMethod({ gateway: "stripe" });
4047
- queryClient.setQueryData(queryKey, result);
4048
- return result;
4049
- }, [
4050
- queryClient,
4051
- queryKey,
4052
- resource
4053
- ]);
4054
- return {
4055
- initializedPaymentMethod: query.data ?? void 0,
4056
- initializePaymentMethod
4057
- };
4058
- }
4059
-
4060
- //#endregion
4061
- //#region src/react/billing/useStripeClerkLibs.tsx
4062
- /**
4063
- * @internal
4064
- */
4065
- function useStripeClerkLibs() {
4066
- const clerk = useClerk();
4067
- return useClerkQuery({
4068
- queryKey: ["clerk-stripe-sdk"],
4069
- queryFn: async () => {
4070
- return { loadStripe: await clerk.__internal_loadStripeJs() };
4071
- },
4072
- staleTime: Infinity,
4073
- refetchOnWindowFocus: false,
4074
- placeholderData: defineKeepPreviousDataFn(true)
4075
- }).data ?? null;
4076
- }
4077
-
4078
- //#endregion
4079
- //#region src/react/billing/useStripeLoader.tsx
4080
- /**
4081
- * @internal
4082
- */
4083
- function useStripeLoader(options) {
4084
- const { stripeClerkLibs, externalGatewayId, stripePublishableKey } = options;
4085
- const queryKey = (0, react.useMemo)(() => {
4086
- return ["stripe-sdk", {
4087
- externalGatewayId,
4088
- stripePublishableKey
4089
- }];
4090
- }, [externalGatewayId, stripePublishableKey]);
4091
- const billingEnabled = useBillingIsEnabled({ authenticated: true });
4092
- return useClerkQuery({
4093
- queryKey,
4094
- queryFn: () => {
4095
- if (!stripeClerkLibs || !externalGatewayId || !stripePublishableKey) return null;
4096
- return stripeClerkLibs.loadStripe(stripePublishableKey, { stripeAccount: externalGatewayId });
4097
- },
4098
- enabled: Boolean(stripeClerkLibs && externalGatewayId && stripePublishableKey) && billingEnabled,
4099
- staleTime: 1e3 * 60,
4100
- refetchOnWindowFocus: false,
4101
- placeholderData: defineKeepPreviousDataFn(true)
4102
- }).data;
4103
- }
4104
-
4105
- //#endregion
4106
- //#region src/react/billing/payment-element.tsx
4107
- const useInternalEnvironment = () => {
4108
- return useClerk().__internal_environment;
4109
- };
4110
- const useLocalization = () => {
4111
- const clerk = useClerk();
4112
- let locale = "en";
4113
- try {
4114
- locale = clerk.__internal_getOption("localization")?.locale || "en";
4115
- } catch {}
4116
- return locale.split("-")[0];
4117
- };
4118
- const usePaymentSourceUtils = (forResource = "user") => {
4119
- const stripeClerkLibs = useStripeClerkLibs();
4120
- const environment = useInternalEnvironment();
4121
- const { initializedPaymentMethod, initializePaymentMethod } = useInitializePaymentMethod({ for: forResource });
4122
- const stripePublishableKey = environment?.commerceSettings.billing.stripePublishableKey ?? void 0;
4123
- return {
4124
- stripe: useStripeLoader({
4125
- stripeClerkLibs,
4126
- externalGatewayId: initializedPaymentMethod?.externalGatewayId,
4127
- stripePublishableKey
4128
- }),
4129
- initializePaymentMethod,
4130
- externalClientSecret: initializedPaymentMethod?.externalClientSecret,
4131
- paymentMethodOrder: initializedPaymentMethod?.paymentMethodOrder
4132
- };
4133
- };
4134
- const [PaymentElementContext, usePaymentElementContext] = createContextAndHook("PaymentElementContext");
4135
- const [StripeUtilsContext, useStripeUtilsContext] = createContextAndHook("StripeUtilsContext");
4136
- const ValidateStripeUtils = ({ children }) => {
4137
- const stripe = useStripe();
4138
- const elements = useElements();
4139
- return /* @__PURE__ */ react.default.createElement(StripeUtilsContext.Provider, { value: { value: {
4140
- stripe,
4141
- elements
4142
- } } }, children);
4143
- };
4144
- const DummyStripeUtils = ({ children }) => {
4145
- return /* @__PURE__ */ react.default.createElement(StripeUtilsContext.Provider, { value: { value: {} } }, children);
4146
- };
4147
- const PropsProvider = ({ children, ...props }) => {
4148
- const utils = usePaymentSourceUtils(props.for);
4149
- const [isPaymentElementReady, setIsPaymentElementReady] = (0, react.useState)(false);
4150
- return /* @__PURE__ */ react.default.createElement(PaymentElementContext.Provider, { value: { value: {
4151
- ...props,
4152
- ...utils,
4153
- setIsPaymentElementReady,
4154
- isPaymentElementReady
4155
- } } }, children);
4156
- };
4157
- const PaymentElementProvider = ({ children, ...props }) => {
4158
- return /* @__PURE__ */ react.default.createElement(PropsProvider, props, /* @__PURE__ */ react.default.createElement(PaymentElementInternalRoot, null, children));
4159
- };
4160
- const PaymentElementInternalRoot = (props) => {
4161
- const { stripe, externalClientSecret, stripeAppearance } = usePaymentElementContext();
4162
- const locale = useLocalization();
4163
- if (stripe && externalClientSecret) return /* @__PURE__ */ react.default.createElement(Elements, {
4164
- key: externalClientSecret,
4165
- stripe,
4166
- options: {
4167
- loader: "never",
4168
- clientSecret: externalClientSecret,
4169
- appearance: { variables: stripeAppearance },
4170
- locale
4171
- }
4172
- }, /* @__PURE__ */ react.default.createElement(ValidateStripeUtils, null, props.children));
4173
- return /* @__PURE__ */ react.default.createElement(DummyStripeUtils, null, props.children);
4174
- };
4175
- const PaymentElement = ({ fallback }) => {
4176
- const { setIsPaymentElementReady, paymentMethodOrder, checkout, stripe, externalClientSecret, paymentDescription, for: _for } = usePaymentElementContext();
4177
- const environment = useInternalEnvironment();
4178
- const applePay = (0, react.useMemo)(() => {
4179
- if (!checkout || !checkout.totals || !checkout.plan) return;
4180
- return { recurringPaymentRequest: {
4181
- paymentDescription: paymentDescription || "",
4182
- managementURL: _for === "organization" ? environment?.displayConfig.organizationProfileUrl || "" : environment?.displayConfig.userProfileUrl || "",
4183
- regularBilling: {
4184
- amount: checkout.totals.totalDueNow?.amount || checkout.totals.grandTotal.amount,
4185
- label: checkout.plan.name,
4186
- recurringPaymentIntervalUnit: checkout.planPeriod === "annual" ? "year" : "month"
4187
- }
4188
- } };
4189
- }, [
4190
- checkout,
4191
- paymentDescription,
4192
- _for,
4193
- environment
4194
- ]);
4195
- const options = (0, react.useMemo)(() => {
4196
- return {
4197
- layout: {
4198
- type: "tabs",
4199
- defaultCollapsed: false
4200
- },
4201
- paymentMethodOrder,
4202
- applePay
4203
- };
4204
- }, [applePay, paymentMethodOrder]);
4205
- const onReady = (0, react.useCallback)(() => {
4206
- setIsPaymentElementReady(true);
4207
- }, [setIsPaymentElementReady]);
4208
- if (!stripe || !externalClientSecret) return /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, fallback);
4209
- return /* @__PURE__ */ react.default.createElement(PaymentElement$1, {
4210
- fallback,
4211
- onReady,
4212
- options
4213
- });
4214
- };
4215
- const throwLibsMissingError = () => {
4216
- throw new Error("Clerk: Unable to submit, Stripe libraries are not yet loaded. Be sure to check `isFormReady` before calling `submit`.");
4217
- };
4218
- const usePaymentElement = () => {
4219
- const { isPaymentElementReady, initializePaymentMethod } = usePaymentElementContext();
4220
- const { stripe, elements } = useStripeUtilsContext();
4221
- const { externalClientSecret } = usePaymentElementContext();
4222
- const submit = (0, react.useCallback)(async () => {
4223
- if (!stripe || !elements) return throwLibsMissingError();
4224
- const { setupIntent, error } = await stripe.confirmSetup({
4225
- elements,
4226
- confirmParams: { return_url: window.location.href },
4227
- redirect: "if_required"
4228
- });
4229
- if (error) return {
4230
- data: null,
4231
- error: {
4232
- gateway: "stripe",
4233
- error: {
4234
- code: error.code,
4235
- message: error.message,
4236
- type: error.type
4237
- }
4238
- }
4239
- };
4240
- return {
4241
- data: {
4242
- gateway: "stripe",
4243
- paymentToken: setupIntent.payment_method
4244
- },
4245
- error: null
4246
- };
4247
- }, [stripe, elements]);
4248
- const reset = (0, react.useCallback)(async () => {
4249
- if (!stripe || !elements) return throwLibsMissingError();
4250
- await initializePaymentMethod();
4251
- }, [
4252
- stripe,
4253
- elements,
4254
- initializePaymentMethod
4255
- ]);
4256
- const isProviderReady = Boolean(stripe && externalClientSecret);
4257
- if (!isProviderReady) return {
4258
- submit: throwLibsMissingError,
4259
- reset: throwLibsMissingError,
4260
- isFormReady: false,
4261
- provider: void 0,
4262
- isProviderReady: false
4263
- };
4264
- return {
4265
- submit,
4266
- reset,
4267
- isFormReady: isPaymentElementReady,
4268
- provider: { name: "stripe" },
4269
- isProviderReady
4270
- };
4271
- };
4272
-
4273
- //#endregion
4274
- //#region src/react/PortalProvider.tsx
4275
- const [PortalContext, , usePortalContextWithoutGuarantee] = createContextAndHook("PortalProvider");
4276
- /**
4277
- * UNSAFE_PortalProvider allows you to specify a custom container for Clerk floating UI elements
4278
- * (popovers, modals, tooltips, etc.) that use portals.
4279
- *
4280
- * Only components within this provider will be affected. Components outside the provider
4281
- * will continue to use the default document.body for portals.
4282
- *
4283
- * This is particularly useful when using Clerk components inside external UI libraries
4284
- * like Radix Dialog or React Aria Components, where portaled elements need to render
4285
- * within the dialog's container to remain interactable.
4286
- *
4287
- * @example
4288
- * ```tsx
4289
- * function Example() {
4290
- * const containerRef = useRef(null);
4291
- * return (
4292
- * <RadixDialog ref={containerRef}>
4293
- * <UNSAFE_PortalProvider getContainer={() => containerRef.current}>
4294
- * <UserButton />
4295
- * </UNSAFE_PortalProvider>
4296
- * </RadixDialog>
4297
- * );
4298
- * }
4299
- * ```
4300
- */
4301
- const UNSAFE_PortalProvider = ({ children, getContainer }) => {
4302
- const contextValue = react.default.useMemo(() => ({ value: { getContainer } }), [getContainer]);
4303
- return /* @__PURE__ */ react.default.createElement(PortalContext.Provider, { value: contextValue }, children);
4304
- };
4305
- UNSAFE_PortalProvider.displayName = "UNSAFE_PortalProvider";
4306
- /**
4307
- * Hook to get the current portal root container.
4308
- * Returns the getContainer function from context if inside a PortalProvider,
4309
- * otherwise returns a function that returns null (default behavior).
4310
- */
4311
- const usePortalRoot = () => {
4312
- const contextValue = usePortalContextWithoutGuarantee();
4313
- if (contextValue && "getContainer" in contextValue && contextValue.getContainer) return contextValue.getContainer;
4314
- return () => null;
4315
- };
4316
-
4317
- //#endregion
4318
- exports.ClerkContextProvider = ClerkContextProvider;
4319
- exports.ClerkInstanceContext = ClerkInstanceContext;
4320
- exports.InitialStateProvider = InitialStateProvider;
4321
- exports.OptionsContext = OptionsContext;
4322
- exports.UNSAFE_PortalProvider = UNSAFE_PortalProvider;
4323
- exports.__createClerkTestQueryClient = __createClerkTestQueryClient;
4324
- exports.__experimental_CheckoutProvider = __experimental_CheckoutProvider;
4325
- exports.__experimental_PaymentElement = PaymentElement;
4326
- exports.__experimental_PaymentElementProvider = PaymentElementProvider;
4327
- exports.__experimental_useCheckout = useCheckout;
4328
- exports.__experimental_usePaymentAttempts = usePaymentAttempts;
4329
- exports.__experimental_usePaymentElement = usePaymentElement;
4330
- exports.__experimental_usePaymentMethods = usePaymentMethods;
4331
- exports.__experimental_usePlans = usePlans;
4332
- exports.__experimental_useStatements = useStatements;
4333
- exports.__experimental_useSubscription = useSubscription;
4334
- exports.__internal_createCacheKeys = createCacheKeys;
4335
- exports.__internal_useClearQueriesOnSignOut = useClearQueriesOnSignOut;
4336
- exports.__internal_useClerkQuery = useClerkQuery;
4337
- exports.__internal_useClientBase = useClientBase;
4338
- exports.__internal_useCreditBalanceQuery = __internal_useCreditBalanceQuery;
4339
- exports.__internal_useCreditHistoryQuery = __internal_useCreditHistoryQuery;
4340
- exports.__internal_useOrganizationBase = useOrganizationBase;
4341
- exports.__internal_useOrganizationDirectorySync = useOrganizationDirectorySync;
4342
- exports.__internal_useOrganizationDirectorySyncGroupRoleMappings = useOrganizationDirectorySyncGroupRoleMappings;
4343
- exports.__internal_useOrganizationDirectorySyncStatus = useOrganizationDirectorySyncStatus;
4344
- exports.__internal_useOrganizationDirectorySyncUsers = useOrganizationDirectorySyncUsers;
4345
- exports.__internal_useOrganizationDomains = useOrganizationDomains;
4346
- exports.__internal_useOrganizationEnterpriseConnectionTestRuns = useOrganizationEnterpriseConnectionTestRuns;
4347
- exports.__internal_useOrganizationEnterpriseConnections = useOrganizationEnterpriseConnections;
4348
- exports.__internal_useOrganizationSSOBypassAllowlist = useOrganizationSSOBypassAllowlist;
4349
- exports.__internal_usePaymentAttemptQuery = usePaymentAttemptQuery;
4350
- exports.__internal_usePlanDetailsQuery = __internal_usePlanDetailsQuery;
4351
- exports.__internal_useSessionBase = useSessionBase;
4352
- exports.__internal_useStatementQuery = useStatementQuery;
4353
- exports.__internal_useUserBase = useUserBase;
4354
- exports.__internal_useUserEnterpriseConnections = useUserEnterpriseConnections;
4355
- exports.__resetClerkQueryClientForTest = __resetClerkQueryClientForTest;
4356
- exports.__setClerkQueryClientForTest = __setClerkQueryClientForTest;
4357
- exports.assertContextExists = assertContextExists;
4358
- exports.createContextAndHook = createContextAndHook;
4359
- exports.getClerkQueryClient = getClerkQueryClient;
4360
- exports.isDeeplyEqual = isDeeplyEqual;
4361
- exports.useAPIKeys = useAPIKeys;
4362
- exports.useAssertWrappedByClerkProvider = useAssertWrappedByClerkProvider;
4363
- exports.useAttemptToEnableOrganizations = useAttemptToEnableOrganizations;
4364
- exports.useClerk = useClerk;
4365
- exports.useClerkInstanceContext = useClerkInstanceContext;
4366
- exports.useDeepEqualMemo = useDeepEqualMemo;
4367
- exports.useInitialStateContext = useInitialStateContext;
4368
- exports.useOAuthConsent = useOAuthConsent;
4369
- exports.useOAuthDeviceVerification = useOAuthDeviceVerification;
4370
- exports.useOptionsContext = useOptionsContext;
4371
- exports.useOrganization = useOrganization;
4372
- exports.useOrganizationCreationDefaults = useOrganizationCreationDefaults;
4373
- exports.useOrganizationList = useOrganizationList;
4374
- exports.usePortalRoot = usePortalRoot;
4375
- exports.useReverification = useReverification;
4376
- exports.useSafeLayoutEffect = useSafeLayoutEffect;
4377
- exports.useSession = useSession;
4378
- exports.useSessionList = useSessionList;
4379
- exports.useUser = useUser;
4380
- //# sourceMappingURL=index.js.map
2
+ const require_createContextAndHook = require('./hooks/createContextAndHook.js');
3
+ const require_contexts = require('./contexts.js');
4
+ const require_createCacheKeys = require('./hooks/createCacheKeys.js');
5
+ const require_clerk_query_client = require('./query/clerk-query-client.js');
6
+ const require_useQuery = require('./query/useQuery.js');
7
+ const require_useClearQueriesOnSignOut = require('./hooks/useClearQueriesOnSignOut.js');
8
+ const require_useAPIKeys = require('./hooks/useAPIKeys.js');
9
+ const require_useUserBase = require('./hooks/base/useUserBase.js');
10
+ const require_useOAuthConsent = require('./hooks/useOAuthConsent.js');
11
+ const require_useOAuthDeviceVerification = require('./hooks/useOAuthDeviceVerification.js');
12
+ const require_useOrganizationBase = require('./hooks/base/useOrganizationBase.js');
13
+ const require_useSessionBase = require('./hooks/base/useSessionBase.js');
14
+ const require_useClerk = require('./hooks/useClerk.js');
15
+ const require_useAttemptToEnableOrganizations = require('./hooks/useAttemptToEnableOrganizations.js');
16
+ const require_useOrganization = require('./hooks/useOrganization.js');
17
+ const require_useOrganizationCreationDefaults = require('./hooks/useOrganizationCreationDefaults.js');
18
+ const require_useOrganizationList = require('./hooks/useOrganizationList.js');
19
+ const require_useSafeLayoutEffect = require('./hooks/useSafeLayoutEffect.js');
20
+ const require_useSession = require('./hooks/useSession.js');
21
+ const require_useClientBase = require('./hooks/base/useClientBase.js');
22
+ const require_useSessionList = require('./hooks/useSessionList.js');
23
+ const require_useUser = require('./hooks/useUser.js');
24
+ const require_useDeepEqualMemo = require('./hooks/useDeepEqualMemo.js');
25
+ const require_useReverification = require('./hooks/useReverification.js');
26
+ const require_useStatements = require('./hooks/useStatements.js');
27
+ const require_usePaymentAttempts = require('./hooks/usePaymentAttempts.js');
28
+ const require_usePaymentMethods = require('./hooks/usePaymentMethods.js');
29
+ const require_usePlans = require('./hooks/usePlans.js');
30
+ const require_useSubscription = require('./hooks/useSubscription.js');
31
+ const require_useCheckout = require('./hooks/useCheckout.js');
32
+ const require_useCreditBalance = require('./hooks/useCreditBalance.js');
33
+ const require_useCreditHistory = require('./hooks/useCreditHistory.js');
34
+ const require_useStatementQuery = require('./hooks/useStatementQuery.js');
35
+ const require_usePlanDetailsQuery = require('./hooks/usePlanDetailsQuery.js');
36
+ const require_usePaymentAttemptQuery = require('./hooks/usePaymentAttemptQuery.js');
37
+ const require_useUserEnterpriseConnections = require('./hooks/useUserEnterpriseConnections.js');
38
+ const require_useOrganizationEnterpriseConnections = require('./hooks/useOrganizationEnterpriseConnections.js');
39
+ const require_useOrganizationDomains = require('./hooks/useOrganizationDomains.js');
40
+ const require_useOrganizationDirectorySync = require('./hooks/useOrganizationDirectorySync.js');
41
+ const require_useOrganizationDirectorySyncUsers = require('./hooks/useOrganizationDirectorySyncUsers.js');
42
+ const require_useOrganizationDirectorySyncStatus = require('./hooks/useOrganizationDirectorySyncStatus.js');
43
+ const require_useOrganizationDirectorySyncGroupRoleMappings = require('./hooks/useOrganizationDirectorySyncGroupRoleMappings.js');
44
+ const require_useOrganizationEnterpriseConnectionTestRuns = require('./hooks/useOrganizationEnterpriseConnectionTestRuns.js');
45
+ const require_useOrganizationSSOBypassAllowlist = require('./hooks/useOrganizationSSOBypassAllowlist.js');
46
+ require('./hooks/index.js');
47
+ const require_ClerkContextProvider = require('./ClerkContextProvider.js');
48
+ const require_payment_element = require('./billing/payment-element.js');
49
+ const require_PortalProvider = require('./PortalProvider.js');
50
+
51
+ exports.ClerkContextProvider = require_ClerkContextProvider.ClerkContextProvider;
52
+ exports.ClerkInstanceContext = require_contexts.ClerkInstanceContext;
53
+ exports.InitialStateProvider = require_contexts.InitialStateProvider;
54
+ exports.OptionsContext = require_contexts.OptionsContext;
55
+ exports.UNSAFE_PortalProvider = require_PortalProvider.UNSAFE_PortalProvider;
56
+ exports.__createClerkTestQueryClient = require_clerk_query_client.__createClerkTestQueryClient;
57
+ exports.__experimental_CheckoutProvider = require_contexts.__experimental_CheckoutProvider;
58
+ exports.__experimental_PaymentElement = require_payment_element.PaymentElement;
59
+ exports.__experimental_PaymentElementProvider = require_payment_element.PaymentElementProvider;
60
+ exports.__experimental_useCheckout = require_useCheckout.useCheckout;
61
+ exports.__experimental_usePaymentAttempts = require_usePaymentAttempts.usePaymentAttempts;
62
+ exports.__experimental_usePaymentElement = require_payment_element.usePaymentElement;
63
+ exports.__experimental_usePaymentMethods = require_usePaymentMethods.usePaymentMethods;
64
+ exports.__experimental_usePlans = require_usePlans.usePlans;
65
+ exports.__experimental_useStatements = require_useStatements.useStatements;
66
+ exports.__experimental_useSubscription = require_useSubscription.useSubscription;
67
+ exports.__internal_createCacheKeys = require_createCacheKeys.createCacheKeys;
68
+ exports.__internal_useClearQueriesOnSignOut = require_useClearQueriesOnSignOut.useClearQueriesOnSignOut;
69
+ exports.__internal_useClerkQuery = require_useQuery.useClerkQuery;
70
+ exports.__internal_useClientBase = require_useClientBase.useClientBase;
71
+ exports.__internal_useCreditBalanceQuery = require_useCreditBalance.__internal_useCreditBalanceQuery;
72
+ exports.__internal_useCreditHistoryQuery = require_useCreditHistory.__internal_useCreditHistoryQuery;
73
+ exports.__internal_useOrganizationBase = require_useOrganizationBase.useOrganizationBase;
74
+ exports.__internal_useOrganizationDirectorySync = require_useOrganizationDirectorySync.useOrganizationDirectorySync;
75
+ exports.__internal_useOrganizationDirectorySyncGroupRoleMappings = require_useOrganizationDirectorySyncGroupRoleMappings.useOrganizationDirectorySyncGroupRoleMappings;
76
+ exports.__internal_useOrganizationDirectorySyncStatus = require_useOrganizationDirectorySyncStatus.useOrganizationDirectorySyncStatus;
77
+ exports.__internal_useOrganizationDirectorySyncUsers = require_useOrganizationDirectorySyncUsers.useOrganizationDirectorySyncUsers;
78
+ exports.__internal_useOrganizationDomains = require_useOrganizationDomains.useOrganizationDomains;
79
+ exports.__internal_useOrganizationEnterpriseConnectionTestRuns = require_useOrganizationEnterpriseConnectionTestRuns.useOrganizationEnterpriseConnectionTestRuns;
80
+ exports.__internal_useOrganizationEnterpriseConnections = require_useOrganizationEnterpriseConnections.useOrganizationEnterpriseConnections;
81
+ exports.__internal_useOrganizationSSOBypassAllowlist = require_useOrganizationSSOBypassAllowlist.useOrganizationSSOBypassAllowlist;
82
+ exports.__internal_usePaymentAttemptQuery = require_usePaymentAttemptQuery.usePaymentAttemptQuery;
83
+ exports.__internal_usePlanDetailsQuery = require_usePlanDetailsQuery.__internal_usePlanDetailsQuery;
84
+ exports.__internal_useSessionBase = require_useSessionBase.useSessionBase;
85
+ exports.__internal_useStatementQuery = require_useStatementQuery.useStatementQuery;
86
+ exports.__internal_useUserBase = require_useUserBase.useUserBase;
87
+ exports.__internal_useUserEnterpriseConnections = require_useUserEnterpriseConnections.useUserEnterpriseConnections;
88
+ exports.__resetClerkQueryClientForTest = require_clerk_query_client.__resetClerkQueryClientForTest;
89
+ exports.__setClerkQueryClientForTest = require_clerk_query_client.__setClerkQueryClientForTest;
90
+ exports.assertContextExists = require_createContextAndHook.assertContextExists;
91
+ exports.createContextAndHook = require_createContextAndHook.createContextAndHook;
92
+ exports.getClerkQueryClient = require_clerk_query_client.getClerkQueryClient;
93
+ exports.isDeeplyEqual = require_useDeepEqualMemo.isDeeplyEqual;
94
+ exports.useAPIKeys = require_useAPIKeys.useAPIKeys;
95
+ exports.useAssertWrappedByClerkProvider = require_contexts.useAssertWrappedByClerkProvider;
96
+ exports.useAttemptToEnableOrganizations = require_useAttemptToEnableOrganizations.useAttemptToEnableOrganizations;
97
+ exports.useClerk = require_useClerk.useClerk;
98
+ exports.useClerkInstanceContext = require_contexts.useClerkInstanceContext;
99
+ exports.useDeepEqualMemo = require_useDeepEqualMemo.useDeepEqualMemo;
100
+ exports.useInitialStateContext = require_contexts.useInitialStateContext;
101
+ exports.useOAuthConsent = require_useOAuthConsent.useOAuthConsent;
102
+ exports.useOAuthDeviceVerification = require_useOAuthDeviceVerification.useOAuthDeviceVerification;
103
+ exports.useOptionsContext = require_contexts.useOptionsContext;
104
+ exports.useOrganization = require_useOrganization.useOrganization;
105
+ exports.useOrganizationCreationDefaults = require_useOrganizationCreationDefaults.useOrganizationCreationDefaults;
106
+ exports.useOrganizationList = require_useOrganizationList.useOrganizationList;
107
+ exports.usePortalRoot = require_PortalProvider.usePortalRoot;
108
+ exports.useReverification = require_useReverification.useReverification;
109
+ exports.useSafeLayoutEffect = require_useSafeLayoutEffect.useSafeLayoutEffect;
110
+ exports.useSession = require_useSession.useSession;
111
+ exports.useSessionList = require_useSessionList.useSessionList;
112
+ exports.useUser = require_useUser.useUser;