@clerk/shared 4.32.0-snapshot.v20260904162929 → 4.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_chunks/{error-C-B61RHn.js → error-CdWUgmMd.js} +4 -4
- package/dist/_chunks/error-CdWUgmMd.js.map +1 -0
- package/dist/_chunks/{error-CYyD2kei.mjs → error-wrUdW78M.mjs} +4 -4
- package/dist/_chunks/error-wrUdW78M.mjs.map +1 -0
- package/dist/error.js +1 -1
- package/dist/error.mjs +1 -1
- package/dist/errors/errorThrower.d.mts +3 -3
- package/dist/errors/errorThrower.d.ts +3 -3
- package/dist/errors/errorThrower.js +3 -3
- package/dist/internal/clerk-js/componentGuards.d.mts +2 -1
- package/dist/internal/clerk-js/componentGuards.d.ts +2 -1
- package/dist/internal/clerk-js/componentGuards.js +4 -0
- package/dist/internal/clerk-js/componentGuards.js.map +1 -1
- package/dist/internal/clerk-js/componentGuards.mjs +4 -1
- package/dist/internal/clerk-js/componentGuards.mjs.map +1 -1
- package/dist/internal/clerk-js/passkeys.js +1 -1
- package/dist/internal/clerk-js/passkeys.mjs +1 -1
- package/dist/internal/clerk-js/protectCheck.js +1 -1
- package/dist/internal/clerk-js/protectCheck.mjs +1 -1
- package/dist/internal/clerk-js/warnings.d.mts +3 -2
- package/dist/internal/clerk-js/warnings.d.ts +3 -2
- package/dist/internal/clerk-js/warnings.js +2 -1
- package/dist/internal/clerk-js/warnings.js.map +1 -1
- package/dist/internal/clerk-js/warnings.mjs +2 -1
- package/dist/internal/clerk-js/warnings.mjs.map +1 -1
- package/dist/internal/clerk-js/web3.js +1 -1
- package/dist/internal/clerk-js/web3.mjs +1 -1
- package/dist/keys.d.mts +1 -6
- package/dist/keys.d.ts +1 -6
- package/dist/keys.js +2 -8
- package/dist/keys.js.map +1 -1
- package/dist/keys.mjs +3 -8
- package/dist/keys.mjs.map +1 -1
- package/dist/loadClerkJsScript.js +2 -2
- package/dist/loadClerkJsScript.js.map +1 -1
- package/dist/loadClerkJsScript.mjs +2 -2
- package/dist/loadClerkJsScript.mjs.map +1 -1
- package/dist/react/hooks/index.d.mts +2 -0
- package/dist/react/hooks/index.d.ts +2 -0
- package/dist/react/hooks/index.js +2 -0
- package/dist/react/hooks/useClerk.d.mts +1 -1
- package/dist/react/hooks/useClerk.d.ts +1 -1
- package/dist/react/hooks/useClerk.js +1 -1
- package/dist/react/hooks/useOAuthDeviceVerification.types.d.mts +31 -2
- package/dist/react/hooks/useOAuthDeviceVerification.types.d.ts +31 -2
- package/dist/react/hooks/useOrganization.d.mts +1 -1
- package/dist/react/hooks/useOrganization.d.ts +1 -1
- package/dist/react/hooks/useOrganizationDirectorySync.d.mts +27 -0
- package/dist/react/hooks/useOrganizationDirectorySync.d.ts +27 -0
- package/dist/react/hooks/useOrganizationDirectorySync.js +89 -0
- package/dist/react/hooks/useOrganizationDirectorySync.shared.js +49 -0
- package/dist/react/hooks/useOrganizationDirectorySyncUsers.d.mts +53 -0
- package/dist/react/hooks/useOrganizationDirectorySyncUsers.d.ts +53 -0
- package/dist/react/hooks/useOrganizationDirectorySyncUsers.js +71 -0
- package/dist/react/hooks/useOrganizationEnterpriseConnectionTestRuns.js +7 -5
- package/dist/react/hooks/useOrganizationList.d.mts +1 -1
- package/dist/react/hooks/useOrganizationList.d.ts +1 -1
- package/dist/react/hooks/useReverification.d.mts +1 -1
- package/dist/react/hooks/useReverification.d.ts +1 -1
- package/dist/react/index.d.mts +3 -1
- package/dist/react/index.d.ts +3 -1
- package/dist/react/index.js +199 -8
- package/dist/react/index.js.map +1 -1
- package/dist/react/index.mjs +198 -9
- package/dist/react/index.mjs.map +1 -1
- package/dist/react/stable-keys.js +5 -1
- package/dist/types/billing.d.mts +1 -1
- package/dist/types/billing.d.ts +1 -1
- package/dist/types/clerk.d.mts +19 -3
- package/dist/types/clerk.d.ts +19 -3
- package/dist/types/directorySync.d.mts +123 -0
- package/dist/types/directorySync.d.ts +123 -0
- package/dist/types/elementIds.d.mts +2 -2
- package/dist/types/elementIds.d.ts +2 -2
- package/dist/types/hooks.d.mts +11 -11
- package/dist/types/hooks.d.ts +11 -11
- package/dist/types/index.d.mts +2 -1
- package/dist/types/index.d.ts +2 -1
- package/dist/types/localization.d.mts +108 -0
- package/dist/types/localization.d.ts +108 -0
- package/dist/types/oauthApplication.d.mts +76 -3
- package/dist/types/oauthApplication.d.ts +76 -3
- package/dist/types/organization.d.mts +11 -1
- package/dist/types/organization.d.ts +11 -1
- package/dist/types/organizationDomain.d.mts +3 -3
- package/dist/types/organizationDomain.d.ts +3 -3
- package/dist/types/signIn.d.mts +2 -0
- package/dist/types/signIn.d.ts +2 -0
- package/dist/types/signInFuture.d.mts +19 -7
- package/dist/types/signInFuture.d.ts +19 -7
- package/dist/types/signUpFuture.d.mts +5 -5
- package/dist/types/signUpFuture.d.ts +5 -5
- package/dist/types/user.d.mts +1 -1
- package/dist/types/user.d.ts +1 -1
- package/dist/types/userSettings.d.mts +2 -1
- package/dist/types/userSettings.d.ts +2 -1
- package/dist/versionSelector.js +1 -1
- package/dist/versionSelector.js.map +1 -1
- package/dist/versionSelector.mjs +1 -1
- package/dist/versionSelector.mjs.map +1 -1
- package/package.json +2 -2
- package/dist/_chunks/error-C-B61RHn.js.map +0 -1
- package/dist/_chunks/error-CYyD2kei.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"warnings.mjs","names":[],"sources":["../../../src/internal/clerk-js/warnings.ts"],"sourcesContent":["import type { Serializable } from '../../types';\n\nconst formatWarning = (msg: string) => {\n return `🔒 Clerk:\\n${msg.trim()}\\n(This notice only appears in development)`;\n};\n\nconst createMessageForDisabledOrganizations = (\n componentName:\n | 'OrganizationProfile'\n | 'InviteMembers'\n | 'OrganizationSwitcher'\n | 'OrganizationList'\n | 'CreateOrganization'\n | 'TaskChooseOrganization'\n | 'ConfigureSSO',\n) => {\n return formatWarning(\n `The <${componentName}/> cannot be rendered when the feature is turned off. Visit 'dashboard.clerk.com' to enable the feature. Since the feature is turned off, this is no-op.`,\n );\n};\n\nconst createCannotRenderComponentWhenOrgDoesNotExist = (\n componentName: 'OrganizationProfile' | 'InviteMembers' | 'ConfigureSSO',\n) => {\n return formatWarning(\n `<${componentName}/> cannot render unless an organization is active. Since no organization is currently active, this is no-op.`,\n );\n};\n\nconst createCannotRenderComponentWhenPermissionIsMissing = (componentName: 'InviteMembers', permission: string) => {\n return formatWarning(\n `<${componentName}/> cannot render unless the current user has the \\`${permission}\\` permission. Since the current user is missing this permission, this is no-op. Render it only for members who can manage memberships, for example by wrapping it in <Show when={{ permission: '${permission}' }}>.`,\n );\n};\n\nconst createMessageForDisabledBilling = (componentName: 'PricingTable' | 'Checkout' | 'PlanDetails') => {\n return formatWarning(\n `The <${componentName}/> component cannot be rendered when billing is disabled. Visit 'https://dashboard.clerk.com
|
|
1
|
+
{"version":3,"file":"warnings.mjs","names":[],"sources":["../../../src/internal/clerk-js/warnings.ts"],"sourcesContent":["import type { Serializable } from '../../types';\n\nconst formatWarning = (msg: string) => {\n return `🔒 Clerk:\\n${msg.trim()}\\n(This notice only appears in development)`;\n};\n\nconst createMessageForDisabledOrganizations = (\n componentName:\n | 'OrganizationProfile'\n | 'InviteMembers'\n | 'OrganizationSwitcher'\n | 'OrganizationList'\n | 'CreateOrganization'\n | 'TaskChooseOrganization'\n | 'ConfigureSSO'\n | 'ConfigureDirectorySync',\n) => {\n return formatWarning(\n `The <${componentName}/> cannot be rendered when the feature is turned off. Visit 'dashboard.clerk.com' to enable the feature. Since the feature is turned off, this is no-op.`,\n );\n};\n\nconst createCannotRenderComponentWhenOrgDoesNotExist = (\n componentName: 'OrganizationProfile' | 'InviteMembers' | 'ConfigureSSO' | 'ConfigureDirectorySync',\n) => {\n return formatWarning(\n `<${componentName}/> cannot render unless an organization is active. Since no organization is currently active, this is no-op.`,\n );\n};\n\nconst createCannotRenderComponentWhenPermissionIsMissing = (componentName: 'InviteMembers', permission: string) => {\n return formatWarning(\n `<${componentName}/> cannot render unless the current user has the \\`${permission}\\` permission. Since the current user is missing this permission, this is no-op. Render it only for members who can manage memberships, for example by wrapping it in <Show when={{ permission: '${permission}' }}>.`,\n );\n};\n\nconst createMessageForDisabledBilling = (componentName: 'PricingTable' | 'Checkout' | 'PlanDetails') => {\n return formatWarning(\n `The <${componentName}/> component cannot be rendered when billing is disabled. Visit 'https://dashboard.clerk.com/~/billing/settings' to follow the necessary steps to enable billing. Since billing is disabled, this is no-op.`,\n );\n};\n\nconst propertyAsFunctionNotSupported = (property: 'proxyUrl' | 'domain') => {\n return formatWarning(\n `${property} as a function is not supported in this environment. The value will be ignored. Provide an absolute URL instead.`,\n );\n};\n\nconst warnings = {\n proxyUrlAsFunctionNotSupported: propertyAsFunctionNotSupported('proxyUrl'),\n domainAsFunctionNotSupported: propertyAsFunctionNotSupported('domain'),\n cannotRenderComponentWhenSessionExists:\n 'The <SignUp/> and <SignIn/> components cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the Home URL instead.',\n cannotRenderSignUpComponentWhenSessionExists:\n 'The <SignUp/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the value set in `afterSignUp` URL instead.',\n cannotRenderSignUpComponentWhenTaskExists:\n 'The <SignUp/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.',\n cannotRenderComponentWhenTaskDoesNotExist:\n '<TaskChooseOrganization/> cannot render unless a session task is pending. Clerk is redirecting to the value set in `redirectUrlComplete` instead.',\n cannotRenderSignInComponentWhenSessionExists:\n 'The <SignIn/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the `afterSignIn` URL instead.',\n cannotRenderSignInComponentWhenTaskExists:\n 'The <SignIn/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.',\n cannotRenderComponentWhenUserDoesNotExist:\n '<UserProfile/> cannot render unless a user is signed in. Since no user is signed in, this is no-op.',\n createCannotRenderComponentWhenOrgDoesNotExist,\n createCannotRenderComponentWhenPermissionIsMissing,\n cannotRenderAnyOrganizationComponent: createMessageForDisabledOrganizations,\n cannotRenderAnyBillingComponent: createMessageForDisabledBilling,\n cannotOpenUserProfile:\n 'The UserProfile modal cannot render unless a user is signed in. Since no user is signed in, this is no-op.',\n cannotOpenCheckout:\n 'The Checkout drawer cannot render unless a user is signed in. Since no user is signed in, this is no-op.',\n cannotOpenSignInOrSignUp:\n 'The <SignIn/> and <SignUp/> modals are hidden because a user is already signed in and this application is configured for single-session mode. This is expected behavior — no action is needed. To allow rendering while signed in, enable multi-session mode in your Clerk Dashboard.',\n cannotRenderAPIKeysComponent:\n 'The <APIKeys/> component cannot be rendered when API keys is disabled. Since API keys is disabled, this is no-op.',\n cannotRenderAPIKeysComponentForOrgWhenUnauthorized:\n 'The <APIKeys/> component cannot be rendered for an organization unless a user has the required permissions. Since the user does not have the necessary permissions, this is no-op.',\n cannotRenderAPIKeysComponentForUserWhenDisabled:\n 'The <APIKeys/> component cannot be rendered when user API keys are disabled. Since user API keys are disabled, this is no-op.',\n cannotRenderAPIKeysComponentForOrgWhenDisabled:\n 'The <APIKeys/> component cannot be rendered when organization API keys are disabled. Since organization API keys are disabled, this is no-op.',\n cannotRenderOAuthConsentComponentWhenUserDoesNotExist:\n '<OAuthConsent/> cannot render unless a user is signed in. Since no user is signed in, this is no-op.',\n cannotRenderOAuthDeviceVerificationComponentWhenUserDoesNotExist:\n '<OAuthDeviceVerification/> cannot render unless a user is signed in. Since no user is signed in, this is no-op.',\n cannotRenderConfigureSSOComponentWhenUserDoesNotExist:\n '<ConfigureSSO/> cannot render unless a user is signed in. Since no user is signed in, this is no-op.',\n cannotRenderConfigureSSOComponentWhenDisabled:\n 'The <ConfigureSSO/> component cannot be rendered when self-serve SSO is disabled. Visit `https://dashboard.clerk.com` to enable the feature. Since self-serve SSO is disabled, this is no-op.',\n cannotRenderConfigureDirectorySyncComponentWhenDisabled:\n 'The <ConfigureDirectorySync/> component cannot be rendered when self-serve Directory Sync is disabled. Since self-serve Directory Sync is disabled, this is no-op.',\n cannotRenderConfigureSSOComponentWhenEmailAddressDisabled:\n 'The <ConfigureSSO/> component cannot be rendered when email addresses are disabled on the instance. Visit `https://dashboard.clerk.com` to enable email addresses. Since email addresses are disabled, this is no-op.',\n};\n\ntype SerializableWarnings = Serializable<typeof warnings>;\n\nfor (const key of Object.keys(warnings)) {\n const item = warnings[key as keyof typeof warnings];\n if (typeof item !== 'function') {\n warnings[key as keyof SerializableWarnings] = formatWarning(item);\n }\n}\n\nexport { warnings };\n"],"mappings":";AAEA,MAAM,iBAAiB,QAAgB;CACrC,OAAO,cAAc,IAAI,KAAK,EAAE;AAClC;AAEA,MAAM,yCACJ,kBASG;CACH,OAAO,cACL,QAAQ,cAAc,yJACxB;AACF;AAEA,MAAM,kDACJ,kBACG;CACH,OAAO,cACL,IAAI,cAAc,6GACpB;AACF;AAEA,MAAM,sDAAsD,eAAgC,eAAuB;CACjH,OAAO,cACL,IAAI,cAAc,qDAAqD,WAAW,mMAAmM,WAAW,OAClS;AACF;AAEA,MAAM,mCAAmC,kBAA+D;CACtG,OAAO,cACL,QAAQ,cAAc,4MACxB;AACF;AAEA,MAAM,kCAAkC,aAAoC;CAC1E,OAAO,cACL,GAAG,SAAS,iHACd;AACF;AAEA,MAAM,WAAW;CACf,gCAAgC,+BAA+B,UAAU;CACzE,8BAA8B,+BAA+B,QAAQ;CACrE,wCACE;CACF,8CACE;CACF,2CACE;CACF,2CACE;CACF,8CACE;CACF,2CACE;CACF,2CACE;CACF;CACA;CACA,sCAAsC;CACtC,iCAAiC;CACjC,uBACE;CACF,oBACE;CACF,0BACE;CACF,8BACE;CACF,oDACE;CACF,iDACE;CACF,gDACE;CACF,uDACE;CACF,kEACE;CACF,uDACE;CACF,+CACE;CACF,yDACE;CACF,2DACE;AACJ;AAIA,KAAK,MAAM,OAAO,OAAO,KAAK,QAAQ,GAAG;CACvC,MAAM,OAAO,SAAS;CACtB,IAAI,OAAO,SAAS,YAClB,SAAS,OAAqC,cAAc,IAAI;AAEpE"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_clerkRuntimeError = require('../../_chunks/clerkRuntimeError-CYZdTZ_x.js');
|
|
3
|
-
const require_error = require('../../_chunks/error-
|
|
3
|
+
const require_error = require('../../_chunks/error-CdWUgmMd.js');
|
|
4
4
|
const require_internal_clerk_js_hex = require('./hex.js');
|
|
5
5
|
const require_internal_clerk_js_injectedWeb3EthProviders = require('./injectedWeb3EthProviders.js');
|
|
6
6
|
const require_internal_clerk_js_injectedWeb3SolanaProviders = require('./injectedWeb3SolanaProviders.js');
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as ClerkRuntimeError } from "../../_chunks/clerkRuntimeError-DlesLWqO.mjs";
|
|
2
|
-
import { y as buildErrorThrower } from "../../_chunks/error-
|
|
2
|
+
import { y as buildErrorThrower } from "../../_chunks/error-wrUdW78M.mjs";
|
|
3
3
|
import { toHex } from "./hex.mjs";
|
|
4
4
|
import { getInjectedWeb3EthProviders } from "./injectedWeb3EthProviders.mjs";
|
|
5
5
|
import { getInjectedWeb3SolanaProviders } from "./injectedWeb3SolanaProviders.mjs";
|
package/dist/keys.d.mts
CHANGED
|
@@ -41,11 +41,6 @@ declare function buildPublishableKey(frontendApi: string): string;
|
|
|
41
41
|
* })
|
|
42
42
|
*/
|
|
43
43
|
declare function publishableKeyFromHost(host: string, fallbackKey?: string): string;
|
|
44
|
-
/**
|
|
45
|
-
* The one sentence that explains how to get working Clerk keys without a Clerk account.
|
|
46
|
-
* Shared by every message that mentions `clerk init` so there is a single sentence to keep true.
|
|
47
|
-
*/
|
|
48
|
-
declare const accountlessInitGuidance = "`npx clerk@latest init` creates a Clerk application and writes keys to your .env file. No Clerk account or login required and the command is non-interactive.";
|
|
49
44
|
declare function parsePublishableKey(key: string | undefined, options: ParsePublishableKeyOptions & {
|
|
50
45
|
fatal: true;
|
|
51
46
|
}): PublishableKey;
|
|
@@ -123,4 +118,4 @@ declare function getCookieSuffix(publishableKey: string, subtle?: SubtleCrypto):
|
|
|
123
118
|
*/
|
|
124
119
|
declare const getSuffixedCookieName: (cookieName: string, cookieSuffix: string) => string;
|
|
125
120
|
//#endregion
|
|
126
|
-
export {
|
|
121
|
+
export { buildPublishableKey, createDevOrStagingUrlCache, getCookieSuffix, getSuffixedCookieName, isDevelopmentFromPublishableKey, isDevelopmentFromSecretKey, isProductionFromPublishableKey, isProductionFromSecretKey, isPublishableKey, parsePublishableKey, publishableKeyFromHost };
|
package/dist/keys.d.ts
CHANGED
|
@@ -41,11 +41,6 @@ declare function buildPublishableKey(frontendApi: string): string;
|
|
|
41
41
|
* })
|
|
42
42
|
*/
|
|
43
43
|
declare function publishableKeyFromHost(host: string, fallbackKey?: string): string;
|
|
44
|
-
/**
|
|
45
|
-
* The one sentence that explains how to get working Clerk keys without a Clerk account.
|
|
46
|
-
* Shared by every message that mentions `clerk init` so there is a single sentence to keep true.
|
|
47
|
-
*/
|
|
48
|
-
declare const accountlessInitGuidance = "`npx clerk@latest init` creates a Clerk application and writes keys to your .env file. No Clerk account or login required and the command is non-interactive.";
|
|
49
44
|
declare function parsePublishableKey(key: string | undefined, options: ParsePublishableKeyOptions & {
|
|
50
45
|
fatal: true;
|
|
51
46
|
}): PublishableKey;
|
|
@@ -123,4 +118,4 @@ declare function getCookieSuffix(publishableKey: string, subtle?: SubtleCrypto):
|
|
|
123
118
|
*/
|
|
124
119
|
declare const getSuffixedCookieName: (cookieName: string, cookieSuffix: string) => string;
|
|
125
120
|
//#endregion
|
|
126
|
-
export {
|
|
121
|
+
export { buildPublishableKey, createDevOrStagingUrlCache, getCookieSuffix, getSuffixedCookieName, isDevelopmentFromPublishableKey, isDevelopmentFromSecretKey, isProductionFromPublishableKey, isProductionFromSecretKey, isPublishableKey, parsePublishableKey, publishableKeyFromHost };
|
package/dist/keys.js
CHANGED
|
@@ -65,18 +65,13 @@ function isValidDecodedPublishableKey(decoded) {
|
|
|
65
65
|
if (withoutTrailing.includes("$")) return false;
|
|
66
66
|
return withoutTrailing.includes(".");
|
|
67
67
|
}
|
|
68
|
-
/**
|
|
69
|
-
* The one sentence that explains how to get working Clerk keys without a Clerk account.
|
|
70
|
-
* Shared by every message that mentions `clerk init` so there is a single sentence to keep true.
|
|
71
|
-
*/
|
|
72
|
-
const accountlessInitGuidance = "`npx clerk@latest init` creates a Clerk application and writes keys to your .env file. No Clerk account or login required and the command is non-interactive.";
|
|
73
68
|
const fatalKeyGuidance = `To create a Clerk application with valid keys, in your terminal run:
|
|
74
69
|
|
|
75
70
|
npx clerk@latest init
|
|
76
71
|
|
|
77
|
-
|
|
72
|
+
\`npx clerk@latest init\` creates a Clerk application and writes keys to your .env file. No Clerk account or login required and the command is non-interactive.
|
|
78
73
|
|
|
79
|
-
If you have a Clerk application, run \`npx clerk@latest env pull\` to write the keys (\`--instance prod\` for production keys). Or copy them from https://dashboard.clerk.com
|
|
74
|
+
If you have a Clerk application, run \`npx clerk@latest env pull\` to write the keys (\`--instance prod\` for production keys). Or copy them from https://dashboard.clerk.com/~/api-keys.`;
|
|
80
75
|
/**
|
|
81
76
|
* Parses and validates a publishable key, extracting the frontend API and instance type.
|
|
82
77
|
*
|
|
@@ -227,7 +222,6 @@ const getSuffixedCookieName = (cookieName, cookieSuffix) => {
|
|
|
227
222
|
};
|
|
228
223
|
|
|
229
224
|
//#endregion
|
|
230
|
-
exports.accountlessInitGuidance = accountlessInitGuidance;
|
|
231
225
|
exports.buildPublishableKey = buildPublishableKey;
|
|
232
226
|
exports.createDevOrStagingUrlCache = createDevOrStagingUrlCache;
|
|
233
227
|
exports.getCookieSuffix = getCookieSuffix;
|
package/dist/keys.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keys.js","names":["LEGACY_DEV_INSTANCE_SUFFIXES","isomorphicBtoa","isomorphicAtob","DEV_OR_STAGING_SUFFIXES"],"sources":["../src/keys.ts"],"sourcesContent":["import { DEV_OR_STAGING_SUFFIXES, LEGACY_DEV_INSTANCE_SUFFIXES } from './constants';\nimport { isomorphicAtob } from './isomorphicAtob';\nimport { isomorphicBtoa } from './isomorphicBtoa';\nimport type { PublishableKey } from './types';\n\n/**\n * Configuration options for parsing publishable keys.\n */\ntype ParsePublishableKeyOptions = {\n /** Whether to throw an error if parsing fails */\n fatal?: boolean;\n /** Custom domain to use for satellite instances */\n domain?: string;\n /** Proxy URL to use instead of the decoded frontend API */\n proxyUrl?: string;\n /** Whether this is a satellite instance */\n isSatellite?: boolean;\n};\n\n/** Prefix used for production publishable keys */\nconst PUBLISHABLE_KEY_LIVE_PREFIX = 'pk_live_';\n\n/** Prefix used for development publishable keys */\nconst PUBLISHABLE_KEY_TEST_PREFIX = 'pk_test_';\n\n/**\n * Regular expression that matches development frontend API keys.\n * Matches patterns like: foo-bar-13.clerk.accounts.dev.\n */\nconst PUBLISHABLE_FRONTEND_API_DEV_REGEX = /^(([a-z]+)-){2}([0-9]{1,2})\\.clerk\\.accounts([a-z.]*)(dev|com)$/i;\n\n/**\n * Converts a frontend API URL into an unpadded base64-encoded publishable key.\n *\n * @param frontendApi - The frontend API URL (e.g., 'clerk.example.com').\n * @returns An unpadded base64-encoded publishable key with appropriate prefix (pk_live_ or pk_test_).\n */\nexport function buildPublishableKey(frontendApi: string): string {\n const isDevKey =\n PUBLISHABLE_FRONTEND_API_DEV_REGEX.test(frontendApi) ||\n (frontendApi.startsWith('clerk.') && LEGACY_DEV_INSTANCE_SUFFIXES.some(s => frontendApi.endsWith(s)));\n const keyPrefix = isDevKey ? PUBLISHABLE_KEY_TEST_PREFIX : PUBLISHABLE_KEY_LIVE_PREFIX;\n return `${keyPrefix}${isomorphicBtoa(`${frontendApi}$`).replace(/=+$/, '')}`;\n}\n\n/**\n * Derives a publishable key from the current hostname. Intended for multi-domain\n * setups (e.g. custom domains on top of a default domain) where the correct key\n * must be resolved per request.\n *\n * Pass the configured publishable key as `fallbackKey` so that development\n * instances (pk_test_) are returned as-is instead of being incorrectly derived\n * from the host (e.g. localhost).\n *\n * @example\n * // React (use window.location.hostname, not window.location.host, to avoid including the port)\n * <ClerkProvider publishableKey={publishableKeyFromHost(window.location.hostname, import.meta.env.VITE_CLERK_PUBLISHABLE_KEY)}>\n *\n * @example\n * // Express (inside clerkMiddleware callback)\n * // Validate req.hostname against a known allowlist before passing it in.\n * // When `trust proxy` is enabled, req.hostname reads from X-Forwarded-Host\n * // and can be spoofed if your proxy is not properly configured.\n * const ALLOWED_HOSTS = ['domain-a.com', 'domain-b.com'];\n * clerkMiddleware((req) => {\n * if (!ALLOWED_HOSTS.includes(req.hostname)) throw new Error('Unknown host');\n * return { publishableKey: publishableKeyFromHost(req.hostname, process.env.CLERK_PUBLISHABLE_KEY) };\n * })\n */\nexport function publishableKeyFromHost(host: string, fallbackKey?: string): string {\n if (fallbackKey && isDevelopmentFromPublishableKey(fallbackKey)) {\n return fallbackKey;\n }\n const hostname = host.toLowerCase().replace(/:\\d+$/, '');\n if (!hostname) {\n throw new Error('Host must not be empty.');\n }\n return buildPublishableKey(`clerk.${hostname}`);\n}\n\n/**\n * Validates that a decoded publishable key has the correct format.\n * The decoded value should be a frontend API followed by exactly one '$' at the end.\n *\n * @param decoded - The decoded publishable key string to validate.\n * @returns `true` if the decoded key has valid format, `false` otherwise.\n */\nfunction isValidDecodedPublishableKey(decoded: string): boolean {\n if (!decoded.endsWith('$')) {\n return false;\n }\n\n const withoutTrailing = decoded.slice(0, -1);\n if (withoutTrailing.includes('$')) {\n return false;\n }\n\n return withoutTrailing.includes('.');\n}\n\n/**\n * The one sentence that explains how to get working Clerk keys without a Clerk account.\n * Shared by every message that mentions `clerk init` so there is a single sentence to keep true.\n */\nexport const accountlessInitGuidance =\n '`npx clerk@latest init` creates a Clerk application and writes keys to your .env file. No Clerk account or login required and the command is non-interactive.';\n\nconst fatalKeyGuidance = `To create a Clerk application with valid keys, in your terminal run:\n\nnpx clerk@latest init\n\n${accountlessInitGuidance}\n\nIf you have a Clerk application, run \\`npx clerk@latest env pull\\` to write the keys (\\`--instance prod\\` for production keys). Or copy them from https://dashboard.clerk.com/last-active?path=api-keys.`;\n\nexport function parsePublishableKey(\n key: string | undefined,\n options: ParsePublishableKeyOptions & { fatal: true },\n): PublishableKey;\nexport function parsePublishableKey(\n key: string | undefined,\n options?: ParsePublishableKeyOptions,\n): PublishableKey | null;\n/**\n * Parses and validates a publishable key, extracting the frontend API and instance type.\n *\n * @param key - The publishable key to parse.\n * @param options - Configuration options for parsing.\n * @param options.fatal\n * @param options.domain\n * @param options.proxyUrl\n * @param options.isSatellite\n * @returns Parsed publishable key object with instanceType and frontendApi, or null if invalid.\n *\n * @throws {Error} When options.fatal is true and key is missing or invalid.\n */\nexport function parsePublishableKey(\n key: string | undefined,\n options: { fatal?: boolean; domain?: string; proxyUrl?: string; isSatellite?: boolean } = {},\n): PublishableKey | null {\n key = key || '';\n\n if (!key || !isPublishableKey(key)) {\n if (options.fatal && !key) {\n throw new Error(`Publishable key is missing. ${fatalKeyGuidance}`);\n }\n if (options.fatal && !isPublishableKey(key)) {\n throw new Error(`Publishable key not valid (expected format: pk_test_... or pk_live_...). ${fatalKeyGuidance}`);\n }\n return null;\n }\n\n const instanceType = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) ? 'production' : 'development';\n\n let decodedFrontendApi: string;\n try {\n decodedFrontendApi = isomorphicAtob(key.split('_')[2]);\n } catch {\n if (options.fatal) {\n throw new Error(`Publishable key not valid: Failed to decode key. ${fatalKeyGuidance}`);\n }\n return null;\n }\n\n if (!isValidDecodedPublishableKey(decodedFrontendApi)) {\n if (options.fatal) {\n throw new Error(`Publishable key not valid: Decoded key has invalid format. ${fatalKeyGuidance}`);\n }\n return null;\n }\n\n let frontendApi = decodedFrontendApi.slice(0, -1);\n\n if (options.proxyUrl) {\n frontendApi = options.proxyUrl;\n } else if (instanceType !== 'development' && options.domain && options.isSatellite) {\n frontendApi = `clerk.${options.domain}`;\n }\n\n return {\n instanceType,\n frontendApi,\n };\n}\n\n/**\n * Checks if the provided key is a valid publishable key.\n *\n * @param key - The key to be checked. Defaults to an empty string if not provided.\n * @returns `true` if 'key' is a valid publishable key, `false` otherwise.\n */\nexport function isPublishableKey(key: string = '') {\n try {\n const hasValidPrefix = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) || key.startsWith(PUBLISHABLE_KEY_TEST_PREFIX);\n\n if (!hasValidPrefix) {\n return false;\n }\n\n const parts = key.split('_');\n if (parts.length !== 3) {\n return false;\n }\n\n const encodedPart = parts[2];\n if (!encodedPart) {\n return false;\n }\n\n const decoded = isomorphicAtob(encodedPart);\n return isValidDecodedPublishableKey(decoded);\n } catch {\n return false;\n }\n}\n\n/**\n * Creates a memoized cache for checking if URLs are development or staging environments.\n * Uses a Map to cache results for better performance on repeated checks.\n *\n * @returns An object with an isDevOrStagingUrl method that checks if a URL is dev/staging.\n */\nexport function createDevOrStagingUrlCache() {\n const devOrStagingUrlCache = new Map<string, boolean>();\n\n return {\n /**\n * Checks if a URL is a development or staging environment.\n *\n * @param url - The URL to check (string or URL object).\n * @returns `true` if the URL is a development or staging environment, `false` otherwise.\n */\n isDevOrStagingUrl: (url: string | URL): boolean => {\n if (!url) {\n return false;\n }\n\n const hostname = typeof url === 'string' ? url : url.hostname;\n let res = devOrStagingUrlCache.get(hostname);\n if (res === undefined) {\n res = DEV_OR_STAGING_SUFFIXES.some(s => hostname.endsWith(s));\n devOrStagingUrlCache.set(hostname, res);\n }\n return res;\n },\n };\n}\n\n/**\n * Checks if a publishable key is for a development environment.\n * Supports both legacy format (test_) and new format (pk_test_).\n *\n * @param apiKey - The API key to check.\n * @returns `true` if the key is for development, `false` otherwise.\n */\nexport function isDevelopmentFromPublishableKey(apiKey: string): boolean {\n return apiKey.startsWith('test_') || apiKey.startsWith('pk_test_');\n}\n\n/**\n * Checks if a publishable key is for a production environment.\n * Supports both legacy format (live_) and new format (pk_live_).\n *\n * @param apiKey - The API key to check.\n * @returns `true` if the key is for production, `false` otherwise.\n */\nexport function isProductionFromPublishableKey(apiKey: string): boolean {\n return apiKey.startsWith('live_') || apiKey.startsWith('pk_live_');\n}\n\n/**\n * Checks if a secret key is for a development environment.\n * Supports both legacy format (test_) and new format (sk_test_).\n *\n * @param apiKey - The secret key to check.\n * @returns `true` if the key is for development, `false` otherwise.\n */\nexport function isDevelopmentFromSecretKey(apiKey: string): boolean {\n return apiKey.startsWith('test_') || apiKey.startsWith('sk_test_');\n}\n\n/**\n * Checks if a secret key is for a production environment.\n * Supports both legacy format (live_) and new format (sk_live_).\n *\n * @param apiKey - The secret key to check.\n * @returns `true` if the key is for production, `false` otherwise.\n */\nexport function isProductionFromSecretKey(apiKey: string): boolean {\n return apiKey.startsWith('live_') || apiKey.startsWith('sk_live_');\n}\n\n/**\n * Generates a unique cookie suffix based on the publishable key using SHA-1 hashing.\n * The suffix is base64-encoded and URL-safe (+ and / characters are replaced).\n *\n * @param publishableKey - The publishable key to generate suffix from.\n * @param subtle - The SubtleCrypto interface to use for hashing (defaults to globalThis.crypto.subtle).\n * @returns A promise that resolves to an 8-character URL-safe base64 string.\n */\nexport async function getCookieSuffix(\n publishableKey: string,\n subtle: SubtleCrypto = globalThis.crypto.subtle,\n): Promise<string> {\n const data = new TextEncoder().encode(publishableKey);\n const digest = await subtle.digest('sha-1', data);\n const stringDigest = String.fromCharCode(...new Uint8Array(digest));\n // Base 64 Encoding with URL and Filename Safe Alphabet: https://datatracker.ietf.org/doc/html/rfc4648#section-5\n return isomorphicBtoa(stringDigest).replace(/\\+/gi, '-').replace(/\\//gi, '_').substring(0, 8);\n}\n\n/**\n * Creates a suffixed cookie name by appending the cookie suffix to the base name.\n * Used to create unique cookie names based on the publishable key.\n *\n * @param cookieName - The base cookie name.\n * @param cookieSuffix - The suffix to append (typically generated by getCookieSuffix).\n * @returns The suffixed cookie name in format: `${cookieName}_${cookieSuffix}`.\n */\nexport const getSuffixedCookieName = (cookieName: string, cookieSuffix: string): string => {\n return `${cookieName}_${cookieSuffix}`;\n};\n"],"mappings":";;;;;;;AAoBA,MAAM,8BAA8B;;AAGpC,MAAM,8BAA8B;;;;;AAMpC,MAAM,qCAAqC;;;;;;;AAQ3C,SAAgB,oBAAoB,aAA6B;CAK/D,OAAO,GAHL,mCAAmC,KAAK,WAAW,KAClD,YAAY,WAAW,QAAQ,KAAKA,+CAA6B,MAAK,MAAK,YAAY,SAAS,CAAC,CAAC,IACxE,8BAA8B,8BACrCC,sCAAe,GAAG,YAAY,EAAE,CAAC,CAAC,QAAQ,OAAO,EAAE;AAC3E;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,uBAAuB,MAAc,aAA8B;CACjF,IAAI,eAAe,gCAAgC,WAAW,GAC5D,OAAO;CAET,MAAM,WAAW,KAAK,YAAY,CAAC,CAAC,QAAQ,SAAS,EAAE;CACvD,IAAI,CAAC,UACH,MAAM,IAAI,MAAM,yBAAyB;CAE3C,OAAO,oBAAoB,SAAS,UAAU;AAChD;;;;;;;;AASA,SAAS,6BAA6B,SAA0B;CAC9D,IAAI,CAAC,QAAQ,SAAS,GAAG,GACvB,OAAO;CAGT,MAAM,kBAAkB,QAAQ,MAAM,GAAG,EAAE;CAC3C,IAAI,gBAAgB,SAAS,GAAG,GAC9B,OAAO;CAGT,OAAO,gBAAgB,SAAS,GAAG;AACrC;;;;;AAMA,MAAa,0BACX;AAEF,MAAM,mBAAmB;;;;EAIvB,wBAAwB;;;;;;;;;;;;;;;;AAyB1B,SAAgB,oBACd,KACA,UAA0F,CAAC,GACpE;CACvB,MAAM,OAAO;CAEb,IAAI,CAAC,OAAO,CAAC,iBAAiB,GAAG,GAAG;EAClC,IAAI,QAAQ,SAAS,CAAC,KACpB,MAAM,IAAI,MAAM,+BAA+B,kB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MC,0CAAwB,MAAK,MAAK,SAAS,SAAS,CAAC,CAAC;GAC5D,qBAAqB,IAAI,UAAU,GAAG;EACxC;EACA,OAAO;CACT,EACF;AACF;;;;;;;;AASA,SAAgB,gCAAgC,QAAyB;CACvE,OAAO,OAAO,WAAW,OAAO,KAAK,OAAO,WAAW,UAAU;AACnE;;;;;;;;AASA,SAAgB,+BAA+B,QAAyB;CACtE,OAAO,OAAO,WAAW,OAAO,KAAK,OAAO,WAAW,UAAU;AACnE;;;;;;;;AASA,SAAgB,2BAA2B,QAAyB;CAClE,OAAO,OAAO,WAAW,OAAO,KAAK,OAAO,WAAW,UAAU;AACnE;;;;;;;;AASA,SAAgB,0BAA0B,QAAyB;CACjE,OAAO,OAAO,WAAW,OAAO,KAAK,OAAO,WAAW,UAAU;AACnE;;;;;;;;;AAUA,eAAsB,gBACpB,gBACA,SAAuB,WAAW,OAAO,QACxB;CACjB,MAAM,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,cAAc;CACpD,MAAM,SAAS,MAAM,OAAO,OAAO,SAAS,IAAI;CAGhD,OAAOF,sCAFc,OAAO,aAAa,GAAG,IAAI,WAAW,MAAM,CAEhC,CAAC,CAAC,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAAC,UAAU,GAAG,CAAC;AAC9F;;;;;;;;;AAUA,MAAa,yBAAyB,YAAoB,iBAAiC;CACzF,OAAO,GAAG,WAAW,GAAG;AAC1B"}
|
|
1
|
+
{"version":3,"file":"keys.js","names":["LEGACY_DEV_INSTANCE_SUFFIXES","isomorphicBtoa","isomorphicAtob","DEV_OR_STAGING_SUFFIXES"],"sources":["../src/keys.ts"],"sourcesContent":["import { DEV_OR_STAGING_SUFFIXES, LEGACY_DEV_INSTANCE_SUFFIXES } from './constants';\nimport { isomorphicAtob } from './isomorphicAtob';\nimport { isomorphicBtoa } from './isomorphicBtoa';\nimport type { PublishableKey } from './types';\n\n/**\n * Configuration options for parsing publishable keys.\n */\ntype ParsePublishableKeyOptions = {\n /** Whether to throw an error if parsing fails */\n fatal?: boolean;\n /** Custom domain to use for satellite instances */\n domain?: string;\n /** Proxy URL to use instead of the decoded frontend API */\n proxyUrl?: string;\n /** Whether this is a satellite instance */\n isSatellite?: boolean;\n};\n\n/** Prefix used for production publishable keys */\nconst PUBLISHABLE_KEY_LIVE_PREFIX = 'pk_live_';\n\n/** Prefix used for development publishable keys */\nconst PUBLISHABLE_KEY_TEST_PREFIX = 'pk_test_';\n\n/**\n * Regular expression that matches development frontend API keys.\n * Matches patterns like: foo-bar-13.clerk.accounts.dev.\n */\nconst PUBLISHABLE_FRONTEND_API_DEV_REGEX = /^(([a-z]+)-){2}([0-9]{1,2})\\.clerk\\.accounts([a-z.]*)(dev|com)$/i;\n\n/**\n * Converts a frontend API URL into an unpadded base64-encoded publishable key.\n *\n * @param frontendApi - The frontend API URL (e.g., 'clerk.example.com').\n * @returns An unpadded base64-encoded publishable key with appropriate prefix (pk_live_ or pk_test_).\n */\nexport function buildPublishableKey(frontendApi: string): string {\n const isDevKey =\n PUBLISHABLE_FRONTEND_API_DEV_REGEX.test(frontendApi) ||\n (frontendApi.startsWith('clerk.') && LEGACY_DEV_INSTANCE_SUFFIXES.some(s => frontendApi.endsWith(s)));\n const keyPrefix = isDevKey ? PUBLISHABLE_KEY_TEST_PREFIX : PUBLISHABLE_KEY_LIVE_PREFIX;\n return `${keyPrefix}${isomorphicBtoa(`${frontendApi}$`).replace(/=+$/, '')}`;\n}\n\n/**\n * Derives a publishable key from the current hostname. Intended for multi-domain\n * setups (e.g. custom domains on top of a default domain) where the correct key\n * must be resolved per request.\n *\n * Pass the configured publishable key as `fallbackKey` so that development\n * instances (pk_test_) are returned as-is instead of being incorrectly derived\n * from the host (e.g. localhost).\n *\n * @example\n * // React (use window.location.hostname, not window.location.host, to avoid including the port)\n * <ClerkProvider publishableKey={publishableKeyFromHost(window.location.hostname, import.meta.env.VITE_CLERK_PUBLISHABLE_KEY)}>\n *\n * @example\n * // Express (inside clerkMiddleware callback)\n * // Validate req.hostname against a known allowlist before passing it in.\n * // When `trust proxy` is enabled, req.hostname reads from X-Forwarded-Host\n * // and can be spoofed if your proxy is not properly configured.\n * const ALLOWED_HOSTS = ['domain-a.com', 'domain-b.com'];\n * clerkMiddleware((req) => {\n * if (!ALLOWED_HOSTS.includes(req.hostname)) throw new Error('Unknown host');\n * return { publishableKey: publishableKeyFromHost(req.hostname, process.env.CLERK_PUBLISHABLE_KEY) };\n * })\n */\nexport function publishableKeyFromHost(host: string, fallbackKey?: string): string {\n if (fallbackKey && isDevelopmentFromPublishableKey(fallbackKey)) {\n return fallbackKey;\n }\n const hostname = host.toLowerCase().replace(/:\\d+$/, '');\n if (!hostname) {\n throw new Error('Host must not be empty.');\n }\n return buildPublishableKey(`clerk.${hostname}`);\n}\n\n/**\n * Validates that a decoded publishable key has the correct format.\n * The decoded value should be a frontend API followed by exactly one '$' at the end.\n *\n * @param decoded - The decoded publishable key string to validate.\n * @returns `true` if the decoded key has valid format, `false` otherwise.\n */\nfunction isValidDecodedPublishableKey(decoded: string): boolean {\n if (!decoded.endsWith('$')) {\n return false;\n }\n\n const withoutTrailing = decoded.slice(0, -1);\n if (withoutTrailing.includes('$')) {\n return false;\n }\n\n return withoutTrailing.includes('.');\n}\n\nconst fatalKeyGuidance = `To create a Clerk application with valid keys, in your terminal run:\n\nnpx clerk@latest init\n\n\\`npx clerk@latest init\\` creates a Clerk application and writes keys to your .env file. No Clerk account or login required and the command is non-interactive.\n\nIf you have a Clerk application, run \\`npx clerk@latest env pull\\` to write the keys (\\`--instance prod\\` for production keys). Or copy them from https://dashboard.clerk.com/~/api-keys.`;\n\nexport function parsePublishableKey(\n key: string | undefined,\n options: ParsePublishableKeyOptions & { fatal: true },\n): PublishableKey;\nexport function parsePublishableKey(\n key: string | undefined,\n options?: ParsePublishableKeyOptions,\n): PublishableKey | null;\n/**\n * Parses and validates a publishable key, extracting the frontend API and instance type.\n *\n * @param key - The publishable key to parse.\n * @param options - Configuration options for parsing.\n * @param options.fatal\n * @param options.domain\n * @param options.proxyUrl\n * @param options.isSatellite\n * @returns Parsed publishable key object with instanceType and frontendApi, or null if invalid.\n *\n * @throws {Error} When options.fatal is true and key is missing or invalid.\n */\nexport function parsePublishableKey(\n key: string | undefined,\n options: { fatal?: boolean; domain?: string; proxyUrl?: string; isSatellite?: boolean } = {},\n): PublishableKey | null {\n key = key || '';\n\n if (!key || !isPublishableKey(key)) {\n if (options.fatal && !key) {\n throw new Error(`Publishable key is missing. ${fatalKeyGuidance}`);\n }\n if (options.fatal && !isPublishableKey(key)) {\n throw new Error(`Publishable key not valid (expected format: pk_test_... or pk_live_...). ${fatalKeyGuidance}`);\n }\n return null;\n }\n\n const instanceType = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) ? 'production' : 'development';\n\n let decodedFrontendApi: string;\n try {\n decodedFrontendApi = isomorphicAtob(key.split('_')[2]);\n } catch {\n if (options.fatal) {\n throw new Error(`Publishable key not valid: Failed to decode key. ${fatalKeyGuidance}`);\n }\n return null;\n }\n\n if (!isValidDecodedPublishableKey(decodedFrontendApi)) {\n if (options.fatal) {\n throw new Error(`Publishable key not valid: Decoded key has invalid format. ${fatalKeyGuidance}`);\n }\n return null;\n }\n\n let frontendApi = decodedFrontendApi.slice(0, -1);\n\n if (options.proxyUrl) {\n frontendApi = options.proxyUrl;\n } else if (instanceType !== 'development' && options.domain && options.isSatellite) {\n frontendApi = `clerk.${options.domain}`;\n }\n\n return {\n instanceType,\n frontendApi,\n };\n}\n\n/**\n * Checks if the provided key is a valid publishable key.\n *\n * @param key - The key to be checked. Defaults to an empty string if not provided.\n * @returns `true` if 'key' is a valid publishable key, `false` otherwise.\n */\nexport function isPublishableKey(key: string = '') {\n try {\n const hasValidPrefix = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) || key.startsWith(PUBLISHABLE_KEY_TEST_PREFIX);\n\n if (!hasValidPrefix) {\n return false;\n }\n\n const parts = key.split('_');\n if (parts.length !== 3) {\n return false;\n }\n\n const encodedPart = parts[2];\n if (!encodedPart) {\n return false;\n }\n\n const decoded = isomorphicAtob(encodedPart);\n return isValidDecodedPublishableKey(decoded);\n } catch {\n return false;\n }\n}\n\n/**\n * Creates a memoized cache for checking if URLs are development or staging environments.\n * Uses a Map to cache results for better performance on repeated checks.\n *\n * @returns An object with an isDevOrStagingUrl method that checks if a URL is dev/staging.\n */\nexport function createDevOrStagingUrlCache() {\n const devOrStagingUrlCache = new Map<string, boolean>();\n\n return {\n /**\n * Checks if a URL is a development or staging environment.\n *\n * @param url - The URL to check (string or URL object).\n * @returns `true` if the URL is a development or staging environment, `false` otherwise.\n */\n isDevOrStagingUrl: (url: string | URL): boolean => {\n if (!url) {\n return false;\n }\n\n const hostname = typeof url === 'string' ? url : url.hostname;\n let res = devOrStagingUrlCache.get(hostname);\n if (res === undefined) {\n res = DEV_OR_STAGING_SUFFIXES.some(s => hostname.endsWith(s));\n devOrStagingUrlCache.set(hostname, res);\n }\n return res;\n },\n };\n}\n\n/**\n * Checks if a publishable key is for a development environment.\n * Supports both legacy format (test_) and new format (pk_test_).\n *\n * @param apiKey - The API key to check.\n * @returns `true` if the key is for development, `false` otherwise.\n */\nexport function isDevelopmentFromPublishableKey(apiKey: string): boolean {\n return apiKey.startsWith('test_') || apiKey.startsWith('pk_test_');\n}\n\n/**\n * Checks if a publishable key is for a production environment.\n * Supports both legacy format (live_) and new format (pk_live_).\n *\n * @param apiKey - The API key to check.\n * @returns `true` if the key is for production, `false` otherwise.\n */\nexport function isProductionFromPublishableKey(apiKey: string): boolean {\n return apiKey.startsWith('live_') || apiKey.startsWith('pk_live_');\n}\n\n/**\n * Checks if a secret key is for a development environment.\n * Supports both legacy format (test_) and new format (sk_test_).\n *\n * @param apiKey - The secret key to check.\n * @returns `true` if the key is for development, `false` otherwise.\n */\nexport function isDevelopmentFromSecretKey(apiKey: string): boolean {\n return apiKey.startsWith('test_') || apiKey.startsWith('sk_test_');\n}\n\n/**\n * Checks if a secret key is for a production environment.\n * Supports both legacy format (live_) and new format (sk_live_).\n *\n * @param apiKey - The secret key to check.\n * @returns `true` if the key is for production, `false` otherwise.\n */\nexport function isProductionFromSecretKey(apiKey: string): boolean {\n return apiKey.startsWith('live_') || apiKey.startsWith('sk_live_');\n}\n\n/**\n * Generates a unique cookie suffix based on the publishable key using SHA-1 hashing.\n * The suffix is base64-encoded and URL-safe (+ and / characters are replaced).\n *\n * @param publishableKey - The publishable key to generate suffix from.\n * @param subtle - The SubtleCrypto interface to use for hashing (defaults to globalThis.crypto.subtle).\n * @returns A promise that resolves to an 8-character URL-safe base64 string.\n */\nexport async function getCookieSuffix(\n publishableKey: string,\n subtle: SubtleCrypto = globalThis.crypto.subtle,\n): Promise<string> {\n const data = new TextEncoder().encode(publishableKey);\n const digest = await subtle.digest('sha-1', data);\n const stringDigest = String.fromCharCode(...new Uint8Array(digest));\n // Base 64 Encoding with URL and Filename Safe Alphabet: https://datatracker.ietf.org/doc/html/rfc4648#section-5\n return isomorphicBtoa(stringDigest).replace(/\\+/gi, '-').replace(/\\//gi, '_').substring(0, 8);\n}\n\n/**\n * Creates a suffixed cookie name by appending the cookie suffix to the base name.\n * Used to create unique cookie names based on the publishable key.\n *\n * @param cookieName - The base cookie name.\n * @param cookieSuffix - The suffix to append (typically generated by getCookieSuffix).\n * @returns The suffixed cookie name in format: `${cookieName}_${cookieSuffix}`.\n */\nexport const getSuffixedCookieName = (cookieName: string, cookieSuffix: string): string => {\n return `${cookieName}_${cookieSuffix}`;\n};\n"],"mappings":";;;;;;;AAoBA,MAAM,8BAA8B;;AAGpC,MAAM,8BAA8B;;;;;AAMpC,MAAM,qCAAqC;;;;;;;AAQ3C,SAAgB,oBAAoB,aAA6B;CAK/D,OAAO,GAHL,mCAAmC,KAAK,WAAW,KAClD,YAAY,WAAW,QAAQ,KAAKA,+CAA6B,MAAK,MAAK,YAAY,SAAS,CAAC,CAAC,IACxE,8BAA8B,8BACrCC,sCAAe,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AAO,WAAW,UAAU;AACnE;;;;;;;;;AAUA,eAAsB,gBACpB,gBACA,SAAuB,WAAW,OAAO,QACxB;CACjB,MAAM,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,cAAc;CACpD,MAAM,SAAS,MAAM,OAAO,OAAO,SAAS,IAAI;CAGhD,OAAOF,sCAFc,OAAO,aAAa,GAAG,IAAI,WAAW,MAAM,CAEhC,CAAC,CAAC,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAAC,UAAU,GAAG,CAAC;AAC9F;;;;;;;;;AAUA,MAAa,yBAAyB,YAAoB,iBAAiC;CACzF,OAAO,GAAG,WAAW,GAAG;AAC1B"}
|
package/dist/keys.mjs
CHANGED
|
@@ -64,18 +64,13 @@ function isValidDecodedPublishableKey(decoded) {
|
|
|
64
64
|
if (withoutTrailing.includes("$")) return false;
|
|
65
65
|
return withoutTrailing.includes(".");
|
|
66
66
|
}
|
|
67
|
-
/**
|
|
68
|
-
* The one sentence that explains how to get working Clerk keys without a Clerk account.
|
|
69
|
-
* Shared by every message that mentions `clerk init` so there is a single sentence to keep true.
|
|
70
|
-
*/
|
|
71
|
-
const accountlessInitGuidance = "`npx clerk@latest init` creates a Clerk application and writes keys to your .env file. No Clerk account or login required and the command is non-interactive.";
|
|
72
67
|
const fatalKeyGuidance = `To create a Clerk application with valid keys, in your terminal run:
|
|
73
68
|
|
|
74
69
|
npx clerk@latest init
|
|
75
70
|
|
|
76
|
-
|
|
71
|
+
\`npx clerk@latest init\` creates a Clerk application and writes keys to your .env file. No Clerk account or login required and the command is non-interactive.
|
|
77
72
|
|
|
78
|
-
If you have a Clerk application, run \`npx clerk@latest env pull\` to write the keys (\`--instance prod\` for production keys). Or copy them from https://dashboard.clerk.com
|
|
73
|
+
If you have a Clerk application, run \`npx clerk@latest env pull\` to write the keys (\`--instance prod\` for production keys). Or copy them from https://dashboard.clerk.com/~/api-keys.`;
|
|
79
74
|
/**
|
|
80
75
|
* Parses and validates a publishable key, extracting the frontend API and instance type.
|
|
81
76
|
*
|
|
@@ -226,5 +221,5 @@ const getSuffixedCookieName = (cookieName, cookieSuffix) => {
|
|
|
226
221
|
};
|
|
227
222
|
|
|
228
223
|
//#endregion
|
|
229
|
-
export {
|
|
224
|
+
export { buildPublishableKey, createDevOrStagingUrlCache, getCookieSuffix, getSuffixedCookieName, isDevelopmentFromPublishableKey, isDevelopmentFromSecretKey, isProductionFromPublishableKey, isProductionFromSecretKey, isPublishableKey, parsePublishableKey, publishableKeyFromHost };
|
|
230
225
|
//# sourceMappingURL=keys.mjs.map
|
package/dist/keys.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keys.mjs","names":[],"sources":["../src/keys.ts"],"sourcesContent":["import { DEV_OR_STAGING_SUFFIXES, LEGACY_DEV_INSTANCE_SUFFIXES } from './constants';\nimport { isomorphicAtob } from './isomorphicAtob';\nimport { isomorphicBtoa } from './isomorphicBtoa';\nimport type { PublishableKey } from './types';\n\n/**\n * Configuration options for parsing publishable keys.\n */\ntype ParsePublishableKeyOptions = {\n /** Whether to throw an error if parsing fails */\n fatal?: boolean;\n /** Custom domain to use for satellite instances */\n domain?: string;\n /** Proxy URL to use instead of the decoded frontend API */\n proxyUrl?: string;\n /** Whether this is a satellite instance */\n isSatellite?: boolean;\n};\n\n/** Prefix used for production publishable keys */\nconst PUBLISHABLE_KEY_LIVE_PREFIX = 'pk_live_';\n\n/** Prefix used for development publishable keys */\nconst PUBLISHABLE_KEY_TEST_PREFIX = 'pk_test_';\n\n/**\n * Regular expression that matches development frontend API keys.\n * Matches patterns like: foo-bar-13.clerk.accounts.dev.\n */\nconst PUBLISHABLE_FRONTEND_API_DEV_REGEX = /^(([a-z]+)-){2}([0-9]{1,2})\\.clerk\\.accounts([a-z.]*)(dev|com)$/i;\n\n/**\n * Converts a frontend API URL into an unpadded base64-encoded publishable key.\n *\n * @param frontendApi - The frontend API URL (e.g., 'clerk.example.com').\n * @returns An unpadded base64-encoded publishable key with appropriate prefix (pk_live_ or pk_test_).\n */\nexport function buildPublishableKey(frontendApi: string): string {\n const isDevKey =\n PUBLISHABLE_FRONTEND_API_DEV_REGEX.test(frontendApi) ||\n (frontendApi.startsWith('clerk.') && LEGACY_DEV_INSTANCE_SUFFIXES.some(s => frontendApi.endsWith(s)));\n const keyPrefix = isDevKey ? PUBLISHABLE_KEY_TEST_PREFIX : PUBLISHABLE_KEY_LIVE_PREFIX;\n return `${keyPrefix}${isomorphicBtoa(`${frontendApi}$`).replace(/=+$/, '')}`;\n}\n\n/**\n * Derives a publishable key from the current hostname. Intended for multi-domain\n * setups (e.g. custom domains on top of a default domain) where the correct key\n * must be resolved per request.\n *\n * Pass the configured publishable key as `fallbackKey` so that development\n * instances (pk_test_) are returned as-is instead of being incorrectly derived\n * from the host (e.g. localhost).\n *\n * @example\n * // React (use window.location.hostname, not window.location.host, to avoid including the port)\n * <ClerkProvider publishableKey={publishableKeyFromHost(window.location.hostname, import.meta.env.VITE_CLERK_PUBLISHABLE_KEY)}>\n *\n * @example\n * // Express (inside clerkMiddleware callback)\n * // Validate req.hostname against a known allowlist before passing it in.\n * // When `trust proxy` is enabled, req.hostname reads from X-Forwarded-Host\n * // and can be spoofed if your proxy is not properly configured.\n * const ALLOWED_HOSTS = ['domain-a.com', 'domain-b.com'];\n * clerkMiddleware((req) => {\n * if (!ALLOWED_HOSTS.includes(req.hostname)) throw new Error('Unknown host');\n * return { publishableKey: publishableKeyFromHost(req.hostname, process.env.CLERK_PUBLISHABLE_KEY) };\n * })\n */\nexport function publishableKeyFromHost(host: string, fallbackKey?: string): string {\n if (fallbackKey && isDevelopmentFromPublishableKey(fallbackKey)) {\n return fallbackKey;\n }\n const hostname = host.toLowerCase().replace(/:\\d+$/, '');\n if (!hostname) {\n throw new Error('Host must not be empty.');\n }\n return buildPublishableKey(`clerk.${hostname}`);\n}\n\n/**\n * Validates that a decoded publishable key has the correct format.\n * The decoded value should be a frontend API followed by exactly one '$' at the end.\n *\n * @param decoded - The decoded publishable key string to validate.\n * @returns `true` if the decoded key has valid format, `false` otherwise.\n */\nfunction isValidDecodedPublishableKey(decoded: string): boolean {\n if (!decoded.endsWith('$')) {\n return false;\n }\n\n const withoutTrailing = decoded.slice(0, -1);\n if (withoutTrailing.includes('$')) {\n return false;\n }\n\n return withoutTrailing.includes('.');\n}\n\n/**\n * The one sentence that explains how to get working Clerk keys without a Clerk account.\n * Shared by every message that mentions `clerk init` so there is a single sentence to keep true.\n */\nexport const accountlessInitGuidance =\n '`npx clerk@latest init` creates a Clerk application and writes keys to your .env file. No Clerk account or login required and the command is non-interactive.';\n\nconst fatalKeyGuidance = `To create a Clerk application with valid keys, in your terminal run:\n\nnpx clerk@latest init\n\n${accountlessInitGuidance}\n\nIf you have a Clerk application, run \\`npx clerk@latest env pull\\` to write the keys (\\`--instance prod\\` for production keys). Or copy them from https://dashboard.clerk.com/last-active?path=api-keys.`;\n\nexport function parsePublishableKey(\n key: string | undefined,\n options: ParsePublishableKeyOptions & { fatal: true },\n): PublishableKey;\nexport function parsePublishableKey(\n key: string | undefined,\n options?: ParsePublishableKeyOptions,\n): PublishableKey | null;\n/**\n * Parses and validates a publishable key, extracting the frontend API and instance type.\n *\n * @param key - The publishable key to parse.\n * @param options - Configuration options for parsing.\n * @param options.fatal\n * @param options.domain\n * @param options.proxyUrl\n * @param options.isSatellite\n * @returns Parsed publishable key object with instanceType and frontendApi, or null if invalid.\n *\n * @throws {Error} When options.fatal is true and key is missing or invalid.\n */\nexport function parsePublishableKey(\n key: string | undefined,\n options: { fatal?: boolean; domain?: string; proxyUrl?: string; isSatellite?: boolean } = {},\n): PublishableKey | null {\n key = key || '';\n\n if (!key || !isPublishableKey(key)) {\n if (options.fatal && !key) {\n throw new Error(`Publishable key is missing. ${fatalKeyGuidance}`);\n }\n if (options.fatal && !isPublishableKey(key)) {\n throw new Error(`Publishable key not valid (expected format: pk_test_... or pk_live_...). ${fatalKeyGuidance}`);\n }\n return null;\n }\n\n const instanceType = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) ? 'production' : 'development';\n\n let decodedFrontendApi: string;\n try {\n decodedFrontendApi = isomorphicAtob(key.split('_')[2]);\n } catch {\n if (options.fatal) {\n throw new Error(`Publishable key not valid: Failed to decode key. ${fatalKeyGuidance}`);\n }\n return null;\n }\n\n if (!isValidDecodedPublishableKey(decodedFrontendApi)) {\n if (options.fatal) {\n throw new Error(`Publishable key not valid: Decoded key has invalid format. ${fatalKeyGuidance}`);\n }\n return null;\n }\n\n let frontendApi = decodedFrontendApi.slice(0, -1);\n\n if (options.proxyUrl) {\n frontendApi = options.proxyUrl;\n } else if (instanceType !== 'development' && options.domain && options.isSatellite) {\n frontendApi = `clerk.${options.domain}`;\n }\n\n return {\n instanceType,\n frontendApi,\n };\n}\n\n/**\n * Checks if the provided key is a valid publishable key.\n *\n * @param key - The key to be checked. Defaults to an empty string if not provided.\n * @returns `true` if 'key' is a valid publishable key, `false` otherwise.\n */\nexport function isPublishableKey(key: string = '') {\n try {\n const hasValidPrefix = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) || key.startsWith(PUBLISHABLE_KEY_TEST_PREFIX);\n\n if (!hasValidPrefix) {\n return false;\n }\n\n const parts = key.split('_');\n if (parts.length !== 3) {\n return false;\n }\n\n const encodedPart = parts[2];\n if (!encodedPart) {\n return false;\n }\n\n const decoded = isomorphicAtob(encodedPart);\n return isValidDecodedPublishableKey(decoded);\n } catch {\n return false;\n }\n}\n\n/**\n * Creates a memoized cache for checking if URLs are development or staging environments.\n * Uses a Map to cache results for better performance on repeated checks.\n *\n * @returns An object with an isDevOrStagingUrl method that checks if a URL is dev/staging.\n */\nexport function createDevOrStagingUrlCache() {\n const devOrStagingUrlCache = new Map<string, boolean>();\n\n return {\n /**\n * Checks if a URL is a development or staging environment.\n *\n * @param url - The URL to check (string or URL object).\n * @returns `true` if the URL is a development or staging environment, `false` otherwise.\n */\n isDevOrStagingUrl: (url: string | URL): boolean => {\n if (!url) {\n return false;\n }\n\n const hostname = typeof url === 'string' ? url : url.hostname;\n let res = devOrStagingUrlCache.get(hostname);\n if (res === undefined) {\n res = DEV_OR_STAGING_SUFFIXES.some(s => hostname.endsWith(s));\n devOrStagingUrlCache.set(hostname, res);\n }\n return res;\n },\n };\n}\n\n/**\n * Checks if a publishable key is for a development environment.\n * Supports both legacy format (test_) and new format (pk_test_).\n *\n * @param apiKey - The API key to check.\n * @returns `true` if the key is for development, `false` otherwise.\n */\nexport function isDevelopmentFromPublishableKey(apiKey: string): boolean {\n return apiKey.startsWith('test_') || apiKey.startsWith('pk_test_');\n}\n\n/**\n * Checks if a publishable key is for a production environment.\n * Supports both legacy format (live_) and new format (pk_live_).\n *\n * @param apiKey - The API key to check.\n * @returns `true` if the key is for production, `false` otherwise.\n */\nexport function isProductionFromPublishableKey(apiKey: string): boolean {\n return apiKey.startsWith('live_') || apiKey.startsWith('pk_live_');\n}\n\n/**\n * Checks if a secret key is for a development environment.\n * Supports both legacy format (test_) and new format (sk_test_).\n *\n * @param apiKey - The secret key to check.\n * @returns `true` if the key is for development, `false` otherwise.\n */\nexport function isDevelopmentFromSecretKey(apiKey: string): boolean {\n return apiKey.startsWith('test_') || apiKey.startsWith('sk_test_');\n}\n\n/**\n * Checks if a secret key is for a production environment.\n * Supports both legacy format (live_) and new format (sk_live_).\n *\n * @param apiKey - The secret key to check.\n * @returns `true` if the key is for production, `false` otherwise.\n */\nexport function isProductionFromSecretKey(apiKey: string): boolean {\n return apiKey.startsWith('live_') || apiKey.startsWith('sk_live_');\n}\n\n/**\n * Generates a unique cookie suffix based on the publishable key using SHA-1 hashing.\n * The suffix is base64-encoded and URL-safe (+ and / characters are replaced).\n *\n * @param publishableKey - The publishable key to generate suffix from.\n * @param subtle - The SubtleCrypto interface to use for hashing (defaults to globalThis.crypto.subtle).\n * @returns A promise that resolves to an 8-character URL-safe base64 string.\n */\nexport async function getCookieSuffix(\n publishableKey: string,\n subtle: SubtleCrypto = globalThis.crypto.subtle,\n): Promise<string> {\n const data = new TextEncoder().encode(publishableKey);\n const digest = await subtle.digest('sha-1', data);\n const stringDigest = String.fromCharCode(...new Uint8Array(digest));\n // Base 64 Encoding with URL and Filename Safe Alphabet: https://datatracker.ietf.org/doc/html/rfc4648#section-5\n return isomorphicBtoa(stringDigest).replace(/\\+/gi, '-').replace(/\\//gi, '_').substring(0, 8);\n}\n\n/**\n * Creates a suffixed cookie name by appending the cookie suffix to the base name.\n * Used to create unique cookie names based on the publishable key.\n *\n * @param cookieName - The base cookie name.\n * @param cookieSuffix - The suffix to append (typically generated by getCookieSuffix).\n * @returns The suffixed cookie name in format: `${cookieName}_${cookieSuffix}`.\n */\nexport const getSuffixedCookieName = (cookieName: string, cookieSuffix: string): string => {\n return `${cookieName}_${cookieSuffix}`;\n};\n"],"mappings":";;;;;;AAoBA,MAAM,8BAA8B;;AAGpC,MAAM,8BAA8B;;;;;AAMpC,MAAM,qCAAqC;;;;;;;AAQ3C,SAAgB,oBAAoB,aAA6B;CAK/D,OAAO,GAHL,mCAAmC,KAAK,WAAW,KAClD,YAAY,WAAW,QAAQ,KAAK,6BAA6B,MAAK,MAAK,YAAY,SAAS,CAAC,CAAC,IACxE,8BAA8B,8BACrC,eAAe,GAAG,YAAY,EAAE,CAAC,CAAC,QAAQ,OAAO,EAAE;AAC3E;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,uBAAuB,MAAc,aAA8B;CACjF,IAAI,eAAe,gCAAgC,WAAW,GAC5D,OAAO;CAET,MAAM,WAAW,KAAK,YAAY,CAAC,CAAC,QAAQ,SAAS,EAAE;CACvD,IAAI,CAAC,UACH,MAAM,IAAI,MAAM,yBAAyB;CAE3C,OAAO,oBAAoB,SAAS,UAAU;AAChD;;;;;;;;AASA,SAAS,6BAA6B,SAA0B;CAC9D,IAAI,CAAC,QAAQ,SAAS,GAAG,GACvB,OAAO;CAGT,MAAM,kBAAkB,QAAQ,MAAM,GAAG,EAAE;CAC3C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AAW,GAAG;AAC1B"}
|
|
1
|
+
{"version":3,"file":"keys.mjs","names":[],"sources":["../src/keys.ts"],"sourcesContent":["import { DEV_OR_STAGING_SUFFIXES, LEGACY_DEV_INSTANCE_SUFFIXES } from './constants';\nimport { isomorphicAtob } from './isomorphicAtob';\nimport { isomorphicBtoa } from './isomorphicBtoa';\nimport type { PublishableKey } from './types';\n\n/**\n * Configuration options for parsing publishable keys.\n */\ntype ParsePublishableKeyOptions = {\n /** Whether to throw an error if parsing fails */\n fatal?: boolean;\n /** Custom domain to use for satellite instances */\n domain?: string;\n /** Proxy URL to use instead of the decoded frontend API */\n proxyUrl?: string;\n /** Whether this is a satellite instance */\n isSatellite?: boolean;\n};\n\n/** Prefix used for production publishable keys */\nconst PUBLISHABLE_KEY_LIVE_PREFIX = 'pk_live_';\n\n/** Prefix used for development publishable keys */\nconst PUBLISHABLE_KEY_TEST_PREFIX = 'pk_test_';\n\n/**\n * Regular expression that matches development frontend API keys.\n * Matches patterns like: foo-bar-13.clerk.accounts.dev.\n */\nconst PUBLISHABLE_FRONTEND_API_DEV_REGEX = /^(([a-z]+)-){2}([0-9]{1,2})\\.clerk\\.accounts([a-z.]*)(dev|com)$/i;\n\n/**\n * Converts a frontend API URL into an unpadded base64-encoded publishable key.\n *\n * @param frontendApi - The frontend API URL (e.g., 'clerk.example.com').\n * @returns An unpadded base64-encoded publishable key with appropriate prefix (pk_live_ or pk_test_).\n */\nexport function buildPublishableKey(frontendApi: string): string {\n const isDevKey =\n PUBLISHABLE_FRONTEND_API_DEV_REGEX.test(frontendApi) ||\n (frontendApi.startsWith('clerk.') && LEGACY_DEV_INSTANCE_SUFFIXES.some(s => frontendApi.endsWith(s)));\n const keyPrefix = isDevKey ? PUBLISHABLE_KEY_TEST_PREFIX : PUBLISHABLE_KEY_LIVE_PREFIX;\n return `${keyPrefix}${isomorphicBtoa(`${frontendApi}$`).replace(/=+$/, '')}`;\n}\n\n/**\n * Derives a publishable key from the current hostname. Intended for multi-domain\n * setups (e.g. custom domains on top of a default domain) where the correct key\n * must be resolved per request.\n *\n * Pass the configured publishable key as `fallbackKey` so that development\n * instances (pk_test_) are returned as-is instead of being incorrectly derived\n * from the host (e.g. localhost).\n *\n * @example\n * // React (use window.location.hostname, not window.location.host, to avoid including the port)\n * <ClerkProvider publishableKey={publishableKeyFromHost(window.location.hostname, import.meta.env.VITE_CLERK_PUBLISHABLE_KEY)}>\n *\n * @example\n * // Express (inside clerkMiddleware callback)\n * // Validate req.hostname against a known allowlist before passing it in.\n * // When `trust proxy` is enabled, req.hostname reads from X-Forwarded-Host\n * // and can be spoofed if your proxy is not properly configured.\n * const ALLOWED_HOSTS = ['domain-a.com', 'domain-b.com'];\n * clerkMiddleware((req) => {\n * if (!ALLOWED_HOSTS.includes(req.hostname)) throw new Error('Unknown host');\n * return { publishableKey: publishableKeyFromHost(req.hostname, process.env.CLERK_PUBLISHABLE_KEY) };\n * })\n */\nexport function publishableKeyFromHost(host: string, fallbackKey?: string): string {\n if (fallbackKey && isDevelopmentFromPublishableKey(fallbackKey)) {\n return fallbackKey;\n }\n const hostname = host.toLowerCase().replace(/:\\d+$/, '');\n if (!hostname) {\n throw new Error('Host must not be empty.');\n }\n return buildPublishableKey(`clerk.${hostname}`);\n}\n\n/**\n * Validates that a decoded publishable key has the correct format.\n * The decoded value should be a frontend API followed by exactly one '$' at the end.\n *\n * @param decoded - The decoded publishable key string to validate.\n * @returns `true` if the decoded key has valid format, `false` otherwise.\n */\nfunction isValidDecodedPublishableKey(decoded: string): boolean {\n if (!decoded.endsWith('$')) {\n return false;\n }\n\n const withoutTrailing = decoded.slice(0, -1);\n if (withoutTrailing.includes('$')) {\n return false;\n }\n\n return withoutTrailing.includes('.');\n}\n\nconst fatalKeyGuidance = `To create a Clerk application with valid keys, in your terminal run:\n\nnpx clerk@latest init\n\n\\`npx clerk@latest init\\` creates a Clerk application and writes keys to your .env file. No Clerk account or login required and the command is non-interactive.\n\nIf you have a Clerk application, run \\`npx clerk@latest env pull\\` to write the keys (\\`--instance prod\\` for production keys). Or copy them from https://dashboard.clerk.com/~/api-keys.`;\n\nexport function parsePublishableKey(\n key: string | undefined,\n options: ParsePublishableKeyOptions & { fatal: true },\n): PublishableKey;\nexport function parsePublishableKey(\n key: string | undefined,\n options?: ParsePublishableKeyOptions,\n): PublishableKey | null;\n/**\n * Parses and validates a publishable key, extracting the frontend API and instance type.\n *\n * @param key - The publishable key to parse.\n * @param options - Configuration options for parsing.\n * @param options.fatal\n * @param options.domain\n * @param options.proxyUrl\n * @param options.isSatellite\n * @returns Parsed publishable key object with instanceType and frontendApi, or null if invalid.\n *\n * @throws {Error} When options.fatal is true and key is missing or invalid.\n */\nexport function parsePublishableKey(\n key: string | undefined,\n options: { fatal?: boolean; domain?: string; proxyUrl?: string; isSatellite?: boolean } = {},\n): PublishableKey | null {\n key = key || '';\n\n if (!key || !isPublishableKey(key)) {\n if (options.fatal && !key) {\n throw new Error(`Publishable key is missing. ${fatalKeyGuidance}`);\n }\n if (options.fatal && !isPublishableKey(key)) {\n throw new Error(`Publishable key not valid (expected format: pk_test_... or pk_live_...). ${fatalKeyGuidance}`);\n }\n return null;\n }\n\n const instanceType = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) ? 'production' : 'development';\n\n let decodedFrontendApi: string;\n try {\n decodedFrontendApi = isomorphicAtob(key.split('_')[2]);\n } catch {\n if (options.fatal) {\n throw new Error(`Publishable key not valid: Failed to decode key. ${fatalKeyGuidance}`);\n }\n return null;\n }\n\n if (!isValidDecodedPublishableKey(decodedFrontendApi)) {\n if (options.fatal) {\n throw new Error(`Publishable key not valid: Decoded key has invalid format. ${fatalKeyGuidance}`);\n }\n return null;\n }\n\n let frontendApi = decodedFrontendApi.slice(0, -1);\n\n if (options.proxyUrl) {\n frontendApi = options.proxyUrl;\n } else if (instanceType !== 'development' && options.domain && options.isSatellite) {\n frontendApi = `clerk.${options.domain}`;\n }\n\n return {\n instanceType,\n frontendApi,\n };\n}\n\n/**\n * Checks if the provided key is a valid publishable key.\n *\n * @param key - The key to be checked. Defaults to an empty string if not provided.\n * @returns `true` if 'key' is a valid publishable key, `false` otherwise.\n */\nexport function isPublishableKey(key: string = '') {\n try {\n const hasValidPrefix = key.startsWith(PUBLISHABLE_KEY_LIVE_PREFIX) || key.startsWith(PUBLISHABLE_KEY_TEST_PREFIX);\n\n if (!hasValidPrefix) {\n return false;\n }\n\n const parts = key.split('_');\n if (parts.length !== 3) {\n return false;\n }\n\n const encodedPart = parts[2];\n if (!encodedPart) {\n return false;\n }\n\n const decoded = isomorphicAtob(encodedPart);\n return isValidDecodedPublishableKey(decoded);\n } catch {\n return false;\n }\n}\n\n/**\n * Creates a memoized cache for checking if URLs are development or staging environments.\n * Uses a Map to cache results for better performance on repeated checks.\n *\n * @returns An object with an isDevOrStagingUrl method that checks if a URL is dev/staging.\n */\nexport function createDevOrStagingUrlCache() {\n const devOrStagingUrlCache = new Map<string, boolean>();\n\n return {\n /**\n * Checks if a URL is a development or staging environment.\n *\n * @param url - The URL to check (string or URL object).\n * @returns `true` if the URL is a development or staging environment, `false` otherwise.\n */\n isDevOrStagingUrl: (url: string | URL): boolean => {\n if (!url) {\n return false;\n }\n\n const hostname = typeof url === 'string' ? url : url.hostname;\n let res = devOrStagingUrlCache.get(hostname);\n if (res === undefined) {\n res = DEV_OR_STAGING_SUFFIXES.some(s => hostname.endsWith(s));\n devOrStagingUrlCache.set(hostname, res);\n }\n return res;\n },\n };\n}\n\n/**\n * Checks if a publishable key is for a development environment.\n * Supports both legacy format (test_) and new format (pk_test_).\n *\n * @param apiKey - The API key to check.\n * @returns `true` if the key is for development, `false` otherwise.\n */\nexport function isDevelopmentFromPublishableKey(apiKey: string): boolean {\n return apiKey.startsWith('test_') || apiKey.startsWith('pk_test_');\n}\n\n/**\n * Checks if a publishable key is for a production environment.\n * Supports both legacy format (live_) and new format (pk_live_).\n *\n * @param apiKey - The API key to check.\n * @returns `true` if the key is for production, `false` otherwise.\n */\nexport function isProductionFromPublishableKey(apiKey: string): boolean {\n return apiKey.startsWith('live_') || apiKey.startsWith('pk_live_');\n}\n\n/**\n * Checks if a secret key is for a development environment.\n * Supports both legacy format (test_) and new format (sk_test_).\n *\n * @param apiKey - The secret key to check.\n * @returns `true` if the key is for development, `false` otherwise.\n */\nexport function isDevelopmentFromSecretKey(apiKey: string): boolean {\n return apiKey.startsWith('test_') || apiKey.startsWith('sk_test_');\n}\n\n/**\n * Checks if a secret key is for a production environment.\n * Supports both legacy format (live_) and new format (sk_live_).\n *\n * @param apiKey - The secret key to check.\n * @returns `true` if the key is for production, `false` otherwise.\n */\nexport function isProductionFromSecretKey(apiKey: string): boolean {\n return apiKey.startsWith('live_') || apiKey.startsWith('sk_live_');\n}\n\n/**\n * Generates a unique cookie suffix based on the publishable key using SHA-1 hashing.\n * The suffix is base64-encoded and URL-safe (+ and / characters are replaced).\n *\n * @param publishableKey - The publishable key to generate suffix from.\n * @param subtle - The SubtleCrypto interface to use for hashing (defaults to globalThis.crypto.subtle).\n * @returns A promise that resolves to an 8-character URL-safe base64 string.\n */\nexport async function getCookieSuffix(\n publishableKey: string,\n subtle: SubtleCrypto = globalThis.crypto.subtle,\n): Promise<string> {\n const data = new TextEncoder().encode(publishableKey);\n const digest = await subtle.digest('sha-1', data);\n const stringDigest = String.fromCharCode(...new Uint8Array(digest));\n // Base 64 Encoding with URL and Filename Safe Alphabet: https://datatracker.ietf.org/doc/html/rfc4648#section-5\n return isomorphicBtoa(stringDigest).replace(/\\+/gi, '-').replace(/\\//gi, '_').substring(0, 8);\n}\n\n/**\n * Creates a suffixed cookie name by appending the cookie suffix to the base name.\n * Used to create unique cookie names based on the publishable key.\n *\n * @param cookieName - The base cookie name.\n * @param cookieSuffix - The suffix to append (typically generated by getCookieSuffix).\n * @returns The suffixed cookie name in format: `${cookieName}_${cookieSuffix}`.\n */\nexport const getSuffixedCookieName = (cookieName: string, cookieSuffix: string): string => {\n return `${cookieName}_${cookieSuffix}`;\n};\n"],"mappings":";;;;;;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,+BAA+B,QAAyB;CACtE,OAAO,OAAO,WAAW,OAAO,KAAK,OAAO,WAAW,UAAU;AACnE;;;;;;;;AASA,SAAgB,2BAA2B,QAAyB;CAClE,OAAO,OAAO,WAAW,OAAO,KAAK,OAAO,WAAW,UAAU;AACnE;;;;;;;;AASA,SAAgB,0BAA0B,QAAyB;CACjE,OAAO,OAAO,WAAW,OAAO,KAAK,OAAO,WAAW,UAAU;AACnE;;;;;;;;;AAUA,eAAsB,gBACpB,gBACA,SAAuB,WAAW,OAAO,QACxB;CACjB,MAAM,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,cAAc;CACpD,MAAM,SAAS,MAAM,OAAO,OAAO,SAAS,IAAI;CAGhD,OAAO,eAFc,OAAO,aAAa,GAAG,IAAI,WAAW,MAAM,CAEhC,CAAC,CAAC,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAAC,UAAU,GAAG,CAAC;AAC9F;;;;;;;;;AAUA,MAAa,yBAAyB,YAAoB,iBAAiC;CACzF,OAAO,GAAG,WAAW,GAAG;AAC1B"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_keys = require('./keys.js');
|
|
3
3
|
const require_clerkRuntimeError = require('./_chunks/clerkRuntimeError-CYZdTZ_x.js');
|
|
4
|
-
const require_error = require('./_chunks/error-
|
|
4
|
+
const require_error = require('./_chunks/error-CdWUgmMd.js');
|
|
5
5
|
const require_loadScript = require('./loadScript.js');
|
|
6
6
|
const require_proxy = require('./proxy.js');
|
|
7
7
|
const require_url = require('./url.js');
|
|
@@ -140,7 +140,7 @@ const clerkJSScriptUrl = (opts) => {
|
|
|
140
140
|
const clerkUIScriptUrl = (opts) => {
|
|
141
141
|
const { __internal_clerkUIUrl, __internal_clerkUIVersion, proxyUrl, domain, publishableKey } = opts;
|
|
142
142
|
if (__internal_clerkUIUrl) return __internal_clerkUIUrl;
|
|
143
|
-
const version = require_versionSelector.versionSelector(__internal_clerkUIVersion, "1.
|
|
143
|
+
const version = require_versionSelector.versionSelector(__internal_clerkUIVersion, "1.33.0");
|
|
144
144
|
if (proxyUrl && require_proxy.isProxyUrlRelative(proxyUrl)) return buildRelativeProxyScriptUrl(proxyUrl, "ui", version, "ui.browser.js");
|
|
145
145
|
return `https://${buildScriptHost({
|
|
146
146
|
publishableKey,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadClerkJsScript.js","names":["createDevOrStagingUrlCache","buildErrorThrower","ClerkRuntimeError","versionSelector","isProxyUrlRelative","isValidProxyUrl","proxyUrlToAbsoluteURL","parsePublishableKey","addClerkPrefix"],"sources":["../src/loadClerkJsScript.ts"],"sourcesContent":["import { buildErrorThrower, ClerkRuntimeError } from './error';\nimport { createDevOrStagingUrlCache, parsePublishableKey } from './keys';\nimport { loadScript } from './loadScript';\nimport { isProxyUrlRelative, isValidProxyUrl, proxyUrlToAbsoluteURL } from './proxy';\nimport type { SDKMetadata } from './types';\nimport { addClerkPrefix } from './url';\nimport { versionSelector } from './versionSelector';\n\nconst { isDevOrStagingUrl } = createDevOrStagingUrlCache();\n\nconst errorThrower = buildErrorThrower({ packageName: '@clerk/shared' });\n\nexport type LoadClerkJSScriptOptions = {\n publishableKey: string;\n /** @internal */\n __internal_clerkJSUrl?: string;\n /** @internal */\n __internal_clerkJSVersion?: string;\n sdkMetadata?: SDKMetadata;\n proxyUrl?: string;\n domain?: string;\n nonce?: string;\n /**\n * Timeout in milliseconds to wait for clerk-js to load before considering it failed.\n *\n * @default 15000 (15 seconds)\n */\n scriptLoadTimeout?: number;\n};\n\n/**\n * @deprecated Use `LoadClerkJSScriptOptions` instead. This alias will be removed in a future major version.\n */\nexport type LoadClerkJsScriptOptions = LoadClerkJSScriptOptions;\n\nexport type LoadClerkUIScriptOptions = {\n publishableKey: string;\n /** @internal */\n __internal_clerkUIUrl?: string;\n /** @internal */\n __internal_clerkUIVersion?: string;\n proxyUrl?: string;\n domain?: string;\n nonce?: string;\n scriptLoadTimeout?: number;\n};\n\n/**\n * Validates that window.Clerk exists and is properly initialized.\n * This ensures we don't have false positives where the script loads but Clerk is malformed.\n *\n * @returns `true` if window.Clerk exists and has the expected structure with a load method.\n */\nfunction isClerkGlobalProperlyLoaded(prop: 'Clerk' | '__internal_ClerkUICtor'): boolean {\n if (typeof window === 'undefined' || !(window as any)[prop]) {\n return false;\n }\n\n // Basic validation that window.Clerk has the expected structure\n const val = (window as any)[prop];\n return !!val;\n}\nconst isClerkProperlyLoaded = () => isClerkGlobalProperlyLoaded('Clerk');\nconst isClerkUIProperlyLoaded = () => isClerkGlobalProperlyLoaded('__internal_ClerkUICtor');\n\n/**\n * Checks if an existing script has a request error using Performance API.\n *\n * @param scriptUrl - The URL of the script to check.\n * @returns True if the script has failed to load due to a network/HTTP error.\n */\nfunction hasScriptRequestError(scriptUrl: string): boolean {\n if (typeof window === 'undefined' || !window.performance) {\n return false;\n }\n\n const entries = performance.getEntriesByName(scriptUrl, 'resource') as PerformanceResourceTiming[];\n\n if (entries.length === 0) {\n return false;\n }\n\n const scriptEntry = entries[entries.length - 1];\n\n // transferSize === 0 with responseEnd === 0 indicates network failure\n // transferSize === 0 with responseEnd > 0 might be a 4xx/5xx error or blocked request\n if (scriptEntry.transferSize === 0 && scriptEntry.decodedBodySize === 0) {\n // If there was no response at all, it's definitely an error\n if (scriptEntry.responseEnd === 0) {\n return true;\n }\n // If we got a response but no content, likely an HTTP error (4xx/5xx)\n if (scriptEntry.responseEnd > 0 && scriptEntry.responseStart > 0) {\n return true;\n }\n\n if ('responseStatus' in scriptEntry) {\n const status = (scriptEntry as any).responseStatus;\n if (status >= 400) {\n return true;\n }\n if (scriptEntry.responseStatus === 0) {\n return true;\n }\n }\n }\n\n return false;\n}\n\n/**\n * Hotloads the Clerk JS script with robust failure detection.\n *\n * Uses a timeout-based approach to ensure absolute certainty about load success/failure.\n * If the script fails to load within the timeout period, or loads but doesn't create\n * a proper Clerk instance, the promise rejects with an error.\n *\n * @param opts - The options used to build the Clerk JS script URL and load the script.\n * Must include a `publishableKey` if no existing script is found.\n * @returns Promise that resolves with null if Clerk loads successfully, or rejects with an error.\n *\n * @example\n * ```typescript\n * try {\n * await loadClerkJsScript({ publishableKey: 'pk_test_...' });\n * console.log('Clerk loaded successfully');\n * } catch (error) {\n * console.error('Failed to load Clerk:', error.message);\n * }\n * ```\n */\nexport const loadClerkJSScript = async (opts?: LoadClerkJSScriptOptions): Promise<HTMLScriptElement | null> => {\n const timeout = opts?.scriptLoadTimeout ?? 15000;\n const rejectWith = (error?: Error) =>\n new ClerkRuntimeError('Failed to load Clerk JS' + (error?.message ? `, ${error.message}` : ''), {\n code: 'failed_to_load_clerk_js',\n cause: error,\n });\n\n if (isClerkProperlyLoaded()) {\n return null;\n }\n\n if (!opts?.publishableKey) {\n errorThrower.throwMissingPublishableKeyError();\n return null;\n }\n\n const scriptUrl = clerkJSScriptUrl(opts);\n const existingScript = document.querySelector<HTMLScriptElement>('script[data-clerk-js-script]');\n\n if (existingScript) {\n if (hasScriptRequestError(scriptUrl)) {\n existingScript.remove();\n } else {\n try {\n await waitForPredicateWithTimeout(timeout, isClerkProperlyLoaded, rejectWith(), existingScript);\n return null;\n } catch {\n existingScript.remove();\n }\n }\n }\n\n const loadPromise = waitForPredicateWithTimeout(timeout, isClerkProperlyLoaded, rejectWith());\n\n loadScript(scriptUrl, {\n async: true,\n crossOrigin: 'anonymous',\n nonce: opts.nonce,\n beforeLoad: applyAttributesToScript(buildClerkJSScriptAttributes(opts)),\n }).catch(error => {\n throw rejectWith(error);\n });\n\n return loadPromise;\n};\n\nexport const loadClerkUIScript = async (opts?: LoadClerkUIScriptOptions): Promise<HTMLScriptElement | null> => {\n const timeout = opts?.scriptLoadTimeout ?? 15000;\n const rejectWith = (error?: Error) =>\n new ClerkRuntimeError('Failed to load Clerk UI' + (error?.message ? `, ${error.message}` : ''), {\n code: 'failed_to_load_clerk_ui',\n cause: error,\n });\n\n if (isClerkUIProperlyLoaded()) {\n return null;\n }\n\n if (!opts?.publishableKey) {\n errorThrower.throwMissingPublishableKeyError();\n return null;\n }\n\n const scriptUrl = clerkUIScriptUrl(opts);\n const existingScript = document.querySelector<HTMLScriptElement>('script[data-clerk-ui-script]');\n\n if (existingScript) {\n if (hasScriptRequestError(scriptUrl)) {\n existingScript.remove();\n } else {\n try {\n await waitForPredicateWithTimeout(timeout, isClerkUIProperlyLoaded, rejectWith(), existingScript);\n return null;\n } catch {\n existingScript.remove();\n }\n }\n }\n\n const loadPromise = waitForPredicateWithTimeout(timeout, isClerkUIProperlyLoaded, rejectWith());\n\n loadScript(scriptUrl, {\n async: true,\n crossOrigin: 'anonymous',\n nonce: opts.nonce,\n beforeLoad: applyAttributesToScript(buildClerkUIScriptAttributes(opts)),\n }).catch(error => {\n throw rejectWith(error);\n });\n\n return loadPromise;\n};\n\nexport const clerkJSScriptUrl = (opts: LoadClerkJSScriptOptions) => {\n const { __internal_clerkJSUrl, __internal_clerkJSVersion, proxyUrl, domain, publishableKey } = opts;\n\n if (__internal_clerkJSUrl) {\n return __internal_clerkJSUrl;\n }\n\n const version = versionSelector(__internal_clerkJSVersion);\n\n if (proxyUrl && isProxyUrlRelative(proxyUrl)) {\n return buildRelativeProxyScriptUrl(proxyUrl, 'clerk-js', version, 'clerk.browser.js');\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\n return `https://${scriptHost}/npm/@clerk/clerk-js@${version}/dist/clerk.browser.js`;\n};\n\nexport const clerkUIScriptUrl = (opts: LoadClerkUIScriptOptions) => {\n const { __internal_clerkUIUrl, __internal_clerkUIVersion, proxyUrl, domain, publishableKey } = opts;\n\n if (__internal_clerkUIUrl) {\n return __internal_clerkUIUrl;\n }\n\n const version = versionSelector(__internal_clerkUIVersion, UI_PACKAGE_VERSION);\n\n if (proxyUrl && isProxyUrlRelative(proxyUrl)) {\n return buildRelativeProxyScriptUrl(proxyUrl, 'ui', version, 'ui.browser.js');\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\n return `https://${scriptHost}/npm/@clerk/ui@${version}/dist/ui.browser.js`;\n};\n\nexport const buildClerkJSScriptAttributes = (options: LoadClerkJSScriptOptions) => {\n const obj: Record<string, string> = {};\n\n if (options.publishableKey) {\n obj['data-clerk-publishable-key'] = options.publishableKey;\n }\n\n if (options.proxyUrl) {\n obj['data-clerk-proxy-url'] = options.proxyUrl;\n }\n\n if (options.domain) {\n obj['data-clerk-domain'] = options.domain;\n }\n\n if (options.nonce) {\n obj.nonce = options.nonce;\n }\n\n return obj;\n};\n\nexport const buildClerkUIScriptAttributes = (options: LoadClerkUIScriptOptions) => {\n // TODO @nikos do we need this?\n return buildClerkJSScriptAttributes(options);\n};\n\nconst applyAttributesToScript = (attributes: Record<string, string>) => (script: HTMLScriptElement) => {\n for (const attribute in attributes) {\n script.setAttribute(attribute, attributes[attribute]);\n }\n};\n\nconst stripTrailingSlashes = (value: string) => {\n while (value.endsWith('/')) {\n value = value.slice(0, -1);\n }\n\n return value;\n};\n\nconst buildRelativeProxyScriptUrl = (proxyUrl: string, packageName: string, version: string, fileName: string) => {\n return `${stripTrailingSlashes(proxyUrl)}/npm/@clerk/${packageName}@${version}/dist/${fileName}`;\n};\n\nexport const buildScriptHost = (opts: { publishableKey: string; proxyUrl?: string; domain?: string }) => {\n const { proxyUrl, domain, publishableKey } = opts;\n\n if (!!proxyUrl && isValidProxyUrl(proxyUrl)) {\n const resolvedProxyUrl = proxyUrlToAbsoluteURL(proxyUrl);\n\n if (isProxyUrlRelative(resolvedProxyUrl)) {\n return parsePublishableKey(publishableKey)?.frontendApi || '';\n }\n\n return resolvedProxyUrl.replace(/http(s)?:\\/\\//, '');\n } else if (domain && !isDevOrStagingUrl(parsePublishableKey(publishableKey)?.frontendApi || '')) {\n return addClerkPrefix(domain);\n } else {\n return parsePublishableKey(publishableKey)?.frontendApi || '';\n }\n};\n\nfunction waitForPredicateWithTimeout(\n timeoutMs: number,\n predicate: () => boolean,\n rejectWith: Error,\n existingScript?: HTMLScriptElement,\n): Promise<HTMLScriptElement | null> {\n return new Promise((resolve, reject) => {\n let resolved = false;\n\n const cleanup = (timeoutId: ReturnType<typeof setTimeout>, pollInterval: ReturnType<typeof setInterval>) => {\n clearTimeout(timeoutId);\n clearInterval(pollInterval);\n };\n\n // Bail out early if the script fails to load, instead of waiting for the entire timeout\n existingScript?.addEventListener('error', () => {\n cleanup(timeoutId, pollInterval);\n reject(rejectWith);\n });\n\n const checkAndResolve = () => {\n if (resolved) {\n return;\n }\n\n if (predicate()) {\n resolved = true;\n cleanup(timeoutId, pollInterval);\n resolve(null);\n }\n };\n\n const handleTimeout = () => {\n if (resolved) {\n return;\n }\n\n resolved = true;\n cleanup(timeoutId, pollInterval);\n\n if (!predicate()) {\n reject(rejectWith);\n } else {\n resolve(null);\n }\n };\n\n const timeoutId = setTimeout(handleTimeout, timeoutMs);\n\n checkAndResolve();\n\n const pollInterval = setInterval(() => {\n if (resolved) {\n clearInterval(pollInterval);\n return;\n }\n checkAndResolve();\n }, 100);\n });\n}\n\nexport function setClerkJSLoadingErrorPackageName(packageName: string) {\n errorThrower.setPackageName({ packageName });\n}\n\n/**\n * @deprecated Use `loadClerkJSScript` instead. This alias will be removed in a future major version.\n */\nexport const loadClerkJsScript = loadClerkJSScript;\n\n/**\n * @deprecated Use `clerkJSScriptUrl` instead. This alias will be removed in a future major version.\n */\nexport const clerkJsScriptUrl = clerkJSScriptUrl;\n\n/**\n * @deprecated Use `buildClerkJSScriptAttributes` instead. This alias will be removed in a future major version.\n */\nexport const buildClerkJsScriptAttributes = buildClerkJSScriptAttributes;\n\n/**\n * @deprecated Use `setClerkJSLoadingErrorPackageName` instead. This alias will be removed in a future major version.\n */\nexport const setClerkJsLoadingErrorPackageName = setClerkJSLoadingErrorPackageName;\n"],"mappings":";;;;;;;;;;AAQA,MAAM,EAAE,sBAAsBA,wCAA2B;AAEzD,MAAM,eAAeC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
|
1
|
+
{"version":3,"file":"loadClerkJsScript.js","names":["createDevOrStagingUrlCache","buildErrorThrower","ClerkRuntimeError","versionSelector","isProxyUrlRelative","isValidProxyUrl","proxyUrlToAbsoluteURL","parsePublishableKey","addClerkPrefix"],"sources":["../src/loadClerkJsScript.ts"],"sourcesContent":["import { buildErrorThrower, ClerkRuntimeError } from './error';\nimport { createDevOrStagingUrlCache, parsePublishableKey } from './keys';\nimport { loadScript } from './loadScript';\nimport { isProxyUrlRelative, isValidProxyUrl, proxyUrlToAbsoluteURL } from './proxy';\nimport type { SDKMetadata } from './types';\nimport { addClerkPrefix } from './url';\nimport { versionSelector } from './versionSelector';\n\nconst { isDevOrStagingUrl } = createDevOrStagingUrlCache();\n\nconst errorThrower = buildErrorThrower({ packageName: '@clerk/shared' });\n\nexport type LoadClerkJSScriptOptions = {\n publishableKey: string;\n /** @internal */\n __internal_clerkJSUrl?: string;\n /** @internal */\n __internal_clerkJSVersion?: string;\n sdkMetadata?: SDKMetadata;\n proxyUrl?: string;\n domain?: string;\n nonce?: string;\n /**\n * Timeout in milliseconds to wait for clerk-js to load before considering it failed.\n *\n * @default 15000 (15 seconds)\n */\n scriptLoadTimeout?: number;\n};\n\n/**\n * @deprecated Use `LoadClerkJSScriptOptions` instead. This alias will be removed in a future major version.\n */\nexport type LoadClerkJsScriptOptions = LoadClerkJSScriptOptions;\n\nexport type LoadClerkUIScriptOptions = {\n publishableKey: string;\n /** @internal */\n __internal_clerkUIUrl?: string;\n /** @internal */\n __internal_clerkUIVersion?: string;\n proxyUrl?: string;\n domain?: string;\n nonce?: string;\n scriptLoadTimeout?: number;\n};\n\n/**\n * Validates that window.Clerk exists and is properly initialized.\n * This ensures we don't have false positives where the script loads but Clerk is malformed.\n *\n * @returns `true` if window.Clerk exists and has the expected structure with a load method.\n */\nfunction isClerkGlobalProperlyLoaded(prop: 'Clerk' | '__internal_ClerkUICtor'): boolean {\n if (typeof window === 'undefined' || !(window as any)[prop]) {\n return false;\n }\n\n // Basic validation that window.Clerk has the expected structure\n const val = (window as any)[prop];\n return !!val;\n}\nconst isClerkProperlyLoaded = () => isClerkGlobalProperlyLoaded('Clerk');\nconst isClerkUIProperlyLoaded = () => isClerkGlobalProperlyLoaded('__internal_ClerkUICtor');\n\n/**\n * Checks if an existing script has a request error using Performance API.\n *\n * @param scriptUrl - The URL of the script to check.\n * @returns True if the script has failed to load due to a network/HTTP error.\n */\nfunction hasScriptRequestError(scriptUrl: string): boolean {\n if (typeof window === 'undefined' || !window.performance) {\n return false;\n }\n\n const entries = performance.getEntriesByName(scriptUrl, 'resource') as PerformanceResourceTiming[];\n\n if (entries.length === 0) {\n return false;\n }\n\n const scriptEntry = entries[entries.length - 1];\n\n // transferSize === 0 with responseEnd === 0 indicates network failure\n // transferSize === 0 with responseEnd > 0 might be a 4xx/5xx error or blocked request\n if (scriptEntry.transferSize === 0 && scriptEntry.decodedBodySize === 0) {\n // If there was no response at all, it's definitely an error\n if (scriptEntry.responseEnd === 0) {\n return true;\n }\n // If we got a response but no content, likely an HTTP error (4xx/5xx)\n if (scriptEntry.responseEnd > 0 && scriptEntry.responseStart > 0) {\n return true;\n }\n\n if ('responseStatus' in scriptEntry) {\n const status = (scriptEntry as any).responseStatus;\n if (status >= 400) {\n return true;\n }\n if (scriptEntry.responseStatus === 0) {\n return true;\n }\n }\n }\n\n return false;\n}\n\n/**\n * Hotloads the Clerk JS script with robust failure detection.\n *\n * Uses a timeout-based approach to ensure absolute certainty about load success/failure.\n * If the script fails to load within the timeout period, or loads but doesn't create\n * a proper Clerk instance, the promise rejects with an error.\n *\n * @param opts - The options used to build the Clerk JS script URL and load the script.\n * Must include a `publishableKey` if no existing script is found.\n * @returns Promise that resolves with null if Clerk loads successfully, or rejects with an error.\n *\n * @example\n * ```typescript\n * try {\n * await loadClerkJsScript({ publishableKey: 'pk_test_...' });\n * console.log('Clerk loaded successfully');\n * } catch (error) {\n * console.error('Failed to load Clerk:', error.message);\n * }\n * ```\n */\nexport const loadClerkJSScript = async (opts?: LoadClerkJSScriptOptions): Promise<HTMLScriptElement | null> => {\n const timeout = opts?.scriptLoadTimeout ?? 15000;\n const rejectWith = (error?: Error) =>\n new ClerkRuntimeError('Failed to load Clerk JS' + (error?.message ? `, ${error.message}` : ''), {\n code: 'failed_to_load_clerk_js',\n cause: error,\n });\n\n if (isClerkProperlyLoaded()) {\n return null;\n }\n\n if (!opts?.publishableKey) {\n errorThrower.throwMissingPublishableKeyError();\n return null;\n }\n\n const scriptUrl = clerkJSScriptUrl(opts);\n const existingScript = document.querySelector<HTMLScriptElement>('script[data-clerk-js-script]');\n\n if (existingScript) {\n if (hasScriptRequestError(scriptUrl)) {\n existingScript.remove();\n } else {\n try {\n await waitForPredicateWithTimeout(timeout, isClerkProperlyLoaded, rejectWith(), existingScript);\n return null;\n } catch {\n existingScript.remove();\n }\n }\n }\n\n const loadPromise = waitForPredicateWithTimeout(timeout, isClerkProperlyLoaded, rejectWith());\n\n loadScript(scriptUrl, {\n async: true,\n crossOrigin: 'anonymous',\n nonce: opts.nonce,\n beforeLoad: applyAttributesToScript(buildClerkJSScriptAttributes(opts)),\n }).catch(error => {\n throw rejectWith(error);\n });\n\n return loadPromise;\n};\n\nexport const loadClerkUIScript = async (opts?: LoadClerkUIScriptOptions): Promise<HTMLScriptElement | null> => {\n const timeout = opts?.scriptLoadTimeout ?? 15000;\n const rejectWith = (error?: Error) =>\n new ClerkRuntimeError('Failed to load Clerk UI' + (error?.message ? `, ${error.message}` : ''), {\n code: 'failed_to_load_clerk_ui',\n cause: error,\n });\n\n if (isClerkUIProperlyLoaded()) {\n return null;\n }\n\n if (!opts?.publishableKey) {\n errorThrower.throwMissingPublishableKeyError();\n return null;\n }\n\n const scriptUrl = clerkUIScriptUrl(opts);\n const existingScript = document.querySelector<HTMLScriptElement>('script[data-clerk-ui-script]');\n\n if (existingScript) {\n if (hasScriptRequestError(scriptUrl)) {\n existingScript.remove();\n } else {\n try {\n await waitForPredicateWithTimeout(timeout, isClerkUIProperlyLoaded, rejectWith(), existingScript);\n return null;\n } catch {\n existingScript.remove();\n }\n }\n }\n\n const loadPromise = waitForPredicateWithTimeout(timeout, isClerkUIProperlyLoaded, rejectWith());\n\n loadScript(scriptUrl, {\n async: true,\n crossOrigin: 'anonymous',\n nonce: opts.nonce,\n beforeLoad: applyAttributesToScript(buildClerkUIScriptAttributes(opts)),\n }).catch(error => {\n throw rejectWith(error);\n });\n\n return loadPromise;\n};\n\nexport const clerkJSScriptUrl = (opts: LoadClerkJSScriptOptions) => {\n const { __internal_clerkJSUrl, __internal_clerkJSVersion, proxyUrl, domain, publishableKey } = opts;\n\n if (__internal_clerkJSUrl) {\n return __internal_clerkJSUrl;\n }\n\n const version = versionSelector(__internal_clerkJSVersion);\n\n if (proxyUrl && isProxyUrlRelative(proxyUrl)) {\n return buildRelativeProxyScriptUrl(proxyUrl, 'clerk-js', version, 'clerk.browser.js');\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\n return `https://${scriptHost}/npm/@clerk/clerk-js@${version}/dist/clerk.browser.js`;\n};\n\nexport const clerkUIScriptUrl = (opts: LoadClerkUIScriptOptions) => {\n const { __internal_clerkUIUrl, __internal_clerkUIVersion, proxyUrl, domain, publishableKey } = opts;\n\n if (__internal_clerkUIUrl) {\n return __internal_clerkUIUrl;\n }\n\n const version = versionSelector(__internal_clerkUIVersion, UI_PACKAGE_VERSION);\n\n if (proxyUrl && isProxyUrlRelative(proxyUrl)) {\n return buildRelativeProxyScriptUrl(proxyUrl, 'ui', version, 'ui.browser.js');\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\n return `https://${scriptHost}/npm/@clerk/ui@${version}/dist/ui.browser.js`;\n};\n\nexport const buildClerkJSScriptAttributes = (options: LoadClerkJSScriptOptions) => {\n const obj: Record<string, string> = {};\n\n if (options.publishableKey) {\n obj['data-clerk-publishable-key'] = options.publishableKey;\n }\n\n if (options.proxyUrl) {\n obj['data-clerk-proxy-url'] = options.proxyUrl;\n }\n\n if (options.domain) {\n obj['data-clerk-domain'] = options.domain;\n }\n\n if (options.nonce) {\n obj.nonce = options.nonce;\n }\n\n return obj;\n};\n\nexport const buildClerkUIScriptAttributes = (options: LoadClerkUIScriptOptions) => {\n // TODO @nikos do we need this?\n return buildClerkJSScriptAttributes(options);\n};\n\nconst applyAttributesToScript = (attributes: Record<string, string>) => (script: HTMLScriptElement) => {\n for (const attribute in attributes) {\n script.setAttribute(attribute, attributes[attribute]);\n }\n};\n\nconst stripTrailingSlashes = (value: string) => {\n while (value.endsWith('/')) {\n value = value.slice(0, -1);\n }\n\n return value;\n};\n\nconst buildRelativeProxyScriptUrl = (proxyUrl: string, packageName: string, version: string, fileName: string) => {\n return `${stripTrailingSlashes(proxyUrl)}/npm/@clerk/${packageName}@${version}/dist/${fileName}`;\n};\n\nexport const buildScriptHost = (opts: { publishableKey: string; proxyUrl?: string; domain?: string }) => {\n const { proxyUrl, domain, publishableKey } = opts;\n\n if (!!proxyUrl && isValidProxyUrl(proxyUrl)) {\n const resolvedProxyUrl = proxyUrlToAbsoluteURL(proxyUrl);\n\n if (isProxyUrlRelative(resolvedProxyUrl)) {\n return parsePublishableKey(publishableKey)?.frontendApi || '';\n }\n\n return resolvedProxyUrl.replace(/http(s)?:\\/\\//, '');\n } else if (domain && !isDevOrStagingUrl(parsePublishableKey(publishableKey)?.frontendApi || '')) {\n return addClerkPrefix(domain);\n } else {\n return parsePublishableKey(publishableKey)?.frontendApi || '';\n }\n};\n\nfunction waitForPredicateWithTimeout(\n timeoutMs: number,\n predicate: () => boolean,\n rejectWith: Error,\n existingScript?: HTMLScriptElement,\n): Promise<HTMLScriptElement | null> {\n return new Promise((resolve, reject) => {\n let resolved = false;\n\n const cleanup = (timeoutId: ReturnType<typeof setTimeout>, pollInterval: ReturnType<typeof setInterval>) => {\n clearTimeout(timeoutId);\n clearInterval(pollInterval);\n };\n\n // Bail out early if the script fails to load, instead of waiting for the entire timeout\n existingScript?.addEventListener('error', () => {\n cleanup(timeoutId, pollInterval);\n reject(rejectWith);\n });\n\n const checkAndResolve = () => {\n if (resolved) {\n return;\n }\n\n if (predicate()) {\n resolved = true;\n cleanup(timeoutId, pollInterval);\n resolve(null);\n }\n };\n\n const handleTimeout = () => {\n if (resolved) {\n return;\n }\n\n resolved = true;\n cleanup(timeoutId, pollInterval);\n\n if (!predicate()) {\n reject(rejectWith);\n } else {\n resolve(null);\n }\n };\n\n const timeoutId = setTimeout(handleTimeout, timeoutMs);\n\n checkAndResolve();\n\n const pollInterval = setInterval(() => {\n if (resolved) {\n clearInterval(pollInterval);\n return;\n }\n checkAndResolve();\n }, 100);\n });\n}\n\nexport function setClerkJSLoadingErrorPackageName(packageName: string) {\n errorThrower.setPackageName({ packageName });\n}\n\n/**\n * @deprecated Use `loadClerkJSScript` instead. This alias will be removed in a future major version.\n */\nexport const loadClerkJsScript = loadClerkJSScript;\n\n/**\n * @deprecated Use `clerkJSScriptUrl` instead. This alias will be removed in a future major version.\n */\nexport const clerkJsScriptUrl = clerkJSScriptUrl;\n\n/**\n * @deprecated Use `buildClerkJSScriptAttributes` instead. This alias will be removed in a future major version.\n */\nexport const buildClerkJsScriptAttributes = buildClerkJSScriptAttributes;\n\n/**\n * @deprecated Use `setClerkJSLoadingErrorPackageName` instead. This alias will be removed in a future major version.\n */\nexport const setClerkJsLoadingErrorPackageName = setClerkJSLoadingErrorPackageName;\n"],"mappings":";;;;;;;;;;AAQA,MAAM,EAAE,sBAAsBA,wCAA2B;AAEzD,MAAM,eAAeC,gCAAkB,EAAE,aAAa,gBAAgB,CAAC;;;;;;;AA2CvE,SAAS,4BAA4B,MAAmD;CACtF,IAAI,OAAO,WAAW,eAAe,CAAE,OAAe,OACpD,OAAO;CAKT,OAAO,CAAC,CADK,OAAe;AAE9B;AACA,MAAM,8BAA8B,4BAA4B,OAAO;AACvE,MAAM,gCAAgC,4BAA4B,wBAAwB;;;;;;;AAQ1F,SAAS,sBAAsB,WAA4B;CACzD,IAAI,OAAO,W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e,MAAM;MAE5B,OAAOD,iCAAoB,cAAc,CAAC,EAAE,eAAe;AAE/D;AAEA,SAAS,4BACP,WACA,WACA,YACA,gBACmC;CACnC,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,IAAI,WAAW;EAEf,MAAM,WAAW,WAA0C,iBAAiD;GAC1G,aAAa,SAAS;GACtB,cAAc,YAAY;EAC5B;EAGA,gBAAgB,iBAAiB,eAAe;GAC9C,QAAQ,WAAW,YAAY;GAC/B,OAAO,UAAU;EACnB,CAAC;EAED,MAAM,wBAAwB;GAC5B,IAAI,UACF;GAGF,IAAI,UAAU,GAAG;IACf,WAAW;IACX,QAAQ,WAAW,YAAY;IAC/B,QAAQ,IAAI;GACd;EACF;EAEA,MAAM,sBAAsB;GAC1B,IAAI,UACF;GAGF,WAAW;GACX,QAAQ,WAAW,YAAY;GAE/B,IAAI,CAAC,UAAU,GACb,OAAO,UAAU;QAEjB,QAAQ,IAAI;EAEhB;EAEA,MAAM,YAAY,WAAW,eAAe,SAAS;EAErD,gBAAgB;EAEhB,MAAM,eAAe,kBAAkB;GACrC,IAAI,UAAU;IACZ,cAAc,YAAY;IAC1B;GACF;GACA,gBAAgB;EAClB,GAAG,GAAG;CACR,CAAC;AACH;AAEA,SAAgB,kCAAkC,aAAqB;CACrE,aAAa,eAAe,EAAE,YAAY,CAAC;AAC7C;;;;AAKA,MAAa,oBAAoB;;;;AAKjC,MAAa,mBAAmB;;;;AAKhC,MAAa,+BAA+B;;;;AAK5C,MAAa,oCAAoC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createDevOrStagingUrlCache, parsePublishableKey } from "./keys.mjs";
|
|
2
2
|
import { t as ClerkRuntimeError } from "./_chunks/clerkRuntimeError-DlesLWqO.mjs";
|
|
3
|
-
import { y as buildErrorThrower } from "./_chunks/error-
|
|
3
|
+
import { y as buildErrorThrower } from "./_chunks/error-wrUdW78M.mjs";
|
|
4
4
|
import { loadScript } from "./loadScript.mjs";
|
|
5
5
|
import { isProxyUrlRelative, isValidProxyUrl, proxyUrlToAbsoluteURL } from "./proxy.mjs";
|
|
6
6
|
import { addClerkPrefix } from "./url.mjs";
|
|
@@ -139,7 +139,7 @@ const clerkJSScriptUrl = (opts) => {
|
|
|
139
139
|
const clerkUIScriptUrl = (opts) => {
|
|
140
140
|
const { __internal_clerkUIUrl, __internal_clerkUIVersion, proxyUrl, domain, publishableKey } = opts;
|
|
141
141
|
if (__internal_clerkUIUrl) return __internal_clerkUIUrl;
|
|
142
|
-
const version = versionSelector(__internal_clerkUIVersion, "1.
|
|
142
|
+
const version = versionSelector(__internal_clerkUIVersion, "1.33.0");
|
|
143
143
|
if (proxyUrl && isProxyUrlRelative(proxyUrl)) return buildRelativeProxyScriptUrl(proxyUrl, "ui", version, "ui.browser.js");
|
|
144
144
|
return `https://${buildScriptHost({
|
|
145
145
|
publishableKey,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadClerkJsScript.mjs","names":[],"sources":["../src/loadClerkJsScript.ts"],"sourcesContent":["import { buildErrorThrower, ClerkRuntimeError } from './error';\nimport { createDevOrStagingUrlCache, parsePublishableKey } from './keys';\nimport { loadScript } from './loadScript';\nimport { isProxyUrlRelative, isValidProxyUrl, proxyUrlToAbsoluteURL } from './proxy';\nimport type { SDKMetadata } from './types';\nimport { addClerkPrefix } from './url';\nimport { versionSelector } from './versionSelector';\n\nconst { isDevOrStagingUrl } = createDevOrStagingUrlCache();\n\nconst errorThrower = buildErrorThrower({ packageName: '@clerk/shared' });\n\nexport type LoadClerkJSScriptOptions = {\n publishableKey: string;\n /** @internal */\n __internal_clerkJSUrl?: string;\n /** @internal */\n __internal_clerkJSVersion?: string;\n sdkMetadata?: SDKMetadata;\n proxyUrl?: string;\n domain?: string;\n nonce?: string;\n /**\n * Timeout in milliseconds to wait for clerk-js to load before considering it failed.\n *\n * @default 15000 (15 seconds)\n */\n scriptLoadTimeout?: number;\n};\n\n/**\n * @deprecated Use `LoadClerkJSScriptOptions` instead. This alias will be removed in a future major version.\n */\nexport type LoadClerkJsScriptOptions = LoadClerkJSScriptOptions;\n\nexport type LoadClerkUIScriptOptions = {\n publishableKey: string;\n /** @internal */\n __internal_clerkUIUrl?: string;\n /** @internal */\n __internal_clerkUIVersion?: string;\n proxyUrl?: string;\n domain?: string;\n nonce?: string;\n scriptLoadTimeout?: number;\n};\n\n/**\n * Validates that window.Clerk exists and is properly initialized.\n * This ensures we don't have false positives where the script loads but Clerk is malformed.\n *\n * @returns `true` if window.Clerk exists and has the expected structure with a load method.\n */\nfunction isClerkGlobalProperlyLoaded(prop: 'Clerk' | '__internal_ClerkUICtor'): boolean {\n if (typeof window === 'undefined' || !(window as any)[prop]) {\n return false;\n }\n\n // Basic validation that window.Clerk has the expected structure\n const val = (window as any)[prop];\n return !!val;\n}\nconst isClerkProperlyLoaded = () => isClerkGlobalProperlyLoaded('Clerk');\nconst isClerkUIProperlyLoaded = () => isClerkGlobalProperlyLoaded('__internal_ClerkUICtor');\n\n/**\n * Checks if an existing script has a request error using Performance API.\n *\n * @param scriptUrl - The URL of the script to check.\n * @returns True if the script has failed to load due to a network/HTTP error.\n */\nfunction hasScriptRequestError(scriptUrl: string): boolean {\n if (typeof window === 'undefined' || !window.performance) {\n return false;\n }\n\n const entries = performance.getEntriesByName(scriptUrl, 'resource') as PerformanceResourceTiming[];\n\n if (entries.length === 0) {\n return false;\n }\n\n const scriptEntry = entries[entries.length - 1];\n\n // transferSize === 0 with responseEnd === 0 indicates network failure\n // transferSize === 0 with responseEnd > 0 might be a 4xx/5xx error or blocked request\n if (scriptEntry.transferSize === 0 && scriptEntry.decodedBodySize === 0) {\n // If there was no response at all, it's definitely an error\n if (scriptEntry.responseEnd === 0) {\n return true;\n }\n // If we got a response but no content, likely an HTTP error (4xx/5xx)\n if (scriptEntry.responseEnd > 0 && scriptEntry.responseStart > 0) {\n return true;\n }\n\n if ('responseStatus' in scriptEntry) {\n const status = (scriptEntry as any).responseStatus;\n if (status >= 400) {\n return true;\n }\n if (scriptEntry.responseStatus === 0) {\n return true;\n }\n }\n }\n\n return false;\n}\n\n/**\n * Hotloads the Clerk JS script with robust failure detection.\n *\n * Uses a timeout-based approach to ensure absolute certainty about load success/failure.\n * If the script fails to load within the timeout period, or loads but doesn't create\n * a proper Clerk instance, the promise rejects with an error.\n *\n * @param opts - The options used to build the Clerk JS script URL and load the script.\n * Must include a `publishableKey` if no existing script is found.\n * @returns Promise that resolves with null if Clerk loads successfully, or rejects with an error.\n *\n * @example\n * ```typescript\n * try {\n * await loadClerkJsScript({ publishableKey: 'pk_test_...' });\n * console.log('Clerk loaded successfully');\n * } catch (error) {\n * console.error('Failed to load Clerk:', error.message);\n * }\n * ```\n */\nexport const loadClerkJSScript = async (opts?: LoadClerkJSScriptOptions): Promise<HTMLScriptElement | null> => {\n const timeout = opts?.scriptLoadTimeout ?? 15000;\n const rejectWith = (error?: Error) =>\n new ClerkRuntimeError('Failed to load Clerk JS' + (error?.message ? `, ${error.message}` : ''), {\n code: 'failed_to_load_clerk_js',\n cause: error,\n });\n\n if (isClerkProperlyLoaded()) {\n return null;\n }\n\n if (!opts?.publishableKey) {\n errorThrower.throwMissingPublishableKeyError();\n return null;\n }\n\n const scriptUrl = clerkJSScriptUrl(opts);\n const existingScript = document.querySelector<HTMLScriptElement>('script[data-clerk-js-script]');\n\n if (existingScript) {\n if (hasScriptRequestError(scriptUrl)) {\n existingScript.remove();\n } else {\n try {\n await waitForPredicateWithTimeout(timeout, isClerkProperlyLoaded, rejectWith(), existingScript);\n return null;\n } catch {\n existingScript.remove();\n }\n }\n }\n\n const loadPromise = waitForPredicateWithTimeout(timeout, isClerkProperlyLoaded, rejectWith());\n\n loadScript(scriptUrl, {\n async: true,\n crossOrigin: 'anonymous',\n nonce: opts.nonce,\n beforeLoad: applyAttributesToScript(buildClerkJSScriptAttributes(opts)),\n }).catch(error => {\n throw rejectWith(error);\n });\n\n return loadPromise;\n};\n\nexport const loadClerkUIScript = async (opts?: LoadClerkUIScriptOptions): Promise<HTMLScriptElement | null> => {\n const timeout = opts?.scriptLoadTimeout ?? 15000;\n const rejectWith = (error?: Error) =>\n new ClerkRuntimeError('Failed to load Clerk UI' + (error?.message ? `, ${error.message}` : ''), {\n code: 'failed_to_load_clerk_ui',\n cause: error,\n });\n\n if (isClerkUIProperlyLoaded()) {\n return null;\n }\n\n if (!opts?.publishableKey) {\n errorThrower.throwMissingPublishableKeyError();\n return null;\n }\n\n const scriptUrl = clerkUIScriptUrl(opts);\n const existingScript = document.querySelector<HTMLScriptElement>('script[data-clerk-ui-script]');\n\n if (existingScript) {\n if (hasScriptRequestError(scriptUrl)) {\n existingScript.remove();\n } else {\n try {\n await waitForPredicateWithTimeout(timeout, isClerkUIProperlyLoaded, rejectWith(), existingScript);\n return null;\n } catch {\n existingScript.remove();\n }\n }\n }\n\n const loadPromise = waitForPredicateWithTimeout(timeout, isClerkUIProperlyLoaded, rejectWith());\n\n loadScript(scriptUrl, {\n async: true,\n crossOrigin: 'anonymous',\n nonce: opts.nonce,\n beforeLoad: applyAttributesToScript(buildClerkUIScriptAttributes(opts)),\n }).catch(error => {\n throw rejectWith(error);\n });\n\n return loadPromise;\n};\n\nexport const clerkJSScriptUrl = (opts: LoadClerkJSScriptOptions) => {\n const { __internal_clerkJSUrl, __internal_clerkJSVersion, proxyUrl, domain, publishableKey } = opts;\n\n if (__internal_clerkJSUrl) {\n return __internal_clerkJSUrl;\n }\n\n const version = versionSelector(__internal_clerkJSVersion);\n\n if (proxyUrl && isProxyUrlRelative(proxyUrl)) {\n return buildRelativeProxyScriptUrl(proxyUrl, 'clerk-js', version, 'clerk.browser.js');\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\n return `https://${scriptHost}/npm/@clerk/clerk-js@${version}/dist/clerk.browser.js`;\n};\n\nexport const clerkUIScriptUrl = (opts: LoadClerkUIScriptOptions) => {\n const { __internal_clerkUIUrl, __internal_clerkUIVersion, proxyUrl, domain, publishableKey } = opts;\n\n if (__internal_clerkUIUrl) {\n return __internal_clerkUIUrl;\n }\n\n const version = versionSelector(__internal_clerkUIVersion, UI_PACKAGE_VERSION);\n\n if (proxyUrl && isProxyUrlRelative(proxyUrl)) {\n return buildRelativeProxyScriptUrl(proxyUrl, 'ui', version, 'ui.browser.js');\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\n return `https://${scriptHost}/npm/@clerk/ui@${version}/dist/ui.browser.js`;\n};\n\nexport const buildClerkJSScriptAttributes = (options: LoadClerkJSScriptOptions) => {\n const obj: Record<string, string> = {};\n\n if (options.publishableKey) {\n obj['data-clerk-publishable-key'] = options.publishableKey;\n }\n\n if (options.proxyUrl) {\n obj['data-clerk-proxy-url'] = options.proxyUrl;\n }\n\n if (options.domain) {\n obj['data-clerk-domain'] = options.domain;\n }\n\n if (options.nonce) {\n obj.nonce = options.nonce;\n }\n\n return obj;\n};\n\nexport const buildClerkUIScriptAttributes = (options: LoadClerkUIScriptOptions) => {\n // TODO @nikos do we need this?\n return buildClerkJSScriptAttributes(options);\n};\n\nconst applyAttributesToScript = (attributes: Record<string, string>) => (script: HTMLScriptElement) => {\n for (const attribute in attributes) {\n script.setAttribute(attribute, attributes[attribute]);\n }\n};\n\nconst stripTrailingSlashes = (value: string) => {\n while (value.endsWith('/')) {\n value = value.slice(0, -1);\n }\n\n return value;\n};\n\nconst buildRelativeProxyScriptUrl = (proxyUrl: string, packageName: string, version: string, fileName: string) => {\n return `${stripTrailingSlashes(proxyUrl)}/npm/@clerk/${packageName}@${version}/dist/${fileName}`;\n};\n\nexport const buildScriptHost = (opts: { publishableKey: string; proxyUrl?: string; domain?: string }) => {\n const { proxyUrl, domain, publishableKey } = opts;\n\n if (!!proxyUrl && isValidProxyUrl(proxyUrl)) {\n const resolvedProxyUrl = proxyUrlToAbsoluteURL(proxyUrl);\n\n if (isProxyUrlRelative(resolvedProxyUrl)) {\n return parsePublishableKey(publishableKey)?.frontendApi || '';\n }\n\n return resolvedProxyUrl.replace(/http(s)?:\\/\\//, '');\n } else if (domain && !isDevOrStagingUrl(parsePublishableKey(publishableKey)?.frontendApi || '')) {\n return addClerkPrefix(domain);\n } else {\n return parsePublishableKey(publishableKey)?.frontendApi || '';\n }\n};\n\nfunction waitForPredicateWithTimeout(\n timeoutMs: number,\n predicate: () => boolean,\n rejectWith: Error,\n existingScript?: HTMLScriptElement,\n): Promise<HTMLScriptElement | null> {\n return new Promise((resolve, reject) => {\n let resolved = false;\n\n const cleanup = (timeoutId: ReturnType<typeof setTimeout>, pollInterval: ReturnType<typeof setInterval>) => {\n clearTimeout(timeoutId);\n clearInterval(pollInterval);\n };\n\n // Bail out early if the script fails to load, instead of waiting for the entire timeout\n existingScript?.addEventListener('error', () => {\n cleanup(timeoutId, pollInterval);\n reject(rejectWith);\n });\n\n const checkAndResolve = () => {\n if (resolved) {\n return;\n }\n\n if (predicate()) {\n resolved = true;\n cleanup(timeoutId, pollInterval);\n resolve(null);\n }\n };\n\n const handleTimeout = () => {\n if (resolved) {\n return;\n }\n\n resolved = true;\n cleanup(timeoutId, pollInterval);\n\n if (!predicate()) {\n reject(rejectWith);\n } else {\n resolve(null);\n }\n };\n\n const timeoutId = setTimeout(handleTimeout, timeoutMs);\n\n checkAndResolve();\n\n const pollInterval = setInterval(() => {\n if (resolved) {\n clearInterval(pollInterval);\n return;\n }\n checkAndResolve();\n }, 100);\n });\n}\n\nexport function setClerkJSLoadingErrorPackageName(packageName: string) {\n errorThrower.setPackageName({ packageName });\n}\n\n/**\n * @deprecated Use `loadClerkJSScript` instead. This alias will be removed in a future major version.\n */\nexport const loadClerkJsScript = loadClerkJSScript;\n\n/**\n * @deprecated Use `clerkJSScriptUrl` instead. This alias will be removed in a future major version.\n */\nexport const clerkJsScriptUrl = clerkJSScriptUrl;\n\n/**\n * @deprecated Use `buildClerkJSScriptAttributes` instead. This alias will be removed in a future major version.\n */\nexport const buildClerkJsScriptAttributes = buildClerkJSScriptAttributes;\n\n/**\n * @deprecated Use `setClerkJSLoadingErrorPackageName` instead. This alias will be removed in a future major version.\n */\nexport const setClerkJsLoadingErrorPackageName = setClerkJSLoadingErrorPackageName;\n"],"mappings":";;;;;;;;;AAQA,MAAM,EAAE,sBAAsB,2BAA2B;AAEzD,MAAM,eAAe,kBAAkB,EAAE,aAAa,gBAAgB,CAAC;;;;;;;AA2CvE,SAAS,4BAA4B,MAAmD;CACtF,IAAI,OAAO,WAAW,eAAe,CAAE,OAAe,OACpD,OAAO;CAKT,OAAO,CAAC,CADK,OAAe;AAE9B;AACA,MAAM,8BAA8B,4BAA4B,OAAO;AACvE,MAAM,gCAAgC,4BAA4B,wBAAwB;;;;;;;AAQ1F,SAAS,sBAAsB,WAA4B;CACzD,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,aAC3C,OAAO;CAGT,MAAM,UAAU,YAAY,iBAAiB,WAAW,UAAU;CAElE,IAAI,QAAQ,WAAW,GACrB,OAAO;CAGT,MAAM,cAAc,QAAQ,QAAQ,SAAS;CAI7C,IAAI,YAAY,iBAAiB,KAAK,YAAY,oBAAoB,GAAG;EAEvE,IAAI,YAAY,gBAAgB,GAC9B,OAAO;EAGT,IAAI,YAAY,cAAc,KAAK,YAAY,gBAAgB,GAC7D,OAAO;EAGT,IAAI,oBAAoB,aAAa;GAEnC,IADgB,YAAoB,kBACtB,KACZ,OAAO;GAET,IAAI,YAAY,mBAAmB,GACjC,OAAO;EAEX;CACF;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAa,oBAAoB,OAAO,SAAuE;CAC7G,MAAM,UAAU,MAAM,qBAAqB;CAC3C,MAAM,cAAc,UAClB,IAAI,kBAAkB,6BAA6B,OAAO,UAAU,KAAK,MAAM,YAAY,KAAK;EAC9F,MAAM;EACN,OAAO;CACT,CAAC;CAEH,IAAI,sBAAsB,GACxB,OAAO;CAGT,IAAI,CAAC,MAAM,gBAAgB;EACzB,aAAa,gCAAgC;EAC7C,OAAO;CACT;CAEA,MAAM,YAAY,iBAAiB,I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a,eAAe,EAAE,YAAY,CAAC;AAC7C;;;;AAKA,MAAa,oBAAoB;;;;AAKjC,MAAa,mBAAmB;;;;AAKhC,MAAa,+BAA+B;;;;AAK5C,MAAa,oCAAoC"}
|
|
1
|
+
{"version":3,"file":"loadClerkJsScript.mjs","names":[],"sources":["../src/loadClerkJsScript.ts"],"sourcesContent":["import { buildErrorThrower, ClerkRuntimeError } from './error';\nimport { createDevOrStagingUrlCache, parsePublishableKey } from './keys';\nimport { loadScript } from './loadScript';\nimport { isProxyUrlRelative, isValidProxyUrl, proxyUrlToAbsoluteURL } from './proxy';\nimport type { SDKMetadata } from './types';\nimport { addClerkPrefix } from './url';\nimport { versionSelector } from './versionSelector';\n\nconst { isDevOrStagingUrl } = createDevOrStagingUrlCache();\n\nconst errorThrower = buildErrorThrower({ packageName: '@clerk/shared' });\n\nexport type LoadClerkJSScriptOptions = {\n publishableKey: string;\n /** @internal */\n __internal_clerkJSUrl?: string;\n /** @internal */\n __internal_clerkJSVersion?: string;\n sdkMetadata?: SDKMetadata;\n proxyUrl?: string;\n domain?: string;\n nonce?: string;\n /**\n * Timeout in milliseconds to wait for clerk-js to load before considering it failed.\n *\n * @default 15000 (15 seconds)\n */\n scriptLoadTimeout?: number;\n};\n\n/**\n * @deprecated Use `LoadClerkJSScriptOptions` instead. This alias will be removed in a future major version.\n */\nexport type LoadClerkJsScriptOptions = LoadClerkJSScriptOptions;\n\nexport type LoadClerkUIScriptOptions = {\n publishableKey: string;\n /** @internal */\n __internal_clerkUIUrl?: string;\n /** @internal */\n __internal_clerkUIVersion?: string;\n proxyUrl?: string;\n domain?: string;\n nonce?: string;\n scriptLoadTimeout?: number;\n};\n\n/**\n * Validates that window.Clerk exists and is properly initialized.\n * This ensures we don't have false positives where the script loads but Clerk is malformed.\n *\n * @returns `true` if window.Clerk exists and has the expected structure with a load method.\n */\nfunction isClerkGlobalProperlyLoaded(prop: 'Clerk' | '__internal_ClerkUICtor'): boolean {\n if (typeof window === 'undefined' || !(window as any)[prop]) {\n return false;\n }\n\n // Basic validation that window.Clerk has the expected structure\n const val = (window as any)[prop];\n return !!val;\n}\nconst isClerkProperlyLoaded = () => isClerkGlobalProperlyLoaded('Clerk');\nconst isClerkUIProperlyLoaded = () => isClerkGlobalProperlyLoaded('__internal_ClerkUICtor');\n\n/**\n * Checks if an existing script has a request error using Performance API.\n *\n * @param scriptUrl - The URL of the script to check.\n * @returns True if the script has failed to load due to a network/HTTP error.\n */\nfunction hasScriptRequestError(scriptUrl: string): boolean {\n if (typeof window === 'undefined' || !window.performance) {\n return false;\n }\n\n const entries = performance.getEntriesByName(scriptUrl, 'resource') as PerformanceResourceTiming[];\n\n if (entries.length === 0) {\n return false;\n }\n\n const scriptEntry = entries[entries.length - 1];\n\n // transferSize === 0 with responseEnd === 0 indicates network failure\n // transferSize === 0 with responseEnd > 0 might be a 4xx/5xx error or blocked request\n if (scriptEntry.transferSize === 0 && scriptEntry.decodedBodySize === 0) {\n // If there was no response at all, it's definitely an error\n if (scriptEntry.responseEnd === 0) {\n return true;\n }\n // If we got a response but no content, likely an HTTP error (4xx/5xx)\n if (scriptEntry.responseEnd > 0 && scriptEntry.responseStart > 0) {\n return true;\n }\n\n if ('responseStatus' in scriptEntry) {\n const status = (scriptEntry as any).responseStatus;\n if (status >= 400) {\n return true;\n }\n if (scriptEntry.responseStatus === 0) {\n return true;\n }\n }\n }\n\n return false;\n}\n\n/**\n * Hotloads the Clerk JS script with robust failure detection.\n *\n * Uses a timeout-based approach to ensure absolute certainty about load success/failure.\n * If the script fails to load within the timeout period, or loads but doesn't create\n * a proper Clerk instance, the promise rejects with an error.\n *\n * @param opts - The options used to build the Clerk JS script URL and load the script.\n * Must include a `publishableKey` if no existing script is found.\n * @returns Promise that resolves with null if Clerk loads successfully, or rejects with an error.\n *\n * @example\n * ```typescript\n * try {\n * await loadClerkJsScript({ publishableKey: 'pk_test_...' });\n * console.log('Clerk loaded successfully');\n * } catch (error) {\n * console.error('Failed to load Clerk:', error.message);\n * }\n * ```\n */\nexport const loadClerkJSScript = async (opts?: LoadClerkJSScriptOptions): Promise<HTMLScriptElement | null> => {\n const timeout = opts?.scriptLoadTimeout ?? 15000;\n const rejectWith = (error?: Error) =>\n new ClerkRuntimeError('Failed to load Clerk JS' + (error?.message ? `, ${error.message}` : ''), {\n code: 'failed_to_load_clerk_js',\n cause: error,\n });\n\n if (isClerkProperlyLoaded()) {\n return null;\n }\n\n if (!opts?.publishableKey) {\n errorThrower.throwMissingPublishableKeyError();\n return null;\n }\n\n const scriptUrl = clerkJSScriptUrl(opts);\n const existingScript = document.querySelector<HTMLScriptElement>('script[data-clerk-js-script]');\n\n if (existingScript) {\n if (hasScriptRequestError(scriptUrl)) {\n existingScript.remove();\n } else {\n try {\n await waitForPredicateWithTimeout(timeout, isClerkProperlyLoaded, rejectWith(), existingScript);\n return null;\n } catch {\n existingScript.remove();\n }\n }\n }\n\n const loadPromise = waitForPredicateWithTimeout(timeout, isClerkProperlyLoaded, rejectWith());\n\n loadScript(scriptUrl, {\n async: true,\n crossOrigin: 'anonymous',\n nonce: opts.nonce,\n beforeLoad: applyAttributesToScript(buildClerkJSScriptAttributes(opts)),\n }).catch(error => {\n throw rejectWith(error);\n });\n\n return loadPromise;\n};\n\nexport const loadClerkUIScript = async (opts?: LoadClerkUIScriptOptions): Promise<HTMLScriptElement | null> => {\n const timeout = opts?.scriptLoadTimeout ?? 15000;\n const rejectWith = (error?: Error) =>\n new ClerkRuntimeError('Failed to load Clerk UI' + (error?.message ? `, ${error.message}` : ''), {\n code: 'failed_to_load_clerk_ui',\n cause: error,\n });\n\n if (isClerkUIProperlyLoaded()) {\n return null;\n }\n\n if (!opts?.publishableKey) {\n errorThrower.throwMissingPublishableKeyError();\n return null;\n }\n\n const scriptUrl = clerkUIScriptUrl(opts);\n const existingScript = document.querySelector<HTMLScriptElement>('script[data-clerk-ui-script]');\n\n if (existingScript) {\n if (hasScriptRequestError(scriptUrl)) {\n existingScript.remove();\n } else {\n try {\n await waitForPredicateWithTimeout(timeout, isClerkUIProperlyLoaded, rejectWith(), existingScript);\n return null;\n } catch {\n existingScript.remove();\n }\n }\n }\n\n const loadPromise = waitForPredicateWithTimeout(timeout, isClerkUIProperlyLoaded, rejectWith());\n\n loadScript(scriptUrl, {\n async: true,\n crossOrigin: 'anonymous',\n nonce: opts.nonce,\n beforeLoad: applyAttributesToScript(buildClerkUIScriptAttributes(opts)),\n }).catch(error => {\n throw rejectWith(error);\n });\n\n return loadPromise;\n};\n\nexport const clerkJSScriptUrl = (opts: LoadClerkJSScriptOptions) => {\n const { __internal_clerkJSUrl, __internal_clerkJSVersion, proxyUrl, domain, publishableKey } = opts;\n\n if (__internal_clerkJSUrl) {\n return __internal_clerkJSUrl;\n }\n\n const version = versionSelector(__internal_clerkJSVersion);\n\n if (proxyUrl && isProxyUrlRelative(proxyUrl)) {\n return buildRelativeProxyScriptUrl(proxyUrl, 'clerk-js', version, 'clerk.browser.js');\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\n return `https://${scriptHost}/npm/@clerk/clerk-js@${version}/dist/clerk.browser.js`;\n};\n\nexport const clerkUIScriptUrl = (opts: LoadClerkUIScriptOptions) => {\n const { __internal_clerkUIUrl, __internal_clerkUIVersion, proxyUrl, domain, publishableKey } = opts;\n\n if (__internal_clerkUIUrl) {\n return __internal_clerkUIUrl;\n }\n\n const version = versionSelector(__internal_clerkUIVersion, UI_PACKAGE_VERSION);\n\n if (proxyUrl && isProxyUrlRelative(proxyUrl)) {\n return buildRelativeProxyScriptUrl(proxyUrl, 'ui', version, 'ui.browser.js');\n }\n\n const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });\n return `https://${scriptHost}/npm/@clerk/ui@${version}/dist/ui.browser.js`;\n};\n\nexport const buildClerkJSScriptAttributes = (options: LoadClerkJSScriptOptions) => {\n const obj: Record<string, string> = {};\n\n if (options.publishableKey) {\n obj['data-clerk-publishable-key'] = options.publishableKey;\n }\n\n if (options.proxyUrl) {\n obj['data-clerk-proxy-url'] = options.proxyUrl;\n }\n\n if (options.domain) {\n obj['data-clerk-domain'] = options.domain;\n }\n\n if (options.nonce) {\n obj.nonce = options.nonce;\n }\n\n return obj;\n};\n\nexport const buildClerkUIScriptAttributes = (options: LoadClerkUIScriptOptions) => {\n // TODO @nikos do we need this?\n return buildClerkJSScriptAttributes(options);\n};\n\nconst applyAttributesToScript = (attributes: Record<string, string>) => (script: HTMLScriptElement) => {\n for (const attribute in attributes) {\n script.setAttribute(attribute, attributes[attribute]);\n }\n};\n\nconst stripTrailingSlashes = (value: string) => {\n while (value.endsWith('/')) {\n value = value.slice(0, -1);\n }\n\n return value;\n};\n\nconst buildRelativeProxyScriptUrl = (proxyUrl: string, packageName: string, version: string, fileName: string) => {\n return `${stripTrailingSlashes(proxyUrl)}/npm/@clerk/${packageName}@${version}/dist/${fileName}`;\n};\n\nexport const buildScriptHost = (opts: { publishableKey: string; proxyUrl?: string; domain?: string }) => {\n const { proxyUrl, domain, publishableKey } = opts;\n\n if (!!proxyUrl && isValidProxyUrl(proxyUrl)) {\n const resolvedProxyUrl = proxyUrlToAbsoluteURL(proxyUrl);\n\n if (isProxyUrlRelative(resolvedProxyUrl)) {\n return parsePublishableKey(publishableKey)?.frontendApi || '';\n }\n\n return resolvedProxyUrl.replace(/http(s)?:\\/\\//, '');\n } else if (domain && !isDevOrStagingUrl(parsePublishableKey(publishableKey)?.frontendApi || '')) {\n return addClerkPrefix(domain);\n } else {\n return parsePublishableKey(publishableKey)?.frontendApi || '';\n }\n};\n\nfunction waitForPredicateWithTimeout(\n timeoutMs: number,\n predicate: () => boolean,\n rejectWith: Error,\n existingScript?: HTMLScriptElement,\n): Promise<HTMLScriptElement | null> {\n return new Promise((resolve, reject) => {\n let resolved = false;\n\n const cleanup = (timeoutId: ReturnType<typeof setTimeout>, pollInterval: ReturnType<typeof setInterval>) => {\n clearTimeout(timeoutId);\n clearInterval(pollInterval);\n };\n\n // Bail out early if the script fails to load, instead of waiting for the entire timeout\n existingScript?.addEventListener('error', () => {\n cleanup(timeoutId, pollInterval);\n reject(rejectWith);\n });\n\n const checkAndResolve = () => {\n if (resolved) {\n return;\n }\n\n if (predicate()) {\n resolved = true;\n cleanup(timeoutId, pollInterval);\n resolve(null);\n }\n };\n\n const handleTimeout = () => {\n if (resolved) {\n return;\n }\n\n resolved = true;\n cleanup(timeoutId, pollInterval);\n\n if (!predicate()) {\n reject(rejectWith);\n } else {\n resolve(null);\n }\n };\n\n const timeoutId = setTimeout(handleTimeout, timeoutMs);\n\n checkAndResolve();\n\n const pollInterval = setInterval(() => {\n if (resolved) {\n clearInterval(pollInterval);\n return;\n }\n checkAndResolve();\n }, 100);\n });\n}\n\nexport function setClerkJSLoadingErrorPackageName(packageName: string) {\n errorThrower.setPackageName({ packageName });\n}\n\n/**\n * @deprecated Use `loadClerkJSScript` instead. This alias will be removed in a future major version.\n */\nexport const loadClerkJsScript = loadClerkJSScript;\n\n/**\n * @deprecated Use `clerkJSScriptUrl` instead. This alias will be removed in a future major version.\n */\nexport const clerkJsScriptUrl = clerkJSScriptUrl;\n\n/**\n * @deprecated Use `buildClerkJSScriptAttributes` instead. This alias will be removed in a future major version.\n */\nexport const buildClerkJsScriptAttributes = buildClerkJSScriptAttributes;\n\n/**\n * @deprecated Use `setClerkJSLoadingErrorPackageName` instead. This alias will be removed in a future major version.\n */\nexport const setClerkJsLoadingErrorPackageName = setClerkJSLoadingErrorPackageName;\n"],"mappings":";;;;;;;;;AAQA,MAAM,EAAE,sBAAsB,2BAA2B;AAEzD,MAAM,eAAe,kBAAkB,EAAE,aAAa,gBAAgB,CAAC;;;;;;;AA2CvE,SAAS,4BAA4B,MAAmD;CACtF,IAAI,OAAO,WAAW,eAAe,CAAE,OAAe,OACpD,OAAO;CAKT,OAAO,CAAC,CADK,OAAe;AAE9B;AACA,MAAM,8BAA8B,4BAA4B,OAAO;AACvE,MAAM,gCAAgC,4BAA4B,wBAAwB;;;;;;;AAQ1F,SAAS,sBAAsB,WAA4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eAAe,MAAM;MAE5B,OAAO,oBAAoB,cAAc,CAAC,EAAE,eAAe;AAE/D;AAEA,SAAS,4BACP,WACA,WACA,YACA,gBACmC;CACnC,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,IAAI,WAAW;EAEf,MAAM,WAAW,WAA0C,iBAAiD;GAC1G,aAAa,SAAS;GACtB,cAAc,YAAY;EAC5B;EAGA,gBAAgB,iBAAiB,eAAe;GAC9C,QAAQ,WAAW,YAAY;GAC/B,OAAO,UAAU;EACnB,CAAC;EAED,MAAM,wBAAwB;GAC5B,IAAI,UACF;GAGF,IAAI,UAAU,GAAG;IACf,WAAW;IACX,QAAQ,WAAW,YAAY;IAC/B,QAAQ,IAAI;GACd;EACF;EAEA,MAAM,sBAAsB;GAC1B,IAAI,UACF;GAGF,WAAW;GACX,QAAQ,WAAW,YAAY;GAE/B,IAAI,CAAC,UAAU,GACb,OAAO,UAAU;QAEjB,QAAQ,IAAI;EAEhB;EAEA,MAAM,YAAY,WAAW,eAAe,SAAS;EAErD,gBAAgB;EAEhB,MAAM,eAAe,kBAAkB;GACrC,IAAI,UAAU;IACZ,cAAc,YAAY;IAC1B;GACF;GACA,gBAAgB;EAClB,GAAG,GAAG;CACR,CAAC;AACH;AAEA,SAAgB,kCAAkC,aAAqB;CACrE,aAAa,eAAe,EAAE,YAAY,CAAC;AAC7C;;;;AAKA,MAAa,oBAAoB;;;;AAKjC,MAAa,mBAAmB;;;;AAKhC,MAAa,+BAA+B;;;;AAK5C,MAAa,oCAAoC"}
|
|
@@ -30,6 +30,8 @@ import { usePaymentAttemptQuery } from "./usePaymentAttemptQuery.mjs";
|
|
|
30
30
|
import { UseUserEnterpriseConnectionsParams, UseUserEnterpriseConnectionsReturn, useUserEnterpriseConnections } from "./useUserEnterpriseConnections.mjs";
|
|
31
31
|
import { UseOrganizationEnterpriseConnectionsParams, UseOrganizationEnterpriseConnectionsReturn, useOrganizationEnterpriseConnections } from "./useOrganizationEnterpriseConnections.mjs";
|
|
32
32
|
import { UseOrganizationDomainsParams, UseOrganizationDomainsReturn, useOrganizationDomains } from "./useOrganizationDomains.mjs";
|
|
33
|
+
import { UseOrganizationDirectorySyncParams, UseOrganizationDirectorySyncReturn, useOrganizationDirectorySync } from "./useOrganizationDirectorySync.mjs";
|
|
34
|
+
import { UseOrganizationDirectorySyncUsersParams, UseOrganizationDirectorySyncUsersReturn, useOrganizationDirectorySyncUsers } from "./useOrganizationDirectorySyncUsers.mjs";
|
|
33
35
|
import { UseOrganizationEnterpriseConnectionTestRunsParams, UseOrganizationEnterpriseConnectionTestRunsReturn, UseOrganizationEnterpriseConnectionTestRunsRevalidateResult, useOrganizationEnterpriseConnectionTestRuns } from "./useOrganizationEnterpriseConnectionTestRuns.mjs";
|
|
34
36
|
import { useUserBase } from "./base/useUserBase.mjs";
|
|
35
37
|
import { useClientBase } from "./base/useClientBase.mjs";
|
|
@@ -30,6 +30,8 @@ import { usePaymentAttemptQuery } from "./usePaymentAttemptQuery.js";
|
|
|
30
30
|
import { UseUserEnterpriseConnectionsParams, UseUserEnterpriseConnectionsReturn, useUserEnterpriseConnections } from "./useUserEnterpriseConnections.js";
|
|
31
31
|
import { UseOrganizationEnterpriseConnectionsParams, UseOrganizationEnterpriseConnectionsReturn, useOrganizationEnterpriseConnections } from "./useOrganizationEnterpriseConnections.js";
|
|
32
32
|
import { UseOrganizationDomainsParams, UseOrganizationDomainsReturn, useOrganizationDomains } from "./useOrganizationDomains.js";
|
|
33
|
+
import { UseOrganizationDirectorySyncParams, UseOrganizationDirectorySyncReturn, useOrganizationDirectorySync } from "./useOrganizationDirectorySync.js";
|
|
34
|
+
import { UseOrganizationDirectorySyncUsersParams, UseOrganizationDirectorySyncUsersReturn, useOrganizationDirectorySyncUsers } from "./useOrganizationDirectorySyncUsers.js";
|
|
33
35
|
import { UseOrganizationEnterpriseConnectionTestRunsParams, UseOrganizationEnterpriseConnectionTestRunsReturn, UseOrganizationEnterpriseConnectionTestRunsRevalidateResult, useOrganizationEnterpriseConnectionTestRuns } from "./useOrganizationEnterpriseConnectionTestRuns.js";
|
|
34
36
|
import { useUserBase } from "./base/useUserBase.js";
|
|
35
37
|
import { useClientBase } from "./base/useClientBase.js";
|
|
@@ -31,4 +31,6 @@ const require_usePaymentAttemptQuery = require('./usePaymentAttemptQuery.js');
|
|
|
31
31
|
const require_useUserEnterpriseConnections = require('./useUserEnterpriseConnections.js');
|
|
32
32
|
const require_useOrganizationEnterpriseConnections = require('./useOrganizationEnterpriseConnections.js');
|
|
33
33
|
const require_useOrganizationDomains = require('./useOrganizationDomains.js');
|
|
34
|
+
const require_useOrganizationDirectorySync = require('./useOrganizationDirectorySync.js');
|
|
35
|
+
const require_useOrganizationDirectorySyncUsers = require('./useOrganizationDirectorySyncUsers.js');
|
|
34
36
|
const require_useOrganizationEnterpriseConnectionTestRuns = require('./useOrganizationEnterpriseConnectionTestRuns.js');
|
|
@@ -12,7 +12,7 @@ import { LoadedClerk } from "../../types/clerk.mjs";
|
|
|
12
12
|
*
|
|
13
13
|
* @example
|
|
14
14
|
*
|
|
15
|
-
* 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#
|
|
15
|
+
* 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.
|
|
16
16
|
*
|
|
17
17
|
* <Tabs items='React,Next.js'>
|
|
18
18
|
* <Tab>
|
|
@@ -12,7 +12,7 @@ import { LoadedClerk } from "../../types/clerk.js";
|
|
|
12
12
|
*
|
|
13
13
|
* @example
|
|
14
14
|
*
|
|
15
|
-
* 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#
|
|
15
|
+
* 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.
|
|
16
16
|
*
|
|
17
17
|
* <Tabs items='React,Next.js'>
|
|
18
18
|
* <Tab>
|
|
@@ -13,7 +13,7 @@ const require_contexts = require('../contexts.js');
|
|
|
13
13
|
*
|
|
14
14
|
* @example
|
|
15
15
|
*
|
|
16
|
-
* 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#
|
|
16
|
+
* 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.
|
|
17
17
|
*
|
|
18
18
|
* <Tabs items='React,Next.js'>
|
|
19
19
|
* <Tab>
|