@clerk/testing 2.0.0-snapshot.v07d9254

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Clerk, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,108 @@
1
+ <p align="center">
2
+ <a href="https://clerk.com?utm_source=github&utm_medium=clerk_testing" target="_blank" rel="noopener noreferrer">
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="https://images.clerk.com/static/logo-dark-mode-400x400.png">
5
+ <img src="https://images.clerk.com/static/logo-light-mode-400x400.png" height="64">
6
+ </picture>
7
+ </a>
8
+ <br />
9
+ </p>
10
+
11
+ # @clerk/testing
12
+
13
+ <div align="center">
14
+
15
+ [![Chat on Discord](https://img.shields.io/discord/856971667393609759.svg?logo=discord)](https://clerk.com/discord)
16
+ [![Clerk documentation](https://img.shields.io/badge/documentation-clerk-green.svg)](https://clerk.com/docs?utm_source=github&utm_medium=clerk_testing)
17
+ [![Follow on Twitter](https://img.shields.io/twitter/follow/ClerkDev?style=social)](https://twitter.com/intent/follow?screen_name=ClerkDev)
18
+
19
+ [Changelog](https://github.com/clerk/javascript/blob/main/packages/testing/CHANGELOG.md)
20
+ ·
21
+ [Report a Bug](https://github.com/clerk/javascript/issues/new?assignees=&labels=needs-triage&projects=&template=BUG_REPORT.yml)
22
+ ·
23
+ [Request a Feature](https://feedback.clerk.com/roadmap)
24
+ ·
25
+ [Ask a Question](https://github.com/clerk/javascript/discussions)
26
+
27
+ </div>
28
+
29
+ ---
30
+
31
+ ## Overview
32
+
33
+ This package provides utilities for testing Clerk applications.
34
+
35
+ It currently supports the following testing frameworks:
36
+
37
+ - [Playwright](https://playwright.dev/), a Node.js library to automate browsers and web pages.
38
+
39
+ ## Getting started
40
+
41
+ ### Prerequisites
42
+
43
+ - Node.js `>=18.17.0` or later
44
+ - Playwright v1+
45
+
46
+ ### Installation
47
+
48
+ ```shell
49
+ npm install @clerk/testing --save-dev
50
+ ```
51
+
52
+ ## Usage
53
+
54
+ ### Playwright
55
+
56
+ On your global setup file for Playwright, you must use the `clerkSetup` function to set up Clerk for your tests.
57
+
58
+ ```typescript
59
+ // global-setup.ts
60
+ import { clerkSetup } from '@clerk/testing/playwright';
61
+ import { test as setup } from '@playwright/test';
62
+
63
+ setup('global setup', async ({ }) => {
64
+ await clerkSetup();
65
+ ...
66
+ });
67
+ ```
68
+
69
+ Then, you can use the `setupClerkTestingToken` function to bypass bot protection on your tests.
70
+
71
+ ```typescript
72
+ // my-test.spec.ts
73
+ import { setupClerkTestingToken } from "@clerk/testing/playwright";
74
+ import { test } from "@playwright/test";
75
+
76
+ test("sign up", async ({ page }) => {
77
+ await setupClerkTestingToken({ page });
78
+
79
+ await page.goto("/sign-up");
80
+ ...
81
+ });
82
+ ```
83
+
84
+ ## Support
85
+
86
+ You can get in touch with us in any of the following ways:
87
+
88
+ - Join our official community [Discord server](https://clerk.com/discord)
89
+ - Create a [GitHub Discussion](https://github.com/clerk/javascript/discussions)
90
+ - Contact options listed on [our Support page](https://clerk.com/support?utm_source=github&utm_medium=clerk_testing)
91
+
92
+ ## Contributing
93
+
94
+ We're open to all community contributions! If you'd like to contribute in any way, please read [our contribution guidelines](https://github.com/clerk/javascript/blob/main/docs/CONTRIBUTING.md).
95
+
96
+ ## Security
97
+
98
+ `@clerk/testing` follows good practices of security, but 100% security cannot be assured.
99
+
100
+ `@clerk/testing` is provided **"as is"** without any **warranty**. Use at your own risk.
101
+
102
+ _For more information and to report security issues, please refer to our [security documentation](https://github.com/clerk/javascript/blob/main/docs/SECURITY.md)._
103
+
104
+ ## License
105
+
106
+ This project is licensed under the **MIT license**.
107
+
108
+ See [LICENSE](https://github.com/clerk/javascript/blob/main/packages/testing/LICENSE) for more information.
@@ -0,0 +1,2 @@
1
+ import{isProductionFromSecretKey as c,parsePublishableKey as a}from"@clerk/shared/keys";import _ from"dotenv";var l="https://api.clerk.com/v1/testing_tokens",K=async r=>{let p=n=>{r?.debug&&console.log(`Clerk: ${n}`)};p("Setting up Clerk..."),_.config({path:[".env.local",".env"]});let o=r?.publishableKey||process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY||process.env.VITE_CLERK_PUBLISHABLE_KEY||process.env.CLERK_PUBLISHABLE_KEY||process.env.GATSBY_CLERK_PUBLISHABLE_KEY||process.env.REACT_APP_CLERK_PUBLISHABLE_KEY||process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY,e=process.env.CLERK_SECRET_KEY,t=process.env.CLERK_TESTING_TOKEN;if(!o)throw new Error("You need to set the CLERK_PUBLISHABLE_KEY environment variable.");if(!e&&!t)throw new Error("You need to set the CLERK_SECRET_KEY or the CLERK_TESTING_KEY environment variable.");if(e&&!t){if(c(e))throw new Error("You are using a secret key from a production instance, but this helper only works for development instances.");let n={method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}};p("Fetching testing token from Clerk Backend API...");let s=process.env.CLERK_API_URL,E=s?`${s}/v1/testing_tokens`:l;await fetch(E,n).then(i=>i.json()).then(i=>{t=i.token}).catch(i=>{throw new Error("Failed to fetch testing token from Clerk API. Error: "+i)})}process.env.CLERK_FAPI=r?.frontendApiUrl||a(o)?.frontendApi,process.env.CLERK_TESTING_TOKEN=t};var L="__clerk_testing_token",T=async({page:r,options:p})=>{let o=p?.frontendApiUrl||process.env.CLERK_FAPI;if(!o)throw new Error("The Frontend API URL is required to bypass bot protection.");let e=`https://${o}/v1/**/*`;await r.route(e,(t,n)=>{let s=new URL(n.url()),E=process.env.CLERK_TESTING_TOKEN;E&&s.searchParams.set(L,E),t.continue({url:s.toString()})})};export{K as clerkSetup,T as setupClerkTestingToken};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/playwright/setup.ts","../../src/playwright/setupClerkTestingToken.ts"],"sourcesContent":["import { isProductionFromSecretKey, parsePublishableKey } from '@clerk/shared/keys';\nimport dotenv from 'dotenv';\n\ntype ClerkSetupParams = {\n /*\n * The publishable key for your Clerk dev instance.\n * If not provided, the library will look for the key in the following environment variables:\n * - NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY\n * - VITE_CLERK_PUBLISHABLE_KEY\n * - CLERK_PUBLISHABLE_KEY\n * - GATSBY_CLERK_PUBLISHABLE_KEY\n * - REACT_APP_CLERK_PUBLISHABLE_KEY\n * - EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY\n */\n publishableKey?: string;\n /*\n * The frontend API URL for your Clerk dev instance, without the protocol.\n * If provided, it overrides the Frontend API URL parsed from the publishable key.\n * Example: 'relieved-chamois-66.clerk.accounts.dev'\n */\n frontendApiUrl?: string;\n /*\n * Enable debug mode.\n */\n debug?: boolean;\n};\n\nconst TESTING_TOKEN_API_URL = 'https://api.clerk.com/v1/testing_tokens';\n\n/**\n * Sets up Clerk for testing by fetching the testing token from the Clerk Backend API.\n *\n * @param options.publishableKey - The publishable key for your Clerk dev instance.\n * @param options.frontendApiUrl - The frontend API URL for your Clerk dev instance, without the protocol. It overrides the Frontend API URL parsed from the publishable key.\n * @param options.debug - Enable debug logs.\n * @returns A promise that resolves when Clerk is set up.\n *\n * @throws An error if the publishable key or the secret key is not provided.\n * @throws An error if the secret key is from a production instance.\n * @throws An error if the testing token cannot be fetched from the Clerk Backend API.\n */\nexport const clerkSetup = async (options?: ClerkSetupParams) => {\n const log = (msg: string) => {\n if (options?.debug) {\n console.log(`Clerk: ${msg}`);\n }\n };\n\n log('Setting up Clerk...');\n dotenv.config({ path: ['.env.local', '.env'] });\n\n const publishableKey =\n options?.publishableKey ||\n process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY ||\n process.env.VITE_CLERK_PUBLISHABLE_KEY ||\n process.env.CLERK_PUBLISHABLE_KEY ||\n process.env.GATSBY_CLERK_PUBLISHABLE_KEY ||\n process.env.REACT_APP_CLERK_PUBLISHABLE_KEY ||\n process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY;\n\n const secretKey = process.env.CLERK_SECRET_KEY;\n let testingToken = process.env.CLERK_TESTING_TOKEN;\n\n if (!publishableKey) {\n throw new Error('You need to set the CLERK_PUBLISHABLE_KEY environment variable.');\n }\n\n if (!secretKey && !testingToken) {\n throw new Error('You need to set the CLERK_SECRET_KEY or the CLERK_TESTING_KEY environment variable.');\n }\n\n if (secretKey && !testingToken) {\n if (isProductionFromSecretKey(secretKey)) {\n throw new Error(\n 'You are using a secret key from a production instance, but this helper only works for development instances.',\n );\n }\n\n const options = {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${secretKey}`,\n 'Content-Type': 'application/json',\n },\n };\n\n log('Fetching testing token from Clerk Backend API...');\n\n const apiUrl = process.env.CLERK_API_URL;\n const testingTokenApiUrl = apiUrl ? `${apiUrl}/v1/testing_tokens` : TESTING_TOKEN_API_URL;\n\n await fetch(testingTokenApiUrl, options)\n .then(response => {\n return response.json();\n })\n .then(data => {\n testingToken = data.token;\n })\n .catch(reason => {\n throw new Error('Failed to fetch testing token from Clerk API. Error: ' + reason);\n });\n }\n\n process.env.CLERK_FAPI = options?.frontendApiUrl || parsePublishableKey(publishableKey)?.frontendApi;\n process.env.CLERK_TESTING_TOKEN = testingToken;\n};\n","import type { Page } from '@playwright/test';\n\ntype BypassBotProtectionParams = {\n page: Page;\n options?: {\n /*\n * The frontend API URL for your Clerk dev instance, without the protocol.\n * If provided, it overrides the Frontend API URL parsed from the publishable key.\n * Example: 'relieved-chamois-66.clerk.accounts.dev'\n */\n frontendApiUrl?: string;\n };\n};\n\nconst TESTING_TOKEN_PARAM = '__clerk_testing_token';\n\n/**\n * Bypasses bot protection by appending the testing token in the Frontend API requests.\n *\n * @param params.page - The Playwright page object.\n * @param params.options.frontendApiUrl - The frontend API URL for your Clerk dev instance, without the protocol.\n * @returns A promise that resolves when the bot protection bypass is set up.\n * @throws An error if the Frontend API URL is not provided.\n * @example\n * ```ts\n * import { setupClerkTestingToken } from '@clerk/testing/playwright';\n *\n * test('should bypass bot protection', async ({ page }) => {\n * await setupClerkTestingToken({ page });\n * await page.goto('https://your-app.com');\n * // Continue with your test...\n * });\n * ```\n *\n */\nexport const setupClerkTestingToken = async ({ page, options }: BypassBotProtectionParams) => {\n const fapiUrl = options?.frontendApiUrl || process.env.CLERK_FAPI;\n if (!fapiUrl) {\n throw new Error('The Frontend API URL is required to bypass bot protection.');\n }\n const apiUrl = `https://${fapiUrl}/v1/**/*`;\n\n await page.route(apiUrl, (route, request) => {\n const originalUrl = new URL(request.url());\n const testingToken = process.env.CLERK_TESTING_TOKEN;\n\n if (testingToken) {\n originalUrl.searchParams.set(TESTING_TOKEN_PARAM, testingToken);\n }\n\n route.continue({\n url: originalUrl.toString(),\n });\n });\n};\n"],"mappings":"AAAA,OAAS,6BAAAA,EAA2B,uBAAAC,MAA2B,qBAC/D,OAAOC,MAAY,SA0BnB,IAAMC,EAAwB,0CAcjBC,EAAa,MAAOC,GAA+B,CAC9D,IAAMC,EAAOC,GAAgB,CACvBF,GAAS,OACX,QAAQ,IAAI,UAAUE,CAAG,EAAE,CAE/B,EAEAD,EAAI,qBAAqB,EACzBJ,EAAO,OAAO,CAAE,KAAM,CAAC,aAAc,MAAM,CAAE,CAAC,EAE9C,IAAMM,EACJH,GAAS,gBACT,QAAQ,IAAI,mCACZ,QAAQ,IAAI,4BACZ,QAAQ,IAAI,uBACZ,QAAQ,IAAI,8BACZ,QAAQ,IAAI,iCACZ,QAAQ,IAAI,kCAERI,EAAY,QAAQ,IAAI,iBAC1BC,EAAe,QAAQ,IAAI,oBAE/B,GAAI,CAACF,EACH,MAAM,IAAI,MAAM,iEAAiE,EAGnF,GAAI,CAACC,GAAa,CAACC,EACjB,MAAM,IAAI,MAAM,qFAAqF,EAGvG,GAAID,GAAa,CAACC,EAAc,CAC9B,GAAIV,EAA0BS,CAAS,EACrC,MAAM,IAAI,MACR,8GACF,EAGF,IAAMJ,EAAU,CACd,OAAQ,OACR,QAAS,CACP,cAAe,UAAUI,CAAS,GAClC,eAAgB,kBAClB,CACF,EAEAH,EAAI,kDAAkD,EAEtD,IAAMK,EAAS,QAAQ,IAAI,cACrBC,EAAqBD,EAAS,GAAGA,CAAM,qBAAuBR,EAEpE,MAAM,MAAMS,EAAoBP,CAAO,EACpC,KAAKQ,GACGA,EAAS,KAAK,CACtB,EACA,KAAKC,GAAQ,CACZJ,EAAeI,EAAK,KACtB,CAAC,EACA,MAAMC,GAAU,CACf,MAAM,IAAI,MAAM,wDAA0DA,CAAM,CAClF,CAAC,CACL,CAEA,QAAQ,IAAI,WAAaV,GAAS,gBAAkBJ,EAAoBO,CAAc,GAAG,YACzF,QAAQ,IAAI,oBAAsBE,CACpC,EC3FA,IAAMM,EAAsB,wBAqBfC,EAAyB,MAAO,CAAE,KAAAC,EAAM,QAAAC,CAAQ,IAAiC,CAC5F,IAAMC,EAAUD,GAAS,gBAAkB,QAAQ,IAAI,WACvD,GAAI,CAACC,EACH,MAAM,IAAI,MAAM,4DAA4D,EAE9E,IAAMC,EAAS,WAAWD,CAAO,WAEjC,MAAMF,EAAK,MAAMG,EAAQ,CAACC,EAAOC,IAAY,CAC3C,IAAMC,EAAc,IAAI,IAAID,EAAQ,IAAI,CAAC,EACnCE,EAAe,QAAQ,IAAI,oBAE7BA,GACFD,EAAY,aAAa,IAAIR,EAAqBS,CAAY,EAGhEH,EAAM,SAAS,CACb,IAAKE,EAAY,SAAS,CAC5B,CAAC,CACH,CAAC,CACH","names":["isProductionFromSecretKey","parsePublishableKey","dotenv","TESTING_TOKEN_API_URL","clerkSetup","options","log","msg","publishableKey","secretKey","testingToken","apiUrl","testingTokenApiUrl","response","data","reason","TESTING_TOKEN_PARAM","setupClerkTestingToken","page","options","fapiUrl","apiUrl","route","request","originalUrl","testingToken"]}
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";var T=Object.create;var c=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var h=Object.getPrototypeOf,g=Object.prototype.hasOwnProperty;var u=(e,t)=>{for(var r in t)c(e,r,{get:t[r],enumerable:!0})},_=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of C(t))!g.call(e,o)&&o!==r&&c(e,o,{get:()=>t[o],enumerable:!(n=P(t,o))||n.enumerable});return e};var k=(e,t,r)=>(r=e!=null?T(h(e)):{},_(t||!e||!e.__esModule?c(r,"default",{value:e,enumerable:!0}):r,e)),A=e=>_(c({},"__esModule",{value:!0}),e);var R={};u(R,{clerkSetup:()=>K,setupClerkTestingToken:()=>L});module.exports=A(R);var a=require("@clerk/shared/keys"),l=k(require("dotenv")),f="https://api.clerk.com/v1/testing_tokens",K=async e=>{let t=s=>{e?.debug&&console.log(`Clerk: ${s}`)};t("Setting up Clerk..."),l.default.config({path:[".env.local",".env"]});let r=e?.publishableKey||process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY||process.env.VITE_CLERK_PUBLISHABLE_KEY||process.env.CLERK_PUBLISHABLE_KEY||process.env.GATSBY_CLERK_PUBLISHABLE_KEY||process.env.REACT_APP_CLERK_PUBLISHABLE_KEY||process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY,n=process.env.CLERK_SECRET_KEY,o=process.env.CLERK_TESTING_TOKEN;if(!r)throw new Error("You need to set the CLERK_PUBLISHABLE_KEY environment variable.");if(!n&&!o)throw new Error("You need to set the CLERK_SECRET_KEY or the CLERK_TESTING_KEY environment variable.");if(n&&!o){if((0,a.isProductionFromSecretKey)(n))throw new Error("You are using a secret key from a production instance, but this helper only works for development instances.");let s={method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}};t("Fetching testing token from Clerk Backend API...");let i=process.env.CLERK_API_URL,E=i?`${i}/v1/testing_tokens`:f;await fetch(E,s).then(p=>p.json()).then(p=>{o=p.token}).catch(p=>{throw new Error("Failed to fetch testing token from Clerk API. Error: "+p)})}process.env.CLERK_FAPI=e?.frontendApiUrl||(0,a.parsePublishableKey)(r)?.frontendApi,process.env.CLERK_TESTING_TOKEN=o};var v="__clerk_testing_token",L=async({page:e,options:t})=>{let r=t?.frontendApiUrl||process.env.CLERK_FAPI;if(!r)throw new Error("The Frontend API URL is required to bypass bot protection.");let n=`https://${r}/v1/**/*`;await e.route(n,(o,s)=>{let i=new URL(s.url()),E=process.env.CLERK_TESTING_TOKEN;E&&i.searchParams.set(v,E),o.continue({url:i.toString()})})};0&&(module.exports={clerkSetup,setupClerkTestingToken});
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/playwright/index.ts","../src/playwright/setup.ts","../src/playwright/setupClerkTestingToken.ts"],"sourcesContent":["export { clerkSetup } from './setup';\nexport { setupClerkTestingToken } from './setupClerkTestingToken';\n","import { isProductionFromSecretKey, parsePublishableKey } from '@clerk/shared/keys';\nimport dotenv from 'dotenv';\n\ntype ClerkSetupParams = {\n /*\n * The publishable key for your Clerk dev instance.\n * If not provided, the library will look for the key in the following environment variables:\n * - NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY\n * - VITE_CLERK_PUBLISHABLE_KEY\n * - CLERK_PUBLISHABLE_KEY\n * - GATSBY_CLERK_PUBLISHABLE_KEY\n * - REACT_APP_CLERK_PUBLISHABLE_KEY\n * - EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY\n */\n publishableKey?: string;\n /*\n * The frontend API URL for your Clerk dev instance, without the protocol.\n * If provided, it overrides the Frontend API URL parsed from the publishable key.\n * Example: 'relieved-chamois-66.clerk.accounts.dev'\n */\n frontendApiUrl?: string;\n /*\n * Enable debug mode.\n */\n debug?: boolean;\n};\n\nconst TESTING_TOKEN_API_URL = 'https://api.clerk.com/v1/testing_tokens';\n\n/**\n * Sets up Clerk for testing by fetching the testing token from the Clerk Backend API.\n *\n * @param options.publishableKey - The publishable key for your Clerk dev instance.\n * @param options.frontendApiUrl - The frontend API URL for your Clerk dev instance, without the protocol. It overrides the Frontend API URL parsed from the publishable key.\n * @param options.debug - Enable debug logs.\n * @returns A promise that resolves when Clerk is set up.\n *\n * @throws An error if the publishable key or the secret key is not provided.\n * @throws An error if the secret key is from a production instance.\n * @throws An error if the testing token cannot be fetched from the Clerk Backend API.\n */\nexport const clerkSetup = async (options?: ClerkSetupParams) => {\n const log = (msg: string) => {\n if (options?.debug) {\n console.log(`Clerk: ${msg}`);\n }\n };\n\n log('Setting up Clerk...');\n dotenv.config({ path: ['.env.local', '.env'] });\n\n const publishableKey =\n options?.publishableKey ||\n process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY ||\n process.env.VITE_CLERK_PUBLISHABLE_KEY ||\n process.env.CLERK_PUBLISHABLE_KEY ||\n process.env.GATSBY_CLERK_PUBLISHABLE_KEY ||\n process.env.REACT_APP_CLERK_PUBLISHABLE_KEY ||\n process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY;\n\n const secretKey = process.env.CLERK_SECRET_KEY;\n let testingToken = process.env.CLERK_TESTING_TOKEN;\n\n if (!publishableKey) {\n throw new Error('You need to set the CLERK_PUBLISHABLE_KEY environment variable.');\n }\n\n if (!secretKey && !testingToken) {\n throw new Error('You need to set the CLERK_SECRET_KEY or the CLERK_TESTING_KEY environment variable.');\n }\n\n if (secretKey && !testingToken) {\n if (isProductionFromSecretKey(secretKey)) {\n throw new Error(\n 'You are using a secret key from a production instance, but this helper only works for development instances.',\n );\n }\n\n const options = {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${secretKey}`,\n 'Content-Type': 'application/json',\n },\n };\n\n log('Fetching testing token from Clerk Backend API...');\n\n const apiUrl = process.env.CLERK_API_URL;\n const testingTokenApiUrl = apiUrl ? `${apiUrl}/v1/testing_tokens` : TESTING_TOKEN_API_URL;\n\n await fetch(testingTokenApiUrl, options)\n .then(response => {\n return response.json();\n })\n .then(data => {\n testingToken = data.token;\n })\n .catch(reason => {\n throw new Error('Failed to fetch testing token from Clerk API. Error: ' + reason);\n });\n }\n\n process.env.CLERK_FAPI = options?.frontendApiUrl || parsePublishableKey(publishableKey)?.frontendApi;\n process.env.CLERK_TESTING_TOKEN = testingToken;\n};\n","import type { Page } from '@playwright/test';\n\ntype BypassBotProtectionParams = {\n page: Page;\n options?: {\n /*\n * The frontend API URL for your Clerk dev instance, without the protocol.\n * If provided, it overrides the Frontend API URL parsed from the publishable key.\n * Example: 'relieved-chamois-66.clerk.accounts.dev'\n */\n frontendApiUrl?: string;\n };\n};\n\nconst TESTING_TOKEN_PARAM = '__clerk_testing_token';\n\n/**\n * Bypasses bot protection by appending the testing token in the Frontend API requests.\n *\n * @param params.page - The Playwright page object.\n * @param params.options.frontendApiUrl - The frontend API URL for your Clerk dev instance, without the protocol.\n * @returns A promise that resolves when the bot protection bypass is set up.\n * @throws An error if the Frontend API URL is not provided.\n * @example\n * ```ts\n * import { setupClerkTestingToken } from '@clerk/testing/playwright';\n *\n * test('should bypass bot protection', async ({ page }) => {\n * await setupClerkTestingToken({ page });\n * await page.goto('https://your-app.com');\n * // Continue with your test...\n * });\n * ```\n *\n */\nexport const setupClerkTestingToken = async ({ page, options }: BypassBotProtectionParams) => {\n const fapiUrl = options?.frontendApiUrl || process.env.CLERK_FAPI;\n if (!fapiUrl) {\n throw new Error('The Frontend API URL is required to bypass bot protection.');\n }\n const apiUrl = `https://${fapiUrl}/v1/**/*`;\n\n await page.route(apiUrl, (route, request) => {\n const originalUrl = new URL(request.url());\n const testingToken = process.env.CLERK_TESTING_TOKEN;\n\n if (testingToken) {\n originalUrl.searchParams.set(TESTING_TOKEN_PARAM, testingToken);\n }\n\n route.continue({\n url: originalUrl.toString(),\n });\n });\n};\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gBAAAE,EAAA,2BAAAC,IAAA,eAAAC,EAAAJ,GCAA,IAAAK,EAA+D,8BAC/DC,EAAmB,qBA0BbC,EAAwB,0CAcjBC,EAAa,MAAOC,GAA+B,CAC9D,IAAMC,EAAOC,GAAgB,CACvBF,GAAS,OACX,QAAQ,IAAI,UAAUE,CAAG,EAAE,CAE/B,EAEAD,EAAI,qBAAqB,EACzB,EAAAE,QAAO,OAAO,CAAE,KAAM,CAAC,aAAc,MAAM,CAAE,CAAC,EAE9C,IAAMC,EACJJ,GAAS,gBACT,QAAQ,IAAI,mCACZ,QAAQ,IAAI,4BACZ,QAAQ,IAAI,uBACZ,QAAQ,IAAI,8BACZ,QAAQ,IAAI,iCACZ,QAAQ,IAAI,kCAERK,EAAY,QAAQ,IAAI,iBAC1BC,EAAe,QAAQ,IAAI,oBAE/B,GAAI,CAACF,EACH,MAAM,IAAI,MAAM,iEAAiE,EAGnF,GAAI,CAACC,GAAa,CAACC,EACjB,MAAM,IAAI,MAAM,qFAAqF,EAGvG,GAAID,GAAa,CAACC,EAAc,CAC9B,MAAI,6BAA0BD,CAAS,EACrC,MAAM,IAAI,MACR,8GACF,EAGF,IAAML,EAAU,CACd,OAAQ,OACR,QAAS,CACP,cAAe,UAAUK,CAAS,GAClC,eAAgB,kBAClB,CACF,EAEAJ,EAAI,kDAAkD,EAEtD,IAAMM,EAAS,QAAQ,IAAI,cACrBC,EAAqBD,EAAS,GAAGA,CAAM,qBAAuBT,EAEpE,MAAM,MAAMU,EAAoBR,CAAO,EACpC,KAAKS,GACGA,EAAS,KAAK,CACtB,EACA,KAAKC,GAAQ,CACZJ,EAAeI,EAAK,KACtB,CAAC,EACA,MAAMC,GAAU,CACf,MAAM,IAAI,MAAM,wDAA0DA,CAAM,CAClF,CAAC,CACL,CAEA,QAAQ,IAAI,WAAaX,GAAS,mBAAkB,uBAAoBI,CAAc,GAAG,YACzF,QAAQ,IAAI,oBAAsBE,CACpC,EC3FA,IAAMM,EAAsB,wBAqBfC,EAAyB,MAAO,CAAE,KAAAC,EAAM,QAAAC,CAAQ,IAAiC,CAC5F,IAAMC,EAAUD,GAAS,gBAAkB,QAAQ,IAAI,WACvD,GAAI,CAACC,EACH,MAAM,IAAI,MAAM,4DAA4D,EAE9E,IAAMC,EAAS,WAAWD,CAAO,WAEjC,MAAMF,EAAK,MAAMG,EAAQ,CAACC,EAAOC,IAAY,CAC3C,IAAMC,EAAc,IAAI,IAAID,EAAQ,IAAI,CAAC,EACnCE,EAAe,QAAQ,IAAI,oBAE7BA,GACFD,EAAY,aAAa,IAAIR,EAAqBS,CAAY,EAGhEH,EAAM,SAAS,CACb,IAAKE,EAAY,SAAS,CAC5B,CAAC,CACH,CAAC,CACH","names":["playwright_exports","__export","clerkSetup","setupClerkTestingToken","__toCommonJS","import_keys","import_dotenv","TESTING_TOKEN_API_URL","clerkSetup","options","log","msg","dotenv","publishableKey","secretKey","testingToken","apiUrl","testingTokenApiUrl","response","data","reason","TESTING_TOKEN_PARAM","setupClerkTestingToken","page","options","fapiUrl","apiUrl","route","request","originalUrl","testingToken"]}
@@ -0,0 +1,3 @@
1
+ export { clerkSetup } from './setup';
2
+ export { setupClerkTestingToken } from './setupClerkTestingToken';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/playwright/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC"}
@@ -0,0 +1,20 @@
1
+ type ClerkSetupParams = {
2
+ publishableKey?: string;
3
+ frontendApiUrl?: string;
4
+ debug?: boolean;
5
+ };
6
+ /**
7
+ * Sets up Clerk for testing by fetching the testing token from the Clerk Backend API.
8
+ *
9
+ * @param options.publishableKey - The publishable key for your Clerk dev instance.
10
+ * @param options.frontendApiUrl - The frontend API URL for your Clerk dev instance, without the protocol. It overrides the Frontend API URL parsed from the publishable key.
11
+ * @param options.debug - Enable debug logs.
12
+ * @returns A promise that resolves when Clerk is set up.
13
+ *
14
+ * @throws An error if the publishable key or the secret key is not provided.
15
+ * @throws An error if the secret key is from a production instance.
16
+ * @throws An error if the testing token cannot be fetched from the Clerk Backend API.
17
+ */
18
+ export declare const clerkSetup: (options?: ClerkSetupParams) => Promise<void>;
19
+ export {};
20
+ //# sourceMappingURL=setup.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup.d.ts","sourceRoot":"","sources":["../../src/playwright/setup.ts"],"names":[],"mappings":"AAGA,KAAK,gBAAgB,GAAG;IAWtB,cAAc,CAAC,EAAE,MAAM,CAAC;IAMxB,cAAc,CAAC,EAAE,MAAM,CAAC;IAIxB,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB,CAAC;AAIF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,UAAU,aAAoB,gBAAgB,kBAgE1D,CAAC"}
@@ -0,0 +1,29 @@
1
+ import type { Page } from '@playwright/test';
2
+ type BypassBotProtectionParams = {
3
+ page: Page;
4
+ options?: {
5
+ frontendApiUrl?: string;
6
+ };
7
+ };
8
+ /**
9
+ * Bypasses bot protection by appending the testing token in the Frontend API requests.
10
+ *
11
+ * @param params.page - The Playwright page object.
12
+ * @param params.options.frontendApiUrl - The frontend API URL for your Clerk dev instance, without the protocol.
13
+ * @returns A promise that resolves when the bot protection bypass is set up.
14
+ * @throws An error if the Frontend API URL is not provided.
15
+ * @example
16
+ * ```ts
17
+ * import { setupClerkTestingToken } from '@clerk/testing/playwright';
18
+ *
19
+ * test('should bypass bot protection', async ({ page }) => {
20
+ * await setupClerkTestingToken({ page });
21
+ * await page.goto('https://your-app.com');
22
+ * // Continue with your test...
23
+ * });
24
+ * ```
25
+ *
26
+ */
27
+ export declare const setupClerkTestingToken: ({ page, options }: BypassBotProtectionParams) => Promise<void>;
28
+ export {};
29
+ //# sourceMappingURL=setupClerkTestingToken.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setupClerkTestingToken.d.ts","sourceRoot":"","sources":["../../src/playwright/setupClerkTestingToken.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE7C,KAAK,yBAAyB,GAAG;IAC/B,IAAI,EAAE,IAAI,CAAC;IACX,OAAO,CAAC,EAAE;QAMR,cAAc,CAAC,EAAE,MAAM,CAAC;KACzB,CAAC;CACH,CAAC;AAIF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,sBAAsB,sBAA6B,yBAAyB,kBAmBxF,CAAC"}
package/package.json ADDED
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "@clerk/testing",
3
+ "version": "2.0.0-snapshot.v07d9254",
4
+ "description": "Utilities to help you create E2E test suites for apps using Clerk",
5
+ "keywords": [
6
+ "auth",
7
+ "authentication",
8
+ "passwordless",
9
+ "session",
10
+ "jwt",
11
+ "playwright",
12
+ "testing",
13
+ "e2e"
14
+ ],
15
+ "homepage": "https://clerk.com",
16
+ "bugs": {
17
+ "url": "https://github.com/clerk/javascript/issues"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/clerk/javascript.git",
22
+ "directory": "packages/testing"
23
+ },
24
+ "license": "MIT",
25
+ "author": "Clerk",
26
+ "sideEffects": false,
27
+ "exports": {
28
+ "./playwright": {
29
+ "import": {
30
+ "types": "./dist/types/index.d.ts",
31
+ "default": "./dist/esm/index.js"
32
+ },
33
+ "require": {
34
+ "types": "./dist/types/index.d.ts",
35
+ "default": "./dist/index.js"
36
+ }
37
+ }
38
+ },
39
+ "files": [
40
+ "dist"
41
+ ],
42
+ "scripts": {
43
+ "build": "tsup --env.NODE_ENV production",
44
+ "clean": "rimraf ./dist",
45
+ "dev": "tsup --watch",
46
+ "lint": "eslint src/"
47
+ },
48
+ "dependencies": {
49
+ "@clerk/shared": "2.0.0",
50
+ "@clerk/types": "4.1.0-snapshot.v07d9254",
51
+ "dotenv": "16.4.5"
52
+ },
53
+ "devDependencies": {
54
+ "@playwright/test": "^1.43.1",
55
+ "@types/node": "^18.17.0",
56
+ "eslint-config-custom": "*",
57
+ "tsup": "*",
58
+ "typescript": "*"
59
+ },
60
+ "peerDependencies": {
61
+ "@playwright/test": "^1"
62
+ },
63
+ "peerDependenciesMeta": {
64
+ "@playwright/test": {
65
+ "optional": true
66
+ }
67
+ },
68
+ "engines": {
69
+ "node": ">=18.17.0"
70
+ },
71
+ "publishConfig": {
72
+ "access": "public"
73
+ }
74
+ }