@clerk/shared 4.0.0-canary.v20260107202600 → 4.0.0-canary.v20260108154421

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 (106) hide show
  1. package/dist/runtime/alternativePhoneCode.d.mts +1 -1
  2. package/dist/runtime/alternativePhoneCode.d.ts +1 -1
  3. package/dist/runtime/apiUrlFromPublishableKey.d.mts +1 -1
  4. package/dist/runtime/apiUrlFromPublishableKey.d.ts +1 -1
  5. package/dist/runtime/authorization-errors.d.mts +1 -1
  6. package/dist/runtime/authorization-errors.d.ts +1 -1
  7. package/dist/runtime/authorization.d.mts +1 -1
  8. package/dist/runtime/authorization.d.ts +1 -1
  9. package/dist/runtime/clerkEventBus.d.mts +1 -1
  10. package/dist/runtime/clerkEventBus.d.ts +1 -1
  11. package/dist/runtime/color.d.mts +1 -1
  12. package/dist/runtime/color.d.ts +1 -1
  13. package/dist/runtime/color.d.ts.map +1 -1
  14. package/dist/runtime/deriveState.d.mts +1 -1
  15. package/dist/runtime/deriveState.d.ts +1 -1
  16. package/dist/runtime/{error-BXk0GDM3.d.mts → error-DNiurtIH.d.mts} +2 -2
  17. package/dist/runtime/{error-BXk0GDM3.d.mts.map → error-DNiurtIH.d.mts.map} +1 -1
  18. package/dist/runtime/{error-Bc2wkICP.d.ts → error-DW8FKFzD.d.ts} +2 -2
  19. package/dist/runtime/{error-Bc2wkICP.d.ts.map → error-DW8FKFzD.d.ts.map} +1 -1
  20. package/dist/runtime/error.d.mts +2 -2
  21. package/dist/runtime/error.d.ts +2 -2
  22. package/dist/runtime/globs.d.ts.map +1 -1
  23. package/dist/runtime/{index-C3yQerjv.d.mts → index-CwXrQ0D9.d.mts} +17 -1
  24. package/dist/runtime/index-CwXrQ0D9.d.mts.map +1 -0
  25. package/dist/runtime/{index-CuGwkvfN.d.ts → index-y60Yzgpv.d.ts} +17 -1
  26. package/dist/runtime/index-y60Yzgpv.d.ts.map +1 -0
  27. package/dist/runtime/internal/clerk-js/completeSignUpFlow.d.mts +1 -1
  28. package/dist/runtime/internal/clerk-js/completeSignUpFlow.d.ts +1 -1
  29. package/dist/runtime/internal/clerk-js/componentGuards.d.mts +1 -1
  30. package/dist/runtime/internal/clerk-js/componentGuards.d.ts +1 -1
  31. package/dist/runtime/internal/clerk-js/injectedWeb3EthProviders.d.mts +1 -1
  32. package/dist/runtime/internal/clerk-js/injectedWeb3EthProviders.d.ts +1 -1
  33. package/dist/runtime/internal/clerk-js/passkeys.d.mts +2 -2
  34. package/dist/runtime/internal/clerk-js/passkeys.d.ts +2 -2
  35. package/dist/runtime/internal/clerk-js/passwords/complexity.d.mts +1 -1
  36. package/dist/runtime/internal/clerk-js/passwords/complexity.d.ts +1 -1
  37. package/dist/runtime/internal/clerk-js/passwords/loadZxcvbn.d.mts +1 -1
  38. package/dist/runtime/internal/clerk-js/passwords/loadZxcvbn.d.ts +1 -1
  39. package/dist/runtime/internal/clerk-js/passwords/password.d.mts +1 -1
  40. package/dist/runtime/internal/clerk-js/passwords/password.d.ts +1 -1
  41. package/dist/runtime/internal/clerk-js/passwords/strength.d.mts +1 -1
  42. package/dist/runtime/internal/clerk-js/passwords/strength.d.ts +1 -1
  43. package/dist/runtime/internal/clerk-js/queryParams.d.mts +2 -2
  44. package/dist/runtime/internal/clerk-js/queryParams.d.ts +2 -2
  45. package/dist/runtime/internal/clerk-js/redirectUrls.d.mts +1 -1
  46. package/dist/runtime/internal/clerk-js/redirectUrls.d.ts +1 -1
  47. package/dist/runtime/internal/clerk-js/sessionTasks.d.mts +2 -2
  48. package/dist/runtime/internal/clerk-js/sessionTasks.d.ts +2 -2
  49. package/dist/runtime/internal/clerk-js/url.d.mts +2 -2
  50. package/dist/runtime/internal/clerk-js/url.d.ts +2 -2
  51. package/dist/runtime/internal/clerk-js/user.d.mts +1 -1
  52. package/dist/runtime/internal/clerk-js/user.d.ts +1 -1
  53. package/dist/runtime/internal/clerk-js/web3.d.mts +1 -1
  54. package/dist/runtime/internal/clerk-js/web3.d.ts +1 -1
  55. package/dist/runtime/jwtPayloadParser.d.mts +1 -1
  56. package/dist/runtime/jwtPayloadParser.d.ts +1 -1
  57. package/dist/runtime/keys.d.mts +1 -1
  58. package/dist/runtime/keys.d.ts +1 -1
  59. package/dist/runtime/loadClerkJsScript.d.mts +1 -1
  60. package/dist/runtime/loadClerkJsScript.d.ts +1 -1
  61. package/dist/runtime/loadClerkJsScript.js +2 -2
  62. package/dist/runtime/loadClerkJsScript.mjs +2 -2
  63. package/dist/runtime/oauth.d.mts +1 -1
  64. package/dist/runtime/oauth.d.ts +1 -1
  65. package/dist/runtime/organization.d.mts +1 -1
  66. package/dist/runtime/organization.d.ts +1 -1
  67. package/dist/runtime/pathMatcher.d.mts +1 -1
  68. package/dist/runtime/pathMatcher.d.ts +1 -1
  69. package/dist/runtime/poller.d.ts.map +1 -1
  70. package/dist/runtime/react/index.d.mts +14 -29
  71. package/dist/runtime/react/index.d.mts.map +1 -1
  72. package/dist/runtime/react/index.d.ts +14 -29
  73. package/dist/runtime/react/index.d.ts.map +1 -1
  74. package/dist/runtime/react/index.js +499 -309
  75. package/dist/runtime/react/index.js.map +1 -1
  76. package/dist/runtime/react/index.mjs +498 -304
  77. package/dist/runtime/react/index.mjs.map +1 -1
  78. package/dist/runtime/router.d.mts +1 -1
  79. package/dist/runtime/router.d.ts +1 -1
  80. package/dist/runtime/saml.d.mts +1 -1
  81. package/dist/runtime/saml.d.ts +1 -1
  82. package/dist/runtime/telemetry.d.mts +1 -1
  83. package/dist/runtime/telemetry.d.ts +1 -1
  84. package/dist/runtime/types/index.d.mts +1 -1
  85. package/dist/runtime/types/index.d.ts +1 -1
  86. package/dist/runtime/ui/index.d.mts +1 -1
  87. package/dist/runtime/ui/index.d.ts +1 -1
  88. package/dist/runtime/{url-CeTIrv79.d.mts → url-DBdjYUUx.d.mts} +2 -2
  89. package/dist/runtime/{url-CeTIrv79.d.mts.map → url-DBdjYUUx.d.mts.map} +1 -1
  90. package/dist/runtime/{url-B3azMvOn.d.ts → url-yHlyfWdB.d.ts} +2 -2
  91. package/dist/runtime/{url-B3azMvOn.d.ts.map → url-yHlyfWdB.d.ts.map} +1 -1
  92. package/dist/runtime/{versionSelector-BvO2gPHd.js → versionSelector-DAcqxcwB.js} +2 -2
  93. package/dist/runtime/{versionSelector-BvO2gPHd.js.map → versionSelector-DAcqxcwB.js.map} +1 -1
  94. package/dist/runtime/{versionSelector-B270CtHZ.mjs → versionSelector-DfdpF2HN.mjs} +2 -2
  95. package/dist/runtime/{versionSelector-B270CtHZ.mjs.map → versionSelector-DfdpF2HN.mjs.map} +1 -1
  96. package/dist/runtime/versionSelector.js +1 -1
  97. package/dist/runtime/versionSelector.mjs +1 -1
  98. package/dist/runtime/web3.d.mts +1 -1
  99. package/dist/runtime/web3.d.ts +1 -1
  100. package/dist/types/index.d.mts +16 -0
  101. package/dist/types/index.d.mts.map +1 -1
  102. package/dist/types/index.d.ts +16 -0
  103. package/dist/types/index.d.ts.map +1 -1
  104. package/package.json +3 -4
  105. package/dist/runtime/index-C3yQerjv.d.mts.map +0 -1
  106. package/dist/runtime/index-CuGwkvfN.d.ts.map +0 -1
