@clianta/sdk 1.6.3 → 1.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * Clianta SDK v1.6.3
2
+ * Clianta SDK v1.6.5
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
@@ -9,24 +9,35 @@
9
9
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Clianta = {}));
10
10
  })(this, (function (exports) { 'use strict';
11
11
 
12
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
12
13
  /**
13
14
  * Clianta SDK - Configuration
14
15
  * @see SDK_VERSION in core/config.ts
15
16
  */
16
17
  /** SDK Version */
17
- const SDK_VERSION = '1.6.2';
18
+ const SDK_VERSION = '1.6.5';
18
19
  /** Default API endpoint — reads from env or falls back to localhost */
19
20
  const getDefaultApiEndpoint = () => {
20
- // Build-time env var (works with Next.js, Vite, CRA, etc.)
21
+ // Next.js (process.env)
21
22
  if (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_CLIANTA_API_ENDPOINT) {
22
23
  return process.env.NEXT_PUBLIC_CLIANTA_API_ENDPOINT;
23
24
  }
24
- if (typeof process !== 'undefined' && process.env?.VITE_CLIANTA_API_ENDPOINT) {
25
- return process.env.VITE_CLIANTA_API_ENDPOINT;
25
+ // Vite / Vue / Svelte / SvelteKit (import.meta.env)
26
+ try {
27
+ // @ts-ignore — import.meta.env is Vite-specific
28
+ if (typeof ({ url: (typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('clianta.umd.js', document.baseURI).href)) }) !== 'undefined' && undefined?.VITE_CLIANTA_API_ENDPOINT) {
29
+ // @ts-ignore
30
+ return undefined.VITE_CLIANTA_API_ENDPOINT;
31
+ }
32
+ }
33
+ catch {
34
+ // import.meta not available in this environment
26
35
  }
36
+ // Create React App (process.env)
27
37
  if (typeof process !== 'undefined' && process.env?.REACT_APP_CLIANTA_API_ENDPOINT) {
28
38
  return process.env.REACT_APP_CLIANTA_API_ENDPOINT;
29
39
  }
40
+ // Generic fallback
30
41
  if (typeof process !== 'undefined' && process.env?.CLIANTA_API_ENDPOINT) {
31
42
  return process.env.CLIANTA_API_ENDPOINT;
32
43
  }
@@ -43,6 +54,7 @@
43
54
  'exitIntent',
44
55
  'errors',
45
56
  'performance',
57
+ 'autoIdentify',
46
58
  ];
47
59
  /** Default configuration values */
48
60
  const DEFAULT_CONFIG = {
@@ -2235,6 +2247,296 @@
2235
2247
  }
2236
2248
  }
2237
2249
 
2250
+ /**
2251
+ * Clianta SDK - Auto-Identify Plugin
2252
+ * Automatically detects logged-in users by checking JWT tokens in
2253
+ * cookies, localStorage, and sessionStorage. Works with any auth provider:
2254
+ * Clerk, Firebase, Auth0, Supabase, NextAuth, Passport, custom JWT, etc.
2255
+ *
2256
+ * How it works:
2257
+ * 1. On init + periodically, scans for JWT tokens
2258
+ * 2. Decodes the JWT payload (base64, no secret needed)
2259
+ * 3. Extracts email/name from standard JWT claims
2260
+ * 4. Calls tracker.identify() automatically
2261
+ *
2262
+ * @see SDK_VERSION in core/config.ts
2263
+ */
2264
+ /** Known auth cookie patterns and their JWT locations */
2265
+ const AUTH_COOKIE_PATTERNS = [
2266
+ // Clerk
2267
+ '__session',
2268
+ '__clerk_db_jwt',
2269
+ // NextAuth
2270
+ 'next-auth.session-token',
2271
+ '__Secure-next-auth.session-token',
2272
+ // Supabase
2273
+ 'sb-access-token',
2274
+ // Auth0
2275
+ 'auth0.is.authenticated',
2276
+ // Firebase — uses localStorage, handled separately
2277
+ // Generic patterns
2278
+ 'token',
2279
+ 'jwt',
2280
+ 'access_token',
2281
+ 'session_token',
2282
+ 'auth_token',
2283
+ 'id_token',
2284
+ ];
2285
+ /** localStorage/sessionStorage key patterns for auth tokens */
2286
+ const STORAGE_KEY_PATTERNS = [
2287
+ // Supabase
2288
+ 'sb-',
2289
+ 'supabase.auth.',
2290
+ // Firebase
2291
+ 'firebase:authUser:',
2292
+ // Auth0
2293
+ 'auth0spajs',
2294
+ '@@auth0spajs@@',
2295
+ // Generic
2296
+ 'token',
2297
+ 'jwt',
2298
+ 'auth',
2299
+ 'user',
2300
+ 'session',
2301
+ ];
2302
+ /** Standard JWT claim fields for email */
2303
+ const EMAIL_CLAIMS = ['email', 'sub', 'preferred_username', 'user_email', 'mail'];
2304
+ const NAME_CLAIMS = ['name', 'full_name', 'display_name', 'given_name'];
2305
+ const FIRST_NAME_CLAIMS = ['given_name', 'first_name', 'firstName'];
2306
+ const LAST_NAME_CLAIMS = ['family_name', 'last_name', 'lastName'];
2307
+ class AutoIdentifyPlugin extends BasePlugin {
2308
+ constructor() {
2309
+ super(...arguments);
2310
+ this.name = 'autoIdentify';
2311
+ this.checkInterval = null;
2312
+ this.identifiedEmail = null;
2313
+ this.checkCount = 0;
2314
+ this.MAX_CHECKS = 30; // Stop checking after ~5 minutes
2315
+ this.CHECK_INTERVAL_MS = 10000; // Check every 10 seconds
2316
+ }
2317
+ init(tracker) {
2318
+ super.init(tracker);
2319
+ if (typeof window === 'undefined')
2320
+ return;
2321
+ // First check after 2 seconds (give auth providers time to init)
2322
+ setTimeout(() => this.checkForAuthUser(), 2000);
2323
+ // Then check periodically
2324
+ this.checkInterval = setInterval(() => {
2325
+ this.checkCount++;
2326
+ if (this.checkCount >= this.MAX_CHECKS) {
2327
+ // Stop checking after MAX_CHECKS — user probably isn't logged in
2328
+ if (this.checkInterval) {
2329
+ clearInterval(this.checkInterval);
2330
+ this.checkInterval = null;
2331
+ }
2332
+ return;
2333
+ }
2334
+ this.checkForAuthUser();
2335
+ }, this.CHECK_INTERVAL_MS);
2336
+ }
2337
+ destroy() {
2338
+ if (this.checkInterval) {
2339
+ clearInterval(this.checkInterval);
2340
+ this.checkInterval = null;
2341
+ }
2342
+ super.destroy();
2343
+ }
2344
+ /**
2345
+ * Main check — scan all sources for auth tokens
2346
+ */
2347
+ checkForAuthUser() {
2348
+ if (!this.tracker || this.identifiedEmail)
2349
+ return;
2350
+ // 1. Check cookies for JWTs
2351
+ const cookieUser = this.checkCookies();
2352
+ if (cookieUser) {
2353
+ this.identifyUser(cookieUser);
2354
+ return;
2355
+ }
2356
+ // 2. Check localStorage
2357
+ const localUser = this.checkStorage(localStorage);
2358
+ if (localUser) {
2359
+ this.identifyUser(localUser);
2360
+ return;
2361
+ }
2362
+ // 3. Check sessionStorage
2363
+ const sessionUser = this.checkStorage(sessionStorage);
2364
+ if (sessionUser) {
2365
+ this.identifyUser(sessionUser);
2366
+ return;
2367
+ }
2368
+ }
2369
+ /**
2370
+ * Identify the user and stop checking
2371
+ */
2372
+ identifyUser(user) {
2373
+ if (!this.tracker || this.identifiedEmail === user.email)
2374
+ return;
2375
+ this.identifiedEmail = user.email;
2376
+ this.tracker.identify(user.email, {
2377
+ firstName: user.firstName,
2378
+ lastName: user.lastName,
2379
+ });
2380
+ // Stop interval — we found the user
2381
+ if (this.checkInterval) {
2382
+ clearInterval(this.checkInterval);
2383
+ this.checkInterval = null;
2384
+ }
2385
+ }
2386
+ /**
2387
+ * Scan cookies for JWT tokens
2388
+ */
2389
+ checkCookies() {
2390
+ if (typeof document === 'undefined')
2391
+ return null;
2392
+ try {
2393
+ const cookies = document.cookie.split(';').map(c => c.trim());
2394
+ for (const cookie of cookies) {
2395
+ const [name, ...valueParts] = cookie.split('=');
2396
+ const value = valueParts.join('=');
2397
+ const cookieName = name.trim().toLowerCase();
2398
+ // Check if this cookie matches known auth patterns
2399
+ const isAuthCookie = AUTH_COOKIE_PATTERNS.some(pattern => cookieName.includes(pattern.toLowerCase()));
2400
+ if (isAuthCookie && value) {
2401
+ const user = this.extractUserFromToken(decodeURIComponent(value));
2402
+ if (user)
2403
+ return user;
2404
+ }
2405
+ }
2406
+ }
2407
+ catch {
2408
+ // Cookie access may fail in some environments
2409
+ }
2410
+ return null;
2411
+ }
2412
+ /**
2413
+ * Scan localStorage or sessionStorage for auth tokens
2414
+ */
2415
+ checkStorage(storage) {
2416
+ try {
2417
+ for (let i = 0; i < storage.length; i++) {
2418
+ const key = storage.key(i);
2419
+ if (!key)
2420
+ continue;
2421
+ const keyLower = key.toLowerCase();
2422
+ const isAuthKey = STORAGE_KEY_PATTERNS.some(pattern => keyLower.includes(pattern.toLowerCase()));
2423
+ if (isAuthKey) {
2424
+ const value = storage.getItem(key);
2425
+ if (!value)
2426
+ continue;
2427
+ // Try as direct JWT
2428
+ const user = this.extractUserFromToken(value);
2429
+ if (user)
2430
+ return user;
2431
+ // Try as JSON containing a token
2432
+ try {
2433
+ const json = JSON.parse(value);
2434
+ const user = this.extractUserFromJson(json);
2435
+ if (user)
2436
+ return user;
2437
+ }
2438
+ catch {
2439
+ // Not JSON, skip
2440
+ }
2441
+ }
2442
+ }
2443
+ }
2444
+ catch {
2445
+ // Storage access may fail (iframe, security restrictions)
2446
+ }
2447
+ return null;
2448
+ }
2449
+ /**
2450
+ * Try to extract user info from a JWT token string
2451
+ */
2452
+ extractUserFromToken(token) {
2453
+ // JWT format: header.payload.signature
2454
+ const parts = token.split('.');
2455
+ if (parts.length !== 3)
2456
+ return null;
2457
+ try {
2458
+ const payload = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')));
2459
+ return this.extractUserFromClaims(payload);
2460
+ }
2461
+ catch {
2462
+ return null;
2463
+ }
2464
+ }
2465
+ /**
2466
+ * Extract user info from a JSON object (e.g., Firebase auth user stored in localStorage)
2467
+ */
2468
+ extractUserFromJson(data) {
2469
+ if (!data || typeof data !== 'object')
2470
+ return null;
2471
+ // Direct user object
2472
+ const user = this.extractUserFromClaims(data);
2473
+ if (user)
2474
+ return user;
2475
+ // Nested: { user: { email } } or { data: { user: { email } } }
2476
+ for (const key of ['user', 'data', 'session', 'currentUser', 'authUser', 'access_token', 'token']) {
2477
+ if (data[key]) {
2478
+ if (typeof data[key] === 'string') {
2479
+ // Might be a JWT inside JSON
2480
+ const tokenUser = this.extractUserFromToken(data[key]);
2481
+ if (tokenUser)
2482
+ return tokenUser;
2483
+ }
2484
+ else if (typeof data[key] === 'object') {
2485
+ const nestedUser = this.extractUserFromClaims(data[key]);
2486
+ if (nestedUser)
2487
+ return nestedUser;
2488
+ }
2489
+ }
2490
+ }
2491
+ return null;
2492
+ }
2493
+ /**
2494
+ * Extract user from JWT claims or user object
2495
+ */
2496
+ extractUserFromClaims(claims) {
2497
+ if (!claims || typeof claims !== 'object')
2498
+ return null;
2499
+ // Find email
2500
+ let email = null;
2501
+ for (const claim of EMAIL_CLAIMS) {
2502
+ const value = claims[claim];
2503
+ if (value && typeof value === 'string' && value.includes('@') && value.includes('.')) {
2504
+ email = value;
2505
+ break;
2506
+ }
2507
+ }
2508
+ if (!email)
2509
+ return null;
2510
+ // Find name
2511
+ let firstName;
2512
+ let lastName;
2513
+ for (const claim of FIRST_NAME_CLAIMS) {
2514
+ if (claims[claim] && typeof claims[claim] === 'string') {
2515
+ firstName = claims[claim];
2516
+ break;
2517
+ }
2518
+ }
2519
+ for (const claim of LAST_NAME_CLAIMS) {
2520
+ if (claims[claim] && typeof claims[claim] === 'string') {
2521
+ lastName = claims[claim];
2522
+ break;
2523
+ }
2524
+ }
2525
+ // If no first/last name, try full name
2526
+ if (!firstName) {
2527
+ for (const claim of NAME_CLAIMS) {
2528
+ if (claims[claim] && typeof claims[claim] === 'string') {
2529
+ const parts = claims[claim].split(' ');
2530
+ firstName = parts[0];
2531
+ lastName = lastName || parts.slice(1).join(' ') || undefined;
2532
+ break;
2533
+ }
2534
+ }
2535
+ }
2536
+ return { email, firstName, lastName };
2537
+ }
2538
+ }
2539
+
2238
2540
  /**
2239
2541
  * Clianta SDK - Plugins Index
2240
2542
  * Version is defined in core/config.ts as SDK_VERSION
@@ -2264,6 +2566,8 @@
2264
2566
  return new PerformancePlugin();
2265
2567
  case 'popupForms':
2266
2568
  return new PopupFormsPlugin();
2569
+ case 'autoIdentify':
2570
+ return new AutoIdentifyPlugin();
2267
2571
  default:
2268
2572
  throw new Error(`Unknown plugin: ${name}`);
2269
2573
  }