@@ -13,13 +13,8 @@ const require_telemetry = require('../telemetry-CXXDXYfo.js');
13
13
  const require_createDeferredPromise = require('../createDeferredPromise-CFgXzt9g.js');
14
14
  let react = require("react");
15
15
  react = require_chunk.__toESM(react);
16
- let swr = require("swr");
17
- swr = require_chunk.__toESM(swr);
18
- let swr_infinite = require("swr/infinite");
19
- swr_infinite = require_chunk.__toESM(swr_infinite);
16
+ let __tanstack_query_core = require("@tanstack/query-core");
20
17
  let dequal = require("dequal");
21
- let swr_mutation = require("swr/mutation");
22
- swr_mutation = require_chunk.__toESM(swr_mutation);
23
18
 
24
19
  //#region src/react/hooks/createContextAndHook.ts
25
20
  /**
@@ -59,15 +54,6 @@ const createContextAndHook = (displayName, options) => {
59
54
  ];
60
55
  };
61
56
 
62
- //#endregion
63
- //#region src/react/providers/SWRConfigCompat.swr.tsx
64
- /**
65
- * @internal
66
- */
67
- function SWRConfigCompat({ swrConfig, children }) {
68
- return /* @__PURE__ */ react.default.createElement(swr.SWRConfig, { value: swrConfig }, children);
69
- }
70
-
71
57
  //#endregion
72
58
  //#region src/react/contexts.tsx
73
59
  const [ClerkInstanceContext, useClerkInstanceContext] = createContextAndHook("ClerkInstanceContext");
@@ -88,8 +74,8 @@ function useOptionsContext() {
88
74
  return context;
89
75
  }
90
76
  const [OrganizationContextInternal, useOrganizationContext] = createContextAndHook("OrganizationContext");
91
- const OrganizationProvider = ({ children, organization, swrConfig }) => {
92
- return /* @__PURE__ */ react.default.createElement(SWRConfigCompat, { swrConfig }, /* @__PURE__ */ react.default.createElement(OrganizationContextInternal.Provider, { value: { value: { organization } } }, children));
77
+ const OrganizationProvider = ({ children, organization }) => {
78
+ return /* @__PURE__ */ react.default.createElement(OrganizationContextInternal.Provider, { value: { value: { organization } } }, children);
93
79
  };
94
80
  /**
95
81
  * @internal
@@ -175,83 +161,123 @@ function createCacheKeys(params) {
175
161
  authenticated: params.authenticated
176
162
  };
177
163
  }
164
+
165
+ //#endregion
166
+ //#region src/react/clerk-rq/keep-previous-data.ts
178
167
  /**
179
168
  * @internal
180
169
  */
181
- function toSWRQuery(keys) {
182
- const { queryKey } = keys;
183
- return {
184
- type: queryKey[0],
185
- ...queryKey[2],
186
- ...queryKey[3].args
170
+ function defineKeepPreviousDataFn(enabled) {
171
+ if (enabled) return function KeepPreviousDataFn(previousData) {
172
+ return previousData;
187
173
  };
188
174
  }
189
175
 
190
176
  //#endregion
191
- //#region src/react/hooks/usePagesOrInfinite.shared.ts
177
+ //#region src/react/clerk-rq/use-clerk-query-client.ts
192
178
  /**
193
- * A hook that safely merges user-provided pagination options with default values.
194
- * It caches initial pagination values (page and size) until component unmount to prevent unwanted rerenders.
195
- *
196
- * @internal
197
- *
198
- * @example
199
- * ```typescript
200
- * // Example 1: With user-provided options
201
- * const userOptions = { initialPage: 2, pageSize: 20, infinite: true };
202
- * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
203
- * useWithSafeValues(userOptions, defaults);
204
- * // Returns { initialPage: 2, pageSize: 20, infinite: true }
205
- *
206
- * // Example 2: With boolean true (use defaults)
207
- * const params = true;
208
- * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
209
- * useWithSafeValues(params, defaults);
210
- * // Returns { initialPage: 1, pageSize: 10, infinite: false }
179
+ * Creates a recursively self-referential Proxy that safely handles:
180
+ * - Arbitrary property access (e.g., obj.any.prop.path)
181
+ * - Function calls at any level (e.g., obj.a().b.c())
182
+ * - Construction (e.g., new obj.a.b())
211
183
  *
212
- * // Example 3: With undefined options (fallback to defaults)
213
- * const params = undefined;
214
- * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
215
- * useWithSafeValues(params, defaults);
216
- * // Returns { initialPage: 1, pageSize: 10, infinite: false }
217
- * ```
184
+ * Always returns itself to allow infinite chaining without throwing.
218
185
  */
219
- const useWithSafeValues = (params, defaultValues) => {
220
- const shouldUseDefaults = typeof params === "boolean" && params;
221
- const initialPageRef = (0, react.useRef)(shouldUseDefaults ? defaultValues.initialPage : params?.initialPage ?? defaultValues.initialPage);
222
- const pageSizeRef = (0, react.useRef)(shouldUseDefaults ? defaultValues.pageSize : params?.pageSize ?? defaultValues.pageSize);
223
- const newObj = {};
224
- for (const key of Object.keys(defaultValues)) newObj[key] = shouldUseDefaults ? defaultValues[key] : params?.[key] ?? defaultValues[key];
225
- return {
226
- ...newObj,
227
- initialPage: initialPageRef.current,
228
- pageSize: pageSizeRef.current
229
- };
186
+ function createRecursiveProxy(label) {
187
+ const callableTarget = function noop$1() {};
188
+ let self;
189
+ self = new Proxy(callableTarget, {
190
+ get(_target, prop) {
191
+ if (prop === "then") return;
192
+ if (prop === "toString") return () => `[${label}]`;
193
+ if (prop === Symbol.toPrimitive) return () => 0;
194
+ return self;
195
+ },
196
+ apply() {
197
+ return self;
198
+ },
199
+ construct() {
200
+ return self;
201
+ },
202
+ has() {
203
+ return false;
204
+ },
205
+ set() {
206
+ return false;
207
+ }
208
+ });
209
+ return self;
210
+ }
211
+ const mockQueryClient = createRecursiveProxy("ClerkMockQueryClient");
212
+ const useClerkQueryClient = () => {
213
+ const clerk = useClerkInstanceContext();
214
+ const queryClient = clerk.__internal_queryClient;
215
+ const [, setQueryClientLoaded] = (0, react.useState)(typeof queryClient === "object" && "__tag" in queryClient && queryClient.__tag === "clerk-rq-client");
216
+ (0, react.useEffect)(() => {
217
+ const _setQueryClientLoaded = () => setQueryClientLoaded(true);
218
+ clerk.on("queryClientStatus", _setQueryClientLoaded);
219
+ return () => {
220
+ clerk.off("queryClientStatus", _setQueryClientLoaded);
221
+ };
222
+ }, [clerk, setQueryClientLoaded]);
223
+ const isLoaded = typeof queryClient === "object" && "__tag" in queryClient && queryClient.__tag === "clerk-rq-client";
224
+ return [queryClient?.client || mockQueryClient, isLoaded];
230
225
  };
226
+
227
+ //#endregion
228
+ //#region src/react/clerk-rq/useBaseQuery.ts
229
+ /**
230
+ * Stripped down version of useBaseQuery from @tanstack/query-core.
231
+ * This implementation allows for an observer to be created every time a query client changes.
232
+ */
231
233
  /**
232
- * Returns an object containing only the keys from the first object that are not present in the second object.
233
- * Useful for extracting unique parameters that should be passed to a request while excluding common cache keys.
234
+ * An alternative `useBaseQuery` implementation that allows for an observer to be created every time a query client changes.
234
235
  *
235
236
  * @internal
237
+ */
238
+ function useBaseQuery(options, Observer) {
239
+ const [client, isQueryClientLoaded] = useClerkQueryClient();
240
+ const defaultedOptions = isQueryClientLoaded ? client.defaultQueryOptions(options) : options;
241
+ defaultedOptions._optimisticResults = "optimistic";
242
+ const observer = react.useMemo(() => {
243
+ return new Observer(client, defaultedOptions);
244
+ }, [client]);
245
+ const result = observer.getOptimisticResult(defaultedOptions);
246
+ const shouldSubscribe = options.subscribed !== false;
247
+ react.useSyncExternalStore(react.useCallback((onStoreChange) => {
248
+ const unsubscribe = shouldSubscribe ? observer.subscribe(__tanstack_query_core.notifyManager.batchCalls(onStoreChange)) : __tanstack_query_core.noop;
249
+ observer.updateResult();
250
+ return unsubscribe;
251
+ }, [observer, shouldSubscribe]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
252
+ react.useEffect(() => {
253
+ observer.setOptions(defaultedOptions);
254
+ }, [defaultedOptions, observer]);
255
+ if (!isQueryClientLoaded) return {
256
+ data: void 0,
257
+ error: null,
258
+ isLoading: false,
259
+ isFetching: false,
260
+ status: "pending"
261
+ };
262
+ return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result;
263
+ }
264
+
265
+ //#endregion
266
+ //#region src/react/clerk-rq/useInfiniteQuery.ts
267
+ /**
268
+ *
269
+ */
270
+ function useClerkInfiniteQuery(options) {
271
+ return useBaseQuery(options, __tanstack_query_core.InfiniteQueryObserver);
272
+ }
273
+
274
+ //#endregion
275
+ //#region src/react/clerk-rq/useQuery.ts
276
+ /**
236
277
  *
237
- * @example
238
- * ```typescript
239
- * // Example 1: Basic usage
240
- * const obj1 = { name: 'John', age: 30, city: 'NY' };
241
- * const obj2 = { name: 'John', age: 30 };
242
- * getDifferentKeys(obj1, obj2); // Returns { city: 'NY' }
243
- *
244
- * // Example 2: With cache keys
245
- * const requestParams = { page: 1, limit: 10, userId: '123' };
246
- * const cacheKeys = { userId: '123' };
247
- * getDifferentKeys(requestParams, cacheKeys); // Returns { page: 1, limit: 10 }
248
- * ```
249
278
  */
250
- function getDifferentKeys(obj1, obj2) {
251
- const keysSet = new Set(Object.keys(obj2));
252
- const differentKeysObject = {};
253
- for (const key1 of Object.keys(obj1)) if (!keysSet.has(key1)) differentKeysObject[key1] = obj1[key1];
254
- return differentKeysObject;
279
+ function useClerkQuery(options) {
280
+ return useBaseQuery(options, __tanstack_query_core.QueryObserver);
255
281
  }
256
282
 
257
283
  //#endregion
@@ -282,114 +308,249 @@ function usePreviousValue(value) {
282
308
  }
283
309
 
284
310
  //#endregion
285
- //#region src/react/hooks/usePagesOrInfinite.swr.tsx
286
- const cachingSWROptions = {
287
- dedupingInterval: 1e3 * 60,
288
- focusThrottleInterval: 1e3 * 60 * 2
289
- };
290
- const cachingSWRInfiniteOptions = {
291
- ...cachingSWROptions,
292
- revalidateFirstPage: false
293
- };
311
+ //#region src/react/hooks/useClearQueriesOnSignOut.ts
312
+ const withInfiniteKey = (key) => [key, `${key}-inf`];
294
313
  /**
295
- * A flexible pagination hook that supports both traditional pagination and infinite loading.
296
- * It provides a unified API for handling paginated data fetching, with built-in caching through SWR.
297
- * The hook can operate in two modes:
298
- * - Traditional pagination: Fetches one page at a time with page navigation
299
- * - Infinite loading: Accumulates data as more pages are loaded.
300
- *
301
- * Features:
302
- * - Cache management with SWR
303
- * - Loading and error states
304
- * - Page navigation helpers
305
- * - Data revalidation and updates
306
- * - Support for keeping previous data while loading.
314
+ * Clears React Query caches associated with the given stable prefixes when
315
+ * the authenticated state transitions from signed-in to signed-out.
307
316
  *
308
317
  * @internal
309
318
  */
319
+ function useClearQueriesOnSignOut(options) {
320
+ const { isSignedOut, stableKeys, authenticated = true, onCleanup } = options;
321
+ const stableKeysRef = (0, react.useRef)(stableKeys);
322
+ const [queryClient] = useClerkQueryClient();
323
+ const previousIsSignedIn = usePreviousValue(!isSignedOut);
324
+ if (authenticated !== true) return;
325
+ (0, react.useEffect)(() => {
326
+ if (previousIsSignedIn && isSignedOut === true) {
327
+ queryClient.removeQueries({ predicate: (query) => {
328
+ const [cachedStableKey, queryAuthenticated] = query.queryKey;
329
+ return queryAuthenticated === true && typeof cachedStableKey === "string" && (Array.isArray(stableKeysRef.current) ? stableKeysRef.current.includes(cachedStableKey) : stableKeysRef.current === cachedStableKey);
330
+ } });
331
+ onCleanup?.();
332
+ }
333
+ }, [
334
+ isSignedOut,
335
+ previousIsSignedIn,
336
+ queryClient
337
+ ]);
338
+ }
339
+
340
+ //#endregion
341
+ //#region src/react/hooks/usePagesOrInfinite.shared.ts
342
+ /**
343
+ * A hook that safely merges user-provided pagination options with default values.
344
+ * It caches initial pagination values (page and size) until component unmount to prevent unwanted rerenders.
345
+ *
346
+ * @internal
347
+ *
348
+ * @example
349
+ * ```typescript
350
+ * // Example 1: With user-provided options
351
+ * const userOptions = { initialPage: 2, pageSize: 20, infinite: true };
352
+ * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
353
+ * useWithSafeValues(userOptions, defaults);
354
+ * // Returns { initialPage: 2, pageSize: 20, infinite: true }
355
+ *
356
+ * // Example 2: With boolean true (use defaults)
357
+ * const params = true;
358
+ * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
359
+ * useWithSafeValues(params, defaults);
360
+ * // Returns { initialPage: 1, pageSize: 10, infinite: false }
361
+ *
362
+ * // Example 3: With undefined options (fallback to defaults)
363
+ * const params = undefined;
364
+ * const defaults = { initialPage: 1, pageSize: 10, infinite: false };
365
+ * useWithSafeValues(params, defaults);
366
+ * // Returns { initialPage: 1, pageSize: 10, infinite: false }
367
+ * ```
368
+ */
369
+ const useWithSafeValues = (params, defaultValues) => {
370
+ const shouldUseDefaults = typeof params === "boolean" && params;
371
+ const initialPageRef = (0, react.useRef)(shouldUseDefaults ? defaultValues.initialPage : params?.initialPage ?? defaultValues.initialPage);
372
+ const pageSizeRef = (0, react.useRef)(shouldUseDefaults ? defaultValues.pageSize : params?.pageSize ?? defaultValues.pageSize);
373
+ const newObj = {};
374
+ for (const key of Object.keys(defaultValues)) newObj[key] = shouldUseDefaults ? defaultValues[key] : params?.[key] ?? defaultValues[key];
375
+ return {
376
+ ...newObj,
377
+ initialPage: initialPageRef.current,
378
+ pageSize: pageSizeRef.current
379
+ };
380
+ };
381
+
382
+ //#endregion
383
+ //#region src/react/hooks/usePagesOrInfinite.tsx
310
384
  const usePagesOrInfinite = (params) => {
311
385
  const { fetcher, config, keys } = params;
312
386
  const [paginatedPage, setPaginatedPage] = (0, react.useState)(config.initialPage ?? 1);
313
387
  const initialPageRef = (0, react.useRef)(config.initialPage ?? 1);
314
388
  const pageSizeRef = (0, react.useRef)(config.pageSize ?? 10);
315
389
  const enabled = config.enabled ?? true;
316
- const cacheMode = config.__experimental_mode === "cache";
390
+ const isSignedIn = config.isSignedIn;
317
391
  const triggerInfinite = config.infinite ?? false;
392
+ const cacheMode = config.__experimental_mode === "cache";
318
393
  const keepPreviousData = config.keepPreviousData ?? false;
319
- const isSignedIn = config.isSignedIn;
320
- const pagesCacheKey = {
321
- ...toSWRQuery(keys),
322
- initialPage: paginatedPage,
323
- pageSize: pageSizeRef.current
324
- };
325
- const previousIsSignedIn = usePreviousValue(isSignedIn);
326
- const shouldFetch = !triggerInfinite && enabled && (!cacheMode ? !!fetcher : true);
327
- const { data: swrData, isValidating: swrIsValidating, isLoading: swrIsLoading, error: swrError, mutate: swrMutate } = (0, swr.default)(typeof isSignedIn === "boolean" ? previousIsSignedIn === true && isSignedIn === false ? pagesCacheKey : isSignedIn ? shouldFetch ? pagesCacheKey : null : null : shouldFetch ? pagesCacheKey : null, !cacheMode && !!fetcher ? (cacheKeyParams) => {
328
- if (isSignedIn === false || shouldFetch === false) return null;
329
- return fetcher(getDifferentKeys(cacheKeyParams, {
330
- type: keys.queryKey[0],
331
- ...keys.queryKey[2]
332
- }));
333
- } : null, {
334
- keepPreviousData,
335
- ...cachingSWROptions
394
+ const [queryClient] = useClerkQueryClient();
395
+ const queriesEnabled = enabled && Boolean(fetcher) && !cacheMode && isSignedIn !== false;
396
+ const [forceUpdateCounter, setForceUpdateCounter] = (0, react.useState)(0);
397
+ const forceUpdate = (0, react.useCallback)((updater) => {
398
+ setForceUpdateCounter(updater);
399
+ }, []);
400
+ const pagesQueryKey = (0, react.useMemo)(() => {
401
+ const [stablePrefix, authenticated, tracked, untracked] = keys.queryKey;
402
+ return [
403
+ stablePrefix,
404
+ authenticated,
405
+ tracked,
406
+ {
407
+ ...untracked,
408
+ args: {
409
+ ...untracked.args,
410
+ initialPage: paginatedPage,
411
+ pageSize: pageSizeRef.current
412
+ }
413
+ }
414
+ ];
415
+ }, [keys.queryKey, paginatedPage]);
416
+ const singlePageQuery = useClerkQuery({
417
+ queryKey: pagesQueryKey,
418
+ queryFn: ({ queryKey }) => {
419
+ const { args } = queryKey[3];
420
+ if (!fetcher) return;
421
+ return fetcher(args);
422
+ },
423
+ staleTime: 6e4,
424
+ enabled: queriesEnabled && !triggerInfinite,
425
+ placeholderData: defineKeepPreviousDataFn(keepPreviousData)
336
426
  });
337
- const { data: swrInfiniteData, isLoading: swrInfiniteIsLoading, isValidating: swrInfiniteIsValidating, error: swrInfiniteError, size, setSize, mutate: swrInfiniteMutate } = (0, swr_infinite.default)((pageIndex) => {
338
- if (!triggerInfinite || !enabled || isSignedIn === false) return null;
427
+ const infiniteQueryKey = (0, react.useMemo)(() => {
428
+ const [stablePrefix, authenticated, tracked, untracked] = keys.queryKey;
429
+ return [
430
+ stablePrefix + "-inf",
431
+ authenticated,
432
+ tracked,
433
+ untracked
434
+ ];
435
+ }, [keys.queryKey]);
436
+ const infiniteQuery = useClerkInfiniteQuery({
437
+ queryKey: infiniteQueryKey,
438
+ initialPageParam: config.initialPage ?? 1,
439
+ getNextPageParam: (lastPage, allPages, lastPageParam) => {
440
+ const total = lastPage?.total_count ?? 0;
441
+ return (allPages.length + (config.initialPage ? config.initialPage - 1 : 0)) * (config.pageSize ?? 10) < total ? lastPageParam + 1 : void 0;
442
+ },
443
+ queryFn: ({ pageParam, queryKey }) => {
444
+ const { args } = queryKey[3];
445
+ if (!fetcher) return;
446
+ return fetcher({
447
+ ...args,
448
+ initialPage: pageParam,
449
+ pageSize: pageSizeRef.current
450
+ });
451
+ },
452
+ staleTime: 6e4,
453
+ enabled: queriesEnabled && triggerInfinite
454
+ });
455
+ useClearQueriesOnSignOut({
456
+ isSignedOut: isSignedIn === false,
457
+ authenticated: keys.authenticated,
458
+ stableKeys: withInfiniteKey(keys.stableKey),
459
+ onCleanup: () => {
460
+ setPaginatedPage(initialPageRef.current);
461
+ Promise.resolve().then(() => forceUpdate((n) => n + 1));
462
+ }
463
+ });
464
+ const { data, count, page } = (0, react.useMemo)(() => {
465
+ if (triggerInfinite) {
466
+ const cachedData = queryClient.getQueryData(infiniteQueryKey);
467
+ const pages = queriesEnabled ? infiniteQuery.data?.pages ?? cachedData?.pages ?? [] : cachedData?.pages ?? [];
468
+ const validPages = Array.isArray(pages) ? pages.filter(Boolean) : [];
469
+ return {
470
+ data: validPages.map((a) => a?.data).flat().filter(Boolean) ?? [],
471
+ count: validPages[validPages.length - 1]?.total_count ?? 0,
472
+ page: validPages.length > 0 ? validPages.length : initialPageRef.current
473
+ };
474
+ }
475
+ const pageData = queriesEnabled ? singlePageQuery.data ?? queryClient.getQueryData(pagesQueryKey) : queryClient.getQueryData(pagesQueryKey);
339
476
  return {
340
- ...toSWRQuery(keys),
341
- initialPage: initialPageRef.current + pageIndex,
342
- pageSize: pageSizeRef.current
477
+ data: Array.isArray(pageData?.data) ? pageData.data : [],
478
+ count: typeof pageData?.total_count === "number" ? pageData.total_count : 0,
479
+ page: paginatedPage
343
480
  };
344
- }, (cacheKeyParams) => {
345
- const requestParams = getDifferentKeys(cacheKeyParams, {
346
- type: keys.queryKey[0],
347
- ...keys.queryKey[2]
348
- });
349
- return fetcher?.(requestParams);
350
- }, cachingSWRInfiniteOptions);
351
- const page = (0, react.useMemo)(() => {
352
- if (triggerInfinite) return size;
353
- return paginatedPage;
354
481
  }, [
482
+ queriesEnabled,
483
+ forceUpdateCounter,
355
484
  triggerInfinite,
356
- size,
485
+ infiniteQuery.data?.pages,
486
+ singlePageQuery.data,
487
+ queryClient,
488
+ infiniteQueryKey,
489
+ pagesQueryKey,
357
490
  paginatedPage
358
491
  ]);
359
492
  const fetchPage = (0, react.useCallback)((numberOrgFn) => {
360
493
  if (triggerInfinite) {
361
- setSize(numberOrgFn);
494
+ const next = typeof numberOrgFn === "function" ? numberOrgFn(page) : numberOrgFn;
495
+ const targetCount = Math.max(0, next);
496
+ const cachedData = queryClient.getQueryData(infiniteQueryKey);
497
+ if (targetCount - (infiniteQuery.data?.pages ?? cachedData?.pages ?? []).length > 0) infiniteQuery.fetchNextPage({ cancelRefetch: false });
362
498
  return;
363
499
  }
364
500
  return setPaginatedPage(numberOrgFn);
365
- }, [setSize, triggerInfinite]);
366
- const data = (0, react.useMemo)(() => {
367
- if (triggerInfinite) return swrInfiniteData?.map((a) => a?.data).flat() ?? [];
368
- return swrData?.data ?? [];
369
- }, [
370
- triggerInfinite,
371
- swrData,
372
- swrInfiniteData
373
- ]);
374
- const count = (0, react.useMemo)(() => {
375
- if (triggerInfinite) return swrInfiniteData?.[swrInfiniteData?.length - 1]?.total_count || 0;
376
- return swrData?.total_count ?? 0;
377
501
  }, [
502
+ infiniteQuery,
503
+ page,
378
504
  triggerInfinite,
379
- swrData,
380
- swrInfiniteData
505
+ queryClient,
506
+ infiniteQueryKey
381
507
  ]);
382
- const isLoading = triggerInfinite ? swrInfiniteIsLoading : swrIsLoading;
383
- const isFetching = triggerInfinite ? swrInfiniteIsValidating : swrIsValidating;
384
- const error = (triggerInfinite ? swrInfiniteError : swrError) ?? null;
508
+ const isLoading = triggerInfinite ? infiniteQuery.isLoading : singlePageQuery.isLoading;
509
+ const isFetching = triggerInfinite ? infiniteQuery.isFetching : singlePageQuery.isFetching;
510
+ const error = (triggerInfinite ? infiniteQuery.error : singlePageQuery.error) ?? null;
385
511
  const isError = !!error;
386
512
  const fetchNext = (0, react.useCallback)(() => {
387
- fetchPage((n) => Math.max(0, n + 1));
388
- }, [fetchPage]);
513
+ if (triggerInfinite) {
514
+ infiniteQuery.fetchNextPage({ cancelRefetch: false });
515
+ return;
516
+ }
517
+ setPaginatedPage((n) => Math.max(0, n + 1));
518
+ }, [infiniteQuery, triggerInfinite]);
389
519
  const fetchPrevious = (0, react.useCallback)(() => {
390
- fetchPage((n) => Math.max(0, n - 1));
391
- }, [fetchPage]);
520
+ if (triggerInfinite) return;
521
+ setPaginatedPage((n) => Math.max(0, n - 1));
522
+ }, [triggerInfinite]);
392
523
  const offsetCount = (initialPageRef.current - 1) * pageSizeRef.current;
524
+ const pageCount = Math.ceil((count - offsetCount) / pageSizeRef.current);
525
+ const hasNextPage = triggerInfinite ? Boolean(infiniteQuery.hasNextPage) : count - offsetCount * pageSizeRef.current > page * pageSizeRef.current;
526
+ const hasPreviousPage = triggerInfinite ? Boolean(infiniteQuery.hasPreviousPage) : (page - 1) * pageSizeRef.current > offsetCount * pageSizeRef.current;
527
+ const setData = (value) => {
528
+ if (triggerInfinite) {
529
+ queryClient.setQueryData(infiniteQueryKey, (prevValue = {}) => {
530
+ const prevPages = Array.isArray(prevValue?.pages) ? prevValue.pages : [];
531
+ const nextPages = typeof value === "function" ? value(prevPages) : value;
532
+ return {
533
+ ...prevValue,
534
+ pages: nextPages
535
+ };
536
+ });
537
+ forceUpdate((n) => n + 1);
538
+ return Promise.resolve();
539
+ }
540
+ queryClient.setQueryData(pagesQueryKey, (prevValue = {
541
+ data: [],
542
+ total_count: 0
543
+ }) => {
544
+ return typeof value === "function" ? value(prevValue) : value;
545
+ });
546
+ forceUpdate((n) => n + 1);
547
+ return Promise.resolve();
548
+ };
549
+ const revalidate = async () => {
550
+ await queryClient.invalidateQueries({ queryKey: keys.invalidationKey });
551
+ const [stablePrefix, ...rest] = keys.invalidationKey;
552
+ return queryClient.invalidateQueries({ queryKey: [stablePrefix + "-inf", ...rest] });
553
+ };
393
554
  return {
394
555
  data,
395
556
  count,
@@ -398,19 +559,19 @@ const usePagesOrInfinite = (params) => {
398
559
  isFetching,
399
560
  isError,
400
561
  page,
401
- pageCount: Math.ceil((count - offsetCount) / pageSizeRef.current),
562
+ pageCount,
402
563
  fetchPage,
403
564
  fetchNext,
404
565
  fetchPrevious,
405
- hasNextPage: count - offsetCount * pageSizeRef.current > page * pageSizeRef.current,
406
- hasPreviousPage: (page - 1) * pageSizeRef.current > offsetCount * pageSizeRef.current,
407
- revalidate: triggerInfinite ? () => swrInfiniteMutate() : () => swrMutate(),
408
- setData: triggerInfinite ? (value) => swrInfiniteMutate(value, { revalidate: false }) : (value) => swrMutate(value, { revalidate: false })
566
+ hasNextPage,
567
+ hasPreviousPage,
568
+ revalidate,
569
+ setData
409
570
  };
410
571
  };
411
572
 
412
573
  //#endregion
413
- //#region src/react/hooks/useAPIKeys.swr.tsx
574
+ //#region src/react/hooks/useAPIKeys.tsx
414
575
  /**
415
576
  * @internal
416
577
  *
@@ -471,7 +632,7 @@ function useAPIKeys(params) {
471
632
  ...safeValues.query ? { query: safeValues.query } : {}
472
633
  };
473
634
  const isEnabled = (safeValues.enabled ?? true) && clerk.loaded;
474
- const result = usePagesOrInfinite({
635
+ return usePagesOrInfinite({
475
636
  fetcher: clerk.apiKeys?.getAll ? (params$1) => clerk.apiKeys.getAll({
476
637
  ...params$1,
477
638
  subject: safeValues.subject
@@ -491,17 +652,6 @@ function useAPIKeys(params) {
491
652
  untracked: { args: hookParams }
492
653
  })
493
654
  });
494
- const { mutate } = (0, swr.useSWRConfig)();
495
- const invalidateAll = (0, react.useCallback)(() => {
496
- return mutate((key) => {
497
- if (!key || typeof key !== "object") return false;
498
- return "type" in key && key.type === "apiKeys" && "subject" in key && key.subject === safeValues.subject;
499
- });
500
- }, [mutate, safeValues.subject]);
501
- return {
502
- ...result,
503
- revalidate: invalidateAll
504
- };
505
655
  }
506
656
 
507
657
  //#endregion
@@ -1142,7 +1292,7 @@ const useSafeLayoutEffect = typeof window !== "undefined" ? react.default.useLay
1142
1292
 
1143
1293
  //#endregion
1144
1294
  //#region src/react/hooks/useSession.ts
1145
- const hookName$3 = `useSession`;
1295
+ const hookName$2 = `useSession`;
1146
1296
  /**
1147
1297
  * The `useSession()` hook provides access to the current user's [`Session`](https://clerk.com/docs/reference/javascript/session) object, as well as helpers for setting the active session.
1148
1298
  *
@@ -1192,10 +1342,10 @@ const hookName$3 = `useSession`;
1192
1342
  * </Tabs>
1193
1343
  */
1194
1344
  const useSession = () => {
1195
- useAssertWrappedByClerkProvider(hookName$3);
1345
+ useAssertWrappedByClerkProvider(hookName$2);
1196
1346
  const session = useSessionContext();
1197
1347
  const clerk = useClerkInstanceContext();
1198
- clerk.telemetry?.record(require_telemetry.eventMethodCalled(hookName$3));
1348
+ clerk.telemetry?.record(require_telemetry.eventMethodCalled(hookName$2));
1199
1349
  if (session === void 0) return {
1200
1350
  isLoaded: false,
1201
1351
  isSignedIn: void 0,
@@ -1215,7 +1365,7 @@ const useSession = () => {
1215
1365
 
1216
1366
  //#endregion
1217
1367
  //#region src/react/hooks/useSessionList.ts
1218
- const hookName$2 = "useSessionList";
1368
+ const hookName$1 = "useSessionList";
1219
1369
  /**
1220
1370
  * The `useSessionList()` hook returns an array of [`Session`](https://clerk.com/docs/reference/javascript/session) objects that have been registered on the client device.
1221
1371
  *
@@ -1260,10 +1410,10 @@ const hookName$2 = "useSessionList";
1260
1410
  * </Tabs>
1261
1411
  */
1262
1412
  const useSessionList = () => {
1263
- useAssertWrappedByClerkProvider(hookName$2);
1413
+ useAssertWrappedByClerkProvider(hookName$1);
1264
1414
  const isomorphicClerk = useClerkInstanceContext();
1265
1415
  const client = useClientContext();
1266
- useClerkInstanceContext().telemetry?.record(require_telemetry.eventMethodCalled(hookName$2));
1416
+ useClerkInstanceContext().telemetry?.record(require_telemetry.eventMethodCalled(hookName$1));
1267
1417
  if (!client) return {
1268
1418
  isLoaded: false,
1269
1419
  sessions: void 0,
@@ -1278,7 +1428,7 @@ const useSessionList = () => {
1278
1428
 
1279
1429
  //#endregion
1280
1430
  //#region src/react/hooks/useUser.ts
1281
- const hookName$1 = "useUser";
1431
+ const hookName = "useUser";
1282
1432
  /**
1283
1433
  * The `useUser()` hook provides access to the current user's [`User`](https://clerk.com/docs/reference/javascript/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 and initialized.
1284
1434
  *
@@ -1410,9 +1560,9 @@ const hookName$1 = "useUser";
1410
1560
  * </Tabs>
1411
1561
  */
1412
1562
  function useUser() {
1413
- useAssertWrappedByClerkProvider(hookName$1);
1563
+ useAssertWrappedByClerkProvider(hookName);
1414
1564
  const user = useUserContext();
1415
- useClerkInstanceContext().telemetry?.record(require_telemetry.eventMethodCalled(hookName$1));
1565
+ useClerkInstanceContext().telemetry?.record(require_telemetry.eventMethodCalled(hookName));
1416
1566
  if (user === void 0) return {
1417
1567
  isLoaded: false,
1418
1568
  isSignedIn: void 0,
@@ -1615,11 +1765,11 @@ function useBillingHookEnabled(params) {
1615
1765
  *
1616
1766
  * @internal
1617
1767
  */
1618
- function createBillingPaginatedHook({ hookName: hookName$4, resourceType, useFetcher, options }) {
1768
+ function createBillingPaginatedHook({ hookName: hookName$3, resourceType, useFetcher, options }) {
1619
1769
  return function useBillingHook(params) {
1620
1770
  const { for: _for, enabled: externalEnabled,...paginationParams } = params || {};
1621
1771
  const safeFor = _for || "user";
1622
- useAssertWrappedByClerkProvider(hookName$4);
1772
+ useAssertWrappedByClerkProvider(hookName$3);
1623
1773
  const fetchFn = useFetcher(safeFor);
1624
1774
  const safeValues = useWithSafeValues(paginationParams, {
1625
1775
  initialPage: 1,
@@ -1631,7 +1781,7 @@ function createBillingPaginatedHook({ hookName: hookName$4, resourceType, useFet
1631
1781
  const clerk = useClerkInstanceContext();
1632
1782
  const user = useUserContext();
1633
1783
  const { organization } = useOrganizationContext();
1634
- clerk.telemetry?.record(require_telemetry.eventMethodCalled(hookName$4));
1784
+ clerk.telemetry?.record(require_telemetry.eventMethodCalled(hookName$3));
1635
1785
  const isForOrganization = safeFor === "organization";
1636
1786
  const billingEnabled = useBillingHookEnabled({
1637
1787
  for: safeFor,
@@ -1660,7 +1810,7 @@ function createBillingPaginatedHook({ hookName: hookName$4, resourceType, useFet
1660
1810
  authenticated: !options?.unauthenticated,
1661
1811
  tracked: options?.unauthenticated ? { for: safeFor } : {
1662
1812
  userId: user?.id,
1663
- ...isForOrganization ? { ["_orgId"]: organization?.id } : {}
1813
+ ...isForOrganization ? { orgId: organization?.id } : {}
1664
1814
  },
1665
1815
  untracked: { args: hookParams }
1666
1816
  })
@@ -1754,44 +1904,53 @@ function useSubscriptionCacheKeys(params) {
1754
1904
  }
1755
1905
 
1756
1906
  //#endregion
1757
- //#region src/react/hooks/useSubscription.swr.tsx
1758
- const hookName = "useSubscription";
1907
+ //#region src/react/hooks/useSubscription.tsx
1908
+ const HOOK_NAME = "useSubscription";
1759
1909
  /**
1760
- * This is the existing implementation of useSubscription using SWR.
1761
- * It is kept here for backwards compatibility until our next major version.
1762
- *
1763
1910
  * @internal
1764
1911
  */
1765
1912
  function useSubscription(params) {
1766
- useAssertWrappedByClerkProvider(hookName);
1913
+ useAssertWrappedByClerkProvider(HOOK_NAME);
1767
1914
  const clerk = useClerkInstanceContext();
1768
1915
  const user = useUserContext();
1769
1916
  const { organization } = useOrganizationContext();
1770
- const environment = clerk.__internal_environment;
1771
- clerk.telemetry?.record(require_telemetry.eventMethodCalled(hookName));
1772
- const billingEnabled = params?.for === "organization" ? environment?.commerceSettings.billing.organization.enabled : environment?.commerceSettings.billing.user.enabled;
1773
- const isEnabled = (params?.enabled ?? true) && billingEnabled;
1774
- const { queryKey } = useSubscriptionCacheKeys({
1917
+ const billingEnabled = useBillingHookEnabled(params);
1918
+ const recordedRef = (0, react.useRef)(false);
1919
+ (0, react.useEffect)(() => {
1920
+ if (!recordedRef.current && clerk?.telemetry) {
1921
+ clerk.telemetry.record(require_telemetry.eventMethodCalled(HOOK_NAME));
1922
+ recordedRef.current = true;
1923
+ }
1924
+ }, [clerk]);
1925
+ const keepPreviousData = params?.keepPreviousData ?? false;
1926
+ const [queryClient] = useClerkQueryClient();
1927
+ const { queryKey, invalidationKey, stableKey, authenticated } = useSubscriptionCacheKeys({
1775
1928
  userId: user?.id,
1776
1929
  orgId: organization?.id,
1777
1930
  for: params?.for
1778
1931
  });
1779
- const swr$1 = (0, swr.default)(isEnabled ? { queryKey } : null, ({ queryKey: queryKey$1 }) => {
1780
- const args = queryKey$1[3].args;
1781
- if (queryKey$1[2].userId) return clerk.billing.getSubscription(args);
1782
- return null;
1783
- }, {
1784
- dedupingInterval: 1e3 * 60,
1785
- keepPreviousData: params?.keepPreviousData
1932
+ const queriesEnabled = Boolean(user?.id && billingEnabled);
1933
+ useClearQueriesOnSignOut({
1934
+ isSignedOut: user === null,
1935
+ authenticated,
1936
+ stableKeys: stableKey
1937
+ });
1938
+ const query = useClerkQuery({
1939
+ queryKey,
1940
+ queryFn: ({ queryKey: queryKey$1 }) => {
1941
+ const obj = queryKey$1[3];
1942
+ return clerk.billing.getSubscription(obj.args);
1943
+ },
1944
+ staleTime: 1e3 * 60,
1945
+ enabled: queriesEnabled,
1946
+ placeholderData: defineKeepPreviousDataFn(keepPreviousData && queriesEnabled)
1786
1947
  });
1787
- const revalidate = (0, react.useCallback)(() => {
1788
- swr$1.mutate();
1789
- }, [swr$1]);
1948
+ const revalidate = (0, react.useCallback)(() => queryClient.invalidateQueries({ queryKey: invalidationKey }), [queryClient, invalidationKey]);
1790
1949
  return {
1791
- data: swr$1.data,
1792
- error: swr$1.error,
1793
- isLoading: swr$1.isLoading,
1794
- isFetching: swr$1.isValidating,
1950
+ data: query.data,
1951
+ error: query.error ?? void 0,
1952
+ isLoading: query.isLoading,
1953
+ isFetching: query.isFetching,
1795
1954
  revalidate
1796
1955
  };
1797
1956
  }
@@ -1871,40 +2030,47 @@ function useStatementQueryCacheKeys(params) {
1871
2030
  }
1872
2031
 
1873
2032
  //#endregion
1874
- //#region src/react/hooks/useStatementQuery.swr.tsx
2033
+ //#region src/react/hooks/useStatementQuery.tsx
1875
2034
  /**
1876
- * This is the existing implementation of useStatementQuery using SWR.
1877
- * It is kept here for backwards compatibility until our next major version.
1878
- *
1879
2035
  * @internal
1880
2036
  */
1881
- function __internal_useStatementQuery(params = {}) {
1882
- const { statementId = null, enabled = true, keepPreviousData = false, for: forType = "user" } = params;
2037
+ function useStatementQuery(params = {}) {
2038
+ const { statementId = null, keepPreviousData = false, for: forType = "user" } = params;
1883
2039
  const clerk = useClerkInstanceContext();
1884
2040
  const user = useUserContext();
1885
2041
  const { organization } = useOrganizationContext();
1886
2042
  const organizationId = forType === "organization" ? organization?.id ?? null : null;
1887
- const { queryKey } = useStatementQueryCacheKeys({
2043
+ const { queryKey, stableKey, authenticated } = useStatementQueryCacheKeys({
1888
2044
  statementId,
1889
2045
  userId: user?.id ?? null,
1890
2046
  orgId: organizationId,
1891
2047
  for: forType
1892
2048
  });
1893
- const swr$1 = (0, swr.default)(Boolean(statementId) && enabled && (forType !== "organization" || Boolean(organizationId)) ? queryKey : null, () => {
1894
- if (!statementId) throw new Error("statementId is required to fetch a statement");
1895
- return clerk.billing.getStatement({
1896
- id: statementId,
1897
- orgId: organizationId ?? void 0
1898
- });
1899
- }, {
1900
- dedupingInterval: 1e3 * 60,
1901
- keepPreviousData
2049
+ const billingEnabled = useBillingHookEnabled(params);
2050
+ const queryEnabled = Boolean(statementId) && billingEnabled;
2051
+ useClearQueriesOnSignOut({
2052
+ isSignedOut: user === null,
2053
+ authenticated,
2054
+ stableKeys: stableKey
2055
+ });
2056
+ const query = useClerkQuery({
2057
+ queryKey,
2058
+ queryFn: () => {
2059
+ if (!statementId) throw new Error("statementId is required to fetch a statement");
2060
+ return clerk.billing.getStatement({
2061
+ id: statementId,
2062
+ orgId: organizationId ?? void 0
2063
+ });
2064
+ },
2065
+ enabled: queryEnabled,
2066
+ placeholderData: defineKeepPreviousDataFn(keepPreviousData),
2067
+ staleTime: 1e3 * 60
1902
2068
  });
1903
2069
  return {
1904
- data: swr$1.data,
1905
- error: swr$1.error ?? null,
1906
- isLoading: swr$1.isLoading,
1907
- isFetching: swr$1.isValidating
2070
+ data: query.data,
2071
+ error: query.error ?? null,
2072
+ isLoading: query.isLoading,
2073
+ isFetching: query.isFetching
1908
2074
  };
1909
2075
  }
1910
2076
 
@@ -1923,31 +2089,32 @@ function usePlanDetailsQueryCacheKeys(params) {
1923
2089
  }
1924
2090
 
1925
2091
  //#endregion
1926
- //#region src/react/hooks/usePlanDetailsQuery.swr.tsx
2092
+ //#region src/react/hooks/usePlanDetailsQuery.tsx
1927
2093
  /**
1928
- * This is the existing implementation of usePlanDetailsQuery using SWR.
1929
- * It is kept here for backwards compatibility until our next major version.
1930
- *
1931
2094
  * @internal
1932
2095
  */
1933
- function usePlanDetailsQuery(params = {}) {
1934
- const { planId, initialPlan = null, enabled = true, keepPreviousData = true } = params;
2096
+ function __internal_usePlanDetailsQuery(params = {}) {
2097
+ const { planId, initialPlan = null, keepPreviousData = true } = params;
1935
2098
  const clerk = useClerkInstanceContext();
1936
2099
  const targetPlanId = planId ?? initialPlan?.id ?? null;
1937
2100
  const { queryKey } = usePlanDetailsQueryCacheKeys({ planId: targetPlanId });
1938
- const swr$1 = (0, swr.default)(Boolean(targetPlanId) && enabled ? queryKey : null, () => {
1939
- if (!targetPlanId) throw new Error("planId is required to fetch plan details");
1940
- return clerk.billing.getPlan({ id: targetPlanId });
1941
- }, {
1942
- dedupingInterval: 1e3 * 60,
1943
- keepPreviousData,
1944
- fallbackData: initialPlan ?? void 0
2101
+ const billingEnabled = useBillingHookEnabled({ authenticated: false });
2102
+ const query = useClerkQuery({
2103
+ queryKey,
2104
+ queryFn: () => {
2105
+ if (!targetPlanId) throw new Error("planId is required to fetch plan details");
2106
+ return clerk.billing.getPlan({ id: targetPlanId });
2107
+ },
2108
+ enabled: Boolean(targetPlanId) && billingEnabled,
2109
+ initialData: initialPlan ?? void 0,
2110
+ placeholderData: defineKeepPreviousDataFn(keepPreviousData),
2111
+ initialDataUpdatedAt: 0
1945
2112
  });
1946
2113
  return {
1947
- data: swr$1.data,
1948
- error: swr$1.error ?? null,
1949
- isLoading: swr$1.isLoading,
1950
- isFetching: swr$1.isValidating
2114
+ data: query.data,
2115
+ error: query.error ?? null,
2116
+ isLoading: query.isLoading,
2117
+ isFetching: query.isFetching
1951
2118
  };
1952
2119
  }
1953
2120
 
@@ -1979,37 +2146,44 @@ function usePaymentAttemptQueryCacheKeys(params) {
1979
2146
  }
1980
2147
 
1981
2148
  //#endregion
1982
- //#region src/react/hooks/usePaymentAttemptQuery.swr.tsx
2149
+ //#region src/react/hooks/usePaymentAttemptQuery.tsx
1983
2150
  /**
1984
- * This is the existing implementation of usePaymentAttemptQuery using SWR.
1985
- * It is kept here for backwards compatibility until our next major version.
1986
- *
1987
2151
  * @internal
1988
2152
  */
1989
- function __internal_usePaymentAttemptQuery(params) {
1990
- const { paymentAttemptId, enabled = true, keepPreviousData = false, for: forType = "user" } = params;
2153
+ function usePaymentAttemptQuery(params) {
2154
+ const { paymentAttemptId, keepPreviousData = false, for: forType = "user" } = params;
1991
2155
  const clerk = useClerkInstanceContext();
1992
2156
  const user = useUserContext();
1993
2157
  const { organization } = useOrganizationContext();
1994
2158
  const organizationId = forType === "organization" ? organization?.id ?? null : null;
1995
- const { queryKey } = usePaymentAttemptQueryCacheKeys({
2159
+ const { queryKey, stableKey, authenticated } = usePaymentAttemptQueryCacheKeys({
1996
2160
  paymentAttemptId,
1997
2161
  userId: user?.id ?? null,
1998
2162
  orgId: organizationId,
1999
2163
  for: forType
2000
2164
  });
2001
- const swr$1 = (0, swr.default)(Boolean(paymentAttemptId) && enabled && (forType !== "organization" || Boolean(organizationId)) ? { queryKey } : null, ({ queryKey: queryKey$1 }) => {
2002
- const args = queryKey$1[3].args;
2003
- return clerk.billing.getPaymentAttempt(args);
2004
- }, {
2005
- dedupingInterval: 1e3 * 60,
2006
- keepPreviousData
2165
+ const billingEnabled = useBillingHookEnabled(params);
2166
+ const queryEnabled = Boolean(paymentAttemptId) && billingEnabled;
2167
+ useClearQueriesOnSignOut({
2168
+ isSignedOut: user === null,
2169
+ authenticated,
2170
+ stableKeys: stableKey
2171
+ });
2172
+ const query = useClerkQuery({
2173
+ queryKey,
2174
+ queryFn: ({ queryKey: queryKey$1 }) => {
2175
+ const args = queryKey$1[3].args;
2176
+ return clerk.billing.getPaymentAttempt(args);
2177
+ },
2178
+ enabled: queryEnabled,
2179
+ placeholderData: defineKeepPreviousDataFn(keepPreviousData),
2180
+ staleTime: 1e3 * 60
2007
2181
  });
2008
2182
  return {
2009
- data: swr$1.data,
2010
- error: swr$1.error ?? null,
2011
- isLoading: swr$1.isLoading,
2012
- isFetching: swr$1.isValidating
2183
+ data: query.data,
2184
+ error: query.error ?? null,
2185
+ isLoading: query.isLoading,
2186
+ isFetching: query.isFetching
2013
2187
  };
2014
2188
  }
2015
2189
 
@@ -2263,74 +2437,90 @@ const createElementComponent = (type, isServer) => {
2263
2437
  const PaymentElement$1 = createElementComponent("payment", typeof window === "undefined");
2264
2438
 
2265
2439
  //#endregion
2266
- //#region src/react/billing/useInitializePaymentMethod.swr.tsx
2440
+ //#region src/react/billing/useInitializePaymentMethod.tsx
2267
2441
  /**
2268
- * This is the existing implementation of the payment method initializer using SWR.
2269
- * It is kept here for backwards compatibility until our next major version.
2270
- *
2271
2442
  * @internal
2272
2443
  */
2273
2444
  function useInitializePaymentMethod(options) {
2274
- const { for: forType = "user" } = options ?? {};
2445
+ const { for: forType } = options ?? {};
2275
2446
  const { organization } = useOrganizationContext();
2276
2447
  const user = useUserContext();
2277
2448
  const resource = forType === "organization" ? organization : user;
2278
- const { data, trigger } = (0, swr_mutation.default)(resource?.id ? {
2279
- key: "billing-payment-method-initialize",
2280
- resourceId: resource.id,
2281
- for: forType
2282
- } : null, () => {
2283
- return resource?.initializePaymentMethod({ gateway: "stripe" });
2449
+ const billingEnabled = useBillingHookEnabled(options);
2450
+ const queryKey = (0, react.useMemo)(() => {
2451
+ return ["billing-payment-method-initialize", { resourceId: resource?.id }];
2452
+ }, [resource?.id]);
2453
+ const query = useClerkQuery({
2454
+ queryKey,
2455
+ queryFn: async () => {
2456
+ if (!resource) return;
2457
+ return resource.initializePaymentMethod({ gateway: "stripe" });
2458
+ },
2459
+ enabled: Boolean(resource?.id) && billingEnabled,
2460
+ staleTime: 1e3 * 60,
2461
+ refetchOnWindowFocus: false,
2462
+ placeholderData: defineKeepPreviousDataFn(true)
2284
2463
  });
2285
- (0, react.useEffect)(() => {
2286
- if (!resource?.id) return;
2287
- trigger().catch(() => {});
2288
- }, [resource?.id, trigger]);
2464
+ const [queryClient] = useClerkQueryClient();
2465
+ const initializePaymentMethod = (0, react.useCallback)(async () => {
2466
+ if (!resource) return;
2467
+ const result = await resource.initializePaymentMethod({ gateway: "stripe" });
2468
+ queryClient.setQueryData(queryKey, result);
2469
+ return result;
2470
+ }, [
2471
+ queryClient,
2472
+ queryKey,
2473
+ resource
2474
+ ]);
2289
2475
  return {
2290
- initializedPaymentMethod: data,
2291
- initializePaymentMethod: trigger
2476
+ initializedPaymentMethod: query.data ?? void 0,
2477
+ initializePaymentMethod
2292
2478
  };
2293
2479
  }
2294
2480
 
2295
2481
  //#endregion
2296
- //#region src/react/billing/useStripeClerkLibs.swr.tsx
2482
+ //#region src/react/billing/useStripeClerkLibs.tsx
2297
2483
  /**
2298
- * This is the existing implementation of the Stripe libraries loader using SWR.
2299
- * It is kept here for backwards compatibility until our next major version.
2300
- *
2301
2484
  * @internal
2302
2485
  */
2303
2486
  function useStripeClerkLibs() {
2304
2487
  const clerk = useClerk();
2305
- return (0, swr.default)("clerk-stripe-sdk", async () => {
2306
- return { loadStripe: await clerk.__internal_loadStripeJs() };
2307
- }, {
2308
- keepPreviousData: true,
2309
- revalidateOnFocus: false,
2310
- dedupingInterval: Infinity
2488
+ return useClerkQuery({
2489
+ queryKey: ["clerk-stripe-sdk"],
2490
+ queryFn: async () => {
2491
+ return { loadStripe: await clerk.__internal_loadStripeJs() };
2492
+ },
2493
+ enabled: useBillingHookEnabled(),
2494
+ staleTime: Infinity,
2495
+ refetchOnWindowFocus: false,
2496
+ placeholderData: defineKeepPreviousDataFn(true)
2311
2497
  }).data ?? null;
2312
2498
  }
2313
2499
 
2314
2500
  //#endregion
2315
- //#region src/react/billing/useStripeLoader.swr.tsx
2501
+ //#region src/react/billing/useStripeLoader.tsx
2316
2502
  /**
2317
- * This is the existing implementation of the Stripe instance loader using SWR.
2318
- * It is kept here for backwards compatibility until our next major version.
2319
- *
2320
2503
  * @internal
2321
2504
  */
2322
2505
  function useStripeLoader(options) {
2323
2506
  const { stripeClerkLibs, externalGatewayId, stripePublishableKey } = options;
2324
- return (0, swr.default)(stripeClerkLibs && externalGatewayId && stripePublishableKey ? {
2325
- key: "stripe-sdk",
2326
- externalGatewayId,
2327
- stripePublishableKey
2328
- } : null, ({ stripePublishableKey: stripePublishableKey$1, externalGatewayId: externalGatewayId$1 }) => {
2329
- return stripeClerkLibs?.loadStripe(stripePublishableKey$1, { stripeAccount: externalGatewayId$1 });
2330
- }, {
2331
- keepPreviousData: true,
2332
- revalidateOnFocus: false,
2333
- dedupingInterval: 1e3 * 60
2507
+ const queryKey = (0, react.useMemo)(() => {
2508
+ return ["stripe-sdk", {
2509
+ externalGatewayId,
2510
+ stripePublishableKey
2511
+ }];
2512
+ }, [externalGatewayId, stripePublishableKey]);
2513
+ const billingEnabled = useBillingHookEnabled({ authenticated: true });
2514
+ return useClerkQuery({
2515
+ queryKey,
2516
+ queryFn: () => {
2517
+ if (!stripeClerkLibs || !externalGatewayId || !stripePublishableKey) return null;
2518
+ return stripeClerkLibs.loadStripe(stripePublishableKey, { stripeAccount: externalGatewayId });
2519
+ },
2520
+ enabled: Boolean(stripeClerkLibs && externalGatewayId && stripePublishableKey) && billingEnabled,
2521
+ staleTime: 1e3 * 60,
2522
+ refetchOnWindowFocus: false,
2523
+ placeholderData: defineKeepPreviousDataFn(true)
2334
2524
  }).data;
2335
2525
  }
2336
2526
 
@@ -2520,9 +2710,9 @@ exports.__experimental_usePaymentMethods = usePaymentMethods;
2520
2710
  exports.__experimental_usePlans = usePlans;
2521
2711
  exports.__experimental_useStatements = useStatements;
2522
2712
  exports.__experimental_useSubscription = useSubscription;
2523
- exports.__internal_usePaymentAttemptQuery = __internal_usePaymentAttemptQuery;
2524
- exports.__internal_usePlanDetailsQuery = usePlanDetailsQuery;
2525
- exports.__internal_useStatementQuery = __internal_useStatementQuery;
2713
+ exports.__internal_usePaymentAttemptQuery = usePaymentAttemptQuery;
2714
+ exports.__internal_usePlanDetailsQuery = __internal_usePlanDetailsQuery;
2715
+ exports.__internal_useStatementQuery = useStatementQuery;
2526
2716
  exports.assertContextExists = assertContextExists;
2527
2717
  exports.createContextAndHook = createContextAndHook;
2528
2718
  exports.isDeeplyEqual = isDeeplyEqual;