@nexushub/client 0.4.2 → 0.4.4

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/index.js CHANGED
@@ -1,33 +1,2587 @@
1
- "use client";
2
- import {
3
- AnalyticsEngine,
4
- AuthProvider,
5
- BrowserCache,
6
- CacheTags,
7
- ContentEngine,
8
- DEFAULT_ANALYTICS_URL,
9
- DEFAULT_API_URL,
10
- LOCAL_NEST_URL,
11
- LOCAL_RUST_URL,
12
- LocalCacheProxy,
13
- MemoryCache,
14
- NexusClient,
15
- NexusProvider,
16
- createNexusClient,
17
- getEnvConfig,
18
- getFullConfig,
19
- mergeConfigs,
20
- nexus,
21
- useNexus,
22
- useNexusAuth,
23
- validateConfig
24
- } from "./chunk-G4SHBWAQ.js";
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // src/config.ts
12
+ var DEFAULT_API_URL, DEFAULT_ANALYTICS_URL, LOCAL_NEST_URL, LOCAL_RUST_URL, getEnvConfig, mergeConfigs, getFullConfig, validateConfig;
13
+ var init_config = __esm({
14
+ "src/config.ts"() {
15
+ "use strict";
16
+ DEFAULT_API_URL = "https://endpoints.gnexus.co.tz";
17
+ DEFAULT_ANALYTICS_URL = "https://sentry.gnexus.co.tz";
18
+ LOCAL_NEST_URL = "https://endpoints.gnexus.co.tz";
19
+ LOCAL_RUST_URL = "https://sentry.gnexus.co.tz";
20
+ getEnvConfig = () => {
21
+ const NEXT_PUBLIC_ID = typeof process !== "undefined" ? process.env.NEXT_PUBLIC_NEXUS_ID : void 0;
22
+ const NEXT_PUBLIC_KEY = typeof process !== "undefined" ? process.env.NEXT_PUBLIC_NEXUS_KEY : void 0;
23
+ const NEXT_PUBLIC_URL = typeof process !== "undefined" ? process.env.NEXT_PUBLIC_NEXUS_API_URL : void 0;
24
+ const NODE_ID = typeof process !== "undefined" ? process.env.NEXUS_PROJECT_ID : void 0;
25
+ const NODE_KEY = typeof process !== "undefined" ? process.env.NEXUS_API_KEY : void 0;
26
+ const NODE_URL = typeof process !== "undefined" ? process.env.NEXUS_API_URL : void 0;
27
+ const NODE_ENV = typeof process !== "undefined" ? process.env.NODE_ENV : "production";
28
+ const isDev = NODE_ENV === "development" || typeof window !== "undefined" && window.location.hostname === "localhost";
29
+ const projectId = NEXT_PUBLIC_ID ?? NODE_ID;
30
+ const apiKey = NEXT_PUBLIC_KEY ?? NODE_KEY;
31
+ const apiUrl = NEXT_PUBLIC_URL ?? NODE_URL ?? (isDev ? LOCAL_NEST_URL : DEFAULT_API_URL);
32
+ const analyticsUrl = apiUrl.includes("localhost") ? LOCAL_RUST_URL : DEFAULT_ANALYTICS_URL;
33
+ return {
34
+ projectId,
35
+ apiKey,
36
+ apiUrl,
37
+ analyticsUrl
38
+ };
39
+ };
40
+ mergeConfigs = (base, override) => {
41
+ const mergedApiUrl = override.apiUrl || base.apiUrl || DEFAULT_API_URL;
42
+ const mergedAnalyticsUrl = override.analyticsUrl || base.analyticsUrl || (mergedApiUrl.includes("localhost") ? LOCAL_RUST_URL : DEFAULT_ANALYTICS_URL);
43
+ return {
44
+ ...base,
45
+ ...override,
46
+ apiUrl: mergedApiUrl,
47
+ analyticsUrl: mergedAnalyticsUrl,
48
+ projectId: override.projectId || base.projectId,
49
+ apiKey: override.apiKey || base.apiKey
50
+ };
51
+ };
52
+ getFullConfig = (partialConfig) => {
53
+ const envConfig = getEnvConfig();
54
+ return mergeConfigs(envConfig, partialConfig || {});
55
+ };
56
+ validateConfig = (config) => {
57
+ const errors = [];
58
+ if (!config.projectId) errors.push("Missing projectId");
59
+ if (!config.apiUrl) errors.push("Missing apiUrl");
60
+ return errors;
61
+ };
62
+ }
63
+ });
64
+
65
+ // src/content/binary-compiler.ts
66
+ import * as crypto2 from "crypto";
67
+ var BinaryCompiler;
68
+ var init_binary_compiler = __esm({
69
+ "src/content/binary-compiler.ts"() {
70
+ "use strict";
71
+ BinaryCompiler = class {
72
+ /**
73
+ * Generates a secure, deterministic cryptographic key from the project's API key.
74
+ */
75
+ static deriveKeys(apiKey) {
76
+ const hash = crypto2.createHash("sha256").update(apiKey).digest();
77
+ const encryptionKey = hash;
78
+ const hmacKey = crypto2.createHmac("sha256", apiKey).update("nexus-integrity-key").digest();
79
+ return { encryptionKey, hmacKey };
80
+ }
81
+ /**
82
+ * Compiles JSON content data into a secure, signed, and encrypted .nx binary buffer.
83
+ */
84
+ static compile(data, apiKey, projectId, metadataOverrides = {}) {
85
+ const { encryptionKey, hmacKey } = this.deriveKeys(apiKey);
86
+ const metadata = {
87
+ version: "2.0.0",
88
+ compiledAt: (/* @__PURE__ */ new Date()).toISOString(),
89
+ projectId,
90
+ ...metadataOverrides
91
+ };
92
+ const metadataStr = JSON.stringify(metadata);
93
+ const metadataBuffer = Buffer.from(metadataStr, "utf-8");
94
+ const iv = crypto2.randomBytes(16);
95
+ const cipher = crypto2.createCipheriv(this.ALGORITHM, encryptionKey, iv);
96
+ const plainTextPayload = JSON.stringify(data);
97
+ let encryptedPayload = cipher.update(plainTextPayload, "utf8");
98
+ encryptedPayload = Buffer.concat([encryptedPayload, cipher.final()]);
99
+ const payloadBuffer = Buffer.concat([iv, encryptedPayload]);
100
+ const headerBuffer = Buffer.from(this.MAGIC_HEADER, "ascii");
101
+ const metaLengthBuffer = Buffer.alloc(4);
102
+ metaLengthBuffer.writeUInt32BE(metadataBuffer.length, 0);
103
+ const payloadLengthBuffer = Buffer.alloc(4);
104
+ payloadLengthBuffer.writeUInt32BE(payloadBuffer.length, 0);
105
+ const prefixBlock = Buffer.concat([
106
+ headerBuffer,
107
+ metaLengthBuffer,
108
+ metadataBuffer,
109
+ payloadLengthBuffer,
110
+ payloadBuffer
111
+ ]);
112
+ const hmac = crypto2.createHmac("sha256", hmacKey);
113
+ hmac.update(prefixBlock);
114
+ const signature = hmac.digest();
115
+ return Buffer.concat([prefixBlock, signature]);
116
+ }
117
+ /**
118
+ * Verifies, decrypts, and decompiles a .nx binary buffer back into clean, type-safe JSON.
119
+ * Throws structured errors on integrity verification failures or file corruption.
120
+ */
121
+ static decompile(buffer, apiKey) {
122
+ if (buffer.length < 44) {
123
+ throw new Error(
124
+ "Corrupted File: Binary payload is too short to be a valid Nexus node."
125
+ );
126
+ }
127
+ const { encryptionKey, hmacKey } = this.deriveKeys(apiKey);
128
+ const prefixBlockLength = buffer.length - 32;
129
+ const prefixBlock = buffer.subarray(0, prefixBlockLength);
130
+ const expectedSignature = buffer.subarray(prefixBlockLength);
131
+ const hmac = crypto2.createHmac("sha256", hmacKey);
132
+ hmac.update(prefixBlock);
133
+ const actualSignature = hmac.digest();
134
+ if (!crypto2.timingSafeEqual(expectedSignature, actualSignature)) {
135
+ throw new Error(
136
+ "DATA_INTEGRITY_VIOLATION: Cryptographic signature mismatch. This local node has been modified externally or tampered with."
137
+ );
138
+ }
139
+ const magicHeader = prefixBlock.subarray(0, 4).toString("ascii");
140
+ if (magicHeader !== this.MAGIC_HEADER) {
141
+ throw new Error(
142
+ "Invalid Format: File lacks the correct Nexus binary magic header."
143
+ );
144
+ }
145
+ const metaLength = prefixBlock.readUInt32BE(4);
146
+ const metaStart = 8;
147
+ const metaEnd = metaStart + metaLength;
148
+ const metadataStr = prefixBlock.subarray(metaStart, metaEnd).toString("utf-8");
149
+ const metadata = JSON.parse(metadataStr);
150
+ const payloadLength = prefixBlock.readUInt32BE(metaEnd);
151
+ const payloadStart = metaEnd + 4;
152
+ const payloadEnd = payloadStart + payloadLength;
153
+ const payloadBuffer = prefixBlock.subarray(payloadStart, payloadEnd);
154
+ const iv = payloadBuffer.subarray(0, 16);
155
+ const cipherText = payloadBuffer.subarray(16);
156
+ const decipher = crypto2.createDecipheriv(this.ALGORITHM, encryptionKey, iv);
157
+ let decrypted = decipher.update(cipherText);
158
+ decrypted = Buffer.concat([decrypted, decipher.final()]);
159
+ const data = JSON.parse(decrypted.toString("utf8"));
160
+ return { data, metadata };
161
+ }
162
+ };
163
+ BinaryCompiler.MAGIC_HEADER = "NEXS";
164
+ // 4-byte ASCII magic identifier
165
+ BinaryCompiler.ALGORITHM = "aes-256-cbc";
166
+ }
167
+ });
168
+
169
+ // src/content/local-cache-server.ts
170
+ var local_cache_server_exports = {};
171
+ __export(local_cache_server_exports, {
172
+ LocalCache: () => LocalCache
173
+ });
174
+ import fs from "fs";
175
+ import path from "path";
176
+ var LocalCache;
177
+ var init_local_cache_server = __esm({
178
+ "src/content/local-cache-server.ts"() {
179
+ "use strict";
180
+ init_config();
181
+ init_binary_compiler();
182
+ LocalCache = class {
183
+ constructor(customPath) {
184
+ this.apiKey = "";
185
+ this.baseDir = customPath || ".nexus/local";
186
+ const config = getEnvConfig();
187
+ this.apiKey = config.apiKey || "";
188
+ }
189
+ isLoaded() {
190
+ return fs.existsSync(path.resolve(process.cwd(), this.baseDir));
191
+ }
192
+ /**
193
+ * Helper to decrypt and decompile `.nx` files on-the-fly.
194
+ */
195
+ decompileFile(filePath) {
196
+ if (!this.apiKey) {
197
+ if (process.env.NODE_ENV === "development") {
198
+ console.warn(
199
+ "\u26A0\uFE0F NexusHub: Missing NEXUS_API_KEY. Local decryption bypassed."
200
+ );
201
+ }
202
+ return null;
203
+ }
204
+ try {
205
+ const encryptedBuffer = fs.readFileSync(filePath);
206
+ const decompiled = BinaryCompiler.decompile(encryptedBuffer, this.apiKey);
207
+ return decompiled.data;
208
+ } catch (error) {
209
+ if (process.env.NODE_ENV === "development") {
210
+ console.error(
211
+ `
212
+ \u{1F6A8} NexusHub Security Alert: Data Integrity Violation in file:
213
+ ${filePath}
214
+ Error: ${error.message}
215
+ This file has been disabled until regenerated via npx nexus pull.
216
+ `
217
+ );
218
+ }
219
+ return null;
220
+ }
221
+ }
222
+ /**
223
+ * Retrieve a specific page directly from its .nx file.
224
+ */
225
+ async getPage(slug) {
226
+ const filePath = path.resolve(
227
+ process.cwd(),
228
+ this.baseDir,
229
+ "pages",
230
+ `${slug}.nx`
231
+ );
232
+ if (fs.existsSync(filePath)) {
233
+ const pageData = this.decompileFile(filePath);
234
+ if (!pageData) return null;
235
+ return pageData.data !== void 0 ? pageData.data : pageData;
236
+ }
237
+ return null;
238
+ }
239
+ /**
240
+ * Retrieve an entire collection from its specific .nx file.
241
+ */
242
+ async getCollection(collectionId) {
243
+ const filePath = path.resolve(
244
+ process.cwd(),
245
+ this.baseDir,
246
+ "collections",
247
+ `${collectionId}.nx`
248
+ );
249
+ if (fs.existsSync(filePath)) {
250
+ return this.decompileFile(filePath);
251
+ }
252
+ return null;
253
+ }
254
+ /**
255
+ * Retrieve global settings from its .nx file.
256
+ */
257
+ async getGlobals() {
258
+ const filePath = path.resolve(process.cwd(), this.baseDir, "globals.nx");
259
+ if (fs.existsSync(filePath)) {
260
+ return this.decompileFile(filePath);
261
+ }
262
+ return null;
263
+ }
264
+ /**
265
+ * Returns a merged JSON of the entire workspace structure.
266
+ */
267
+ async getAllData() {
268
+ const pages = {};
269
+ const collections = {};
270
+ let globals = {};
271
+ try {
272
+ const pagesDir = path.resolve(process.cwd(), this.baseDir, "pages");
273
+ if (fs.existsSync(pagesDir)) {
274
+ for (const file of fs.readdirSync(pagesDir)) {
275
+ if (file.endsWith(".nx")) {
276
+ const slug = path.basename(file, ".nx");
277
+ pages[slug] = await this.getPage(slug);
278
+ }
279
+ }
280
+ }
281
+ const colsDir = path.resolve(process.cwd(), this.baseDir, "collections");
282
+ if (fs.existsSync(colsDir)) {
283
+ for (const file of fs.readdirSync(colsDir)) {
284
+ if (file.endsWith(".nx")) {
285
+ const id = path.basename(file, ".nx");
286
+ collections[id] = await this.getCollection(id) || [];
287
+ }
288
+ }
289
+ }
290
+ globals = await this.getGlobals() || {};
291
+ } catch {
292
+ }
293
+ return { pages, collections, globals };
294
+ }
295
+ };
296
+ }
297
+ });
298
+
299
+ // src/content/local-cache-client.ts
300
+ var local_cache_client_exports = {};
301
+ __export(local_cache_client_exports, {
302
+ LocalCache: () => LocalCache2
303
+ });
304
+ var LocalCache2;
305
+ var init_local_cache_client = __esm({
306
+ "src/content/local-cache-client.ts"() {
307
+ "use strict";
308
+ LocalCache2 = class {
309
+ constructor(customPath) {
310
+ // Maintain private properties for type parity with the Server version
311
+ this.data = null;
312
+ this.hasLoaded = false;
313
+ this.cachePath = customPath || ".nexus/cache.json";
314
+ }
315
+ /**
316
+ * Always returns false in the browser as local file caching
317
+ * is a server-side only feature.
318
+ */
319
+ isLoaded() {
320
+ return false;
321
+ }
322
+ /**
323
+ * No-op method to maintain internal API compatibility.
324
+ */
325
+ load() {
326
+ return;
327
+ }
328
+ /**
329
+ * Returns null. Browsers should fetch pages from the Remote API
330
+ * or the Memory/Browser cache.
331
+ */
332
+ async getPage(_slug) {
333
+ return null;
334
+ }
335
+ /**
336
+ * Returns null. Browsers should fetch collections from the Remote API.
337
+ */
338
+ async getCollection(_collectionId) {
339
+ return null;
340
+ }
341
+ /**
342
+ * Returns null.
343
+ */
344
+ async getGlobals() {
345
+ return null;
346
+ }
347
+ /**
348
+ * Returns null.
349
+ */
350
+ async getAllData() {
351
+ return null;
352
+ }
353
+ /**
354
+ * Dummy helper to match Node implementation.
355
+ */
356
+ shouldWarnAboutMissingCache(error) {
357
+ const isMissing = error.code === "ENOENT";
358
+ const isMalformed = error instanceof SyntaxError;
359
+ if (process.env.NODE_ENV !== "development") return false;
360
+ return !isMissing || isMalformed;
361
+ }
362
+ };
363
+ }
364
+ });
365
+
366
+ // src/client.ts
367
+ init_config();
368
+
369
+ // src/content/cache-implementations.ts
370
+ var CacheTags = {
371
+ project: (projectId) => `nexus_project_${projectId}`,
372
+ content: (slug) => `content_${slug}`,
373
+ collection: (collectionId) => `collection_${collectionId}`,
374
+ global: "nexus_global_config",
375
+ user: (userId) => `user_${userId}`,
376
+ media: (mediaId) => `media_${mediaId}`
377
+ };
378
+ var MemoryCache = class {
379
+ constructor(options = {}) {
380
+ this.cache = /* @__PURE__ */ new Map();
381
+ this.tagIndex = /* @__PURE__ */ new Map();
382
+ this.stats = {
383
+ size: 0,
384
+ hits: 0,
385
+ misses: 0,
386
+ hitRate: 0,
387
+ evictions: 0
388
+ };
389
+ this.maxSize = options.maxSize || 1e3;
390
+ this.defaultTTL = options.ttl || 5 * 60 * 1e3;
391
+ }
392
+ set(key, data, options = {}) {
393
+ if (this.cache.size >= this.maxSize) {
394
+ this.evictLRU();
395
+ }
396
+ const metadata = {
397
+ timestamp: Date.now(),
398
+ expiresAt: Date.now() + (options.ttl || this.defaultTTL),
399
+ tags: options.tags || [],
400
+ size: this.calculateSize(data)
401
+ };
402
+ this.cache.set(key, { data, metadata });
403
+ this.stats.size = this.cache.size;
404
+ metadata.tags.forEach((tag) => {
405
+ if (!this.tagIndex.has(tag)) {
406
+ this.tagIndex.set(tag, /* @__PURE__ */ new Set());
407
+ }
408
+ this.tagIndex.get(tag).add(key);
409
+ });
410
+ }
411
+ get(key) {
412
+ const entry = this.cache.get(key);
413
+ if (!entry) {
414
+ this.stats.misses++;
415
+ this.updateHitRate();
416
+ return null;
417
+ }
418
+ if (Date.now() > entry.metadata.expiresAt) {
419
+ this.delete(key);
420
+ this.stats.misses++;
421
+ this.updateHitRate();
422
+ return null;
423
+ }
424
+ entry.metadata.timestamp = Date.now();
425
+ this.stats.hits++;
426
+ this.updateHitRate();
427
+ return entry;
428
+ }
429
+ delete(key) {
430
+ const entry = this.cache.get(key);
431
+ if (!entry) return false;
432
+ entry.metadata.tags.forEach((tag) => {
433
+ const keys = this.tagIndex.get(tag);
434
+ if (keys) {
435
+ keys.delete(key);
436
+ if (keys.size === 0) {
437
+ this.tagIndex.delete(tag);
438
+ }
439
+ }
440
+ });
441
+ this.cache.delete(key);
442
+ this.stats.size = this.cache.size;
443
+ return true;
444
+ }
445
+ invalidateByTags(tags) {
446
+ const keysToDelete = /* @__PURE__ */ new Set();
447
+ tags.forEach((tag) => {
448
+ const keys = this.tagIndex.get(tag);
449
+ if (keys) {
450
+ keys.forEach((key) => keysToDelete.add(key));
451
+ this.tagIndex.delete(tag);
452
+ }
453
+ });
454
+ keysToDelete.forEach((key) => this.delete(key));
455
+ if (process.env.NODE_ENV === "development") {
456
+ console.log(
457
+ `[MemoryCache] Invalidated ${keysToDelete.size} entries by tags: ${tags.join(", ")}`
458
+ );
459
+ }
460
+ }
461
+ clear() {
462
+ this.cache.clear();
463
+ this.tagIndex.clear();
464
+ this.stats = {
465
+ size: 0,
466
+ hits: 0,
467
+ misses: 0,
468
+ hitRate: 0,
469
+ evictions: 0
470
+ };
471
+ }
472
+ getStats() {
473
+ return { ...this.stats };
474
+ }
475
+ evictLRU() {
476
+ let oldestKey = null;
477
+ let oldestTime = Infinity;
478
+ for (const [key, entry] of this.cache.entries()) {
479
+ if (entry.metadata.timestamp < oldestTime) {
480
+ oldestTime = entry.metadata.timestamp;
481
+ oldestKey = key;
482
+ }
483
+ }
484
+ if (oldestKey) {
485
+ this.delete(oldestKey);
486
+ this.stats.evictions++;
487
+ }
488
+ }
489
+ calculateSize(data) {
490
+ try {
491
+ const jsonString = JSON.stringify(data);
492
+ return new Blob([jsonString]).size;
493
+ } catch {
494
+ return 0;
495
+ }
496
+ }
497
+ updateHitRate() {
498
+ const total = this.stats.hits + this.stats.misses;
499
+ this.stats.hitRate = total > 0 ? this.stats.hits / total : 0;
500
+ }
501
+ };
502
+ var BrowserCache = class {
503
+ constructor(projectId) {
504
+ this.projectId = projectId;
505
+ this.prefix = "nexushub_";
506
+ this.maxSize = 5 * 1024 * 1024;
507
+ // 5MB standard LocalStorage limit
508
+ this.currentSize = 0;
509
+ if (typeof window !== "undefined") {
510
+ this.calculateCurrentSize();
511
+ }
512
+ }
513
+ set(key, data, ttl = 5 * 60 * 1e3) {
514
+ if (typeof window === "undefined") return;
515
+ const storageKey = this.getStorageKey(key);
516
+ const entry = {
517
+ data,
518
+ metadata: {
519
+ timestamp: Date.now(),
520
+ expiresAt: Date.now() + ttl,
521
+ size: this.calculateStorageSize(data)
522
+ }
523
+ };
524
+ const serialized = JSON.stringify(entry);
525
+ const newSize = new Blob([serialized]).size;
526
+ if (this.currentSize + newSize > this.maxSize) {
527
+ this.evictOldest();
528
+ }
529
+ try {
530
+ localStorage.setItem(storageKey, serialized);
531
+ this.currentSize += newSize;
532
+ } catch (error) {
533
+ console.warn("[BrowserCache] Failed to save to localStorage:", error);
534
+ this.evictOldest();
535
+ try {
536
+ localStorage.setItem(storageKey, serialized);
537
+ } catch (e) {
538
+ }
539
+ }
540
+ }
541
+ get(key) {
542
+ if (typeof window === "undefined") return null;
543
+ const storageKey = this.getStorageKey(key);
544
+ const item = localStorage.getItem(storageKey);
545
+ if (!item) return null;
546
+ try {
547
+ const entry = JSON.parse(item);
548
+ if (Date.now() > entry.metadata.expiresAt) {
549
+ this.delete(key);
550
+ return null;
551
+ }
552
+ return entry.data;
553
+ } catch {
554
+ this.delete(key);
555
+ return null;
556
+ }
557
+ }
558
+ delete(key) {
559
+ if (typeof window === "undefined") return;
560
+ const storageKey = this.getStorageKey(key);
561
+ const item = localStorage.getItem(storageKey);
562
+ if (item) {
563
+ this.currentSize -= new Blob([item]).size;
564
+ }
565
+ localStorage.removeItem(storageKey);
566
+ }
567
+ clear() {
568
+ if (typeof window === "undefined") return;
569
+ const keysToRemove = [];
570
+ for (let i = 0; i < localStorage.length; i++) {
571
+ const key = localStorage.key(i);
572
+ if (key?.startsWith(this.prefix)) {
573
+ keysToRemove.push(key);
574
+ }
575
+ }
576
+ keysToRemove.forEach((key) => localStorage.removeItem(key));
577
+ this.currentSize = 0;
578
+ }
579
+ getStorageKey(key) {
580
+ return `${this.prefix}${this.projectId}_${key}`;
581
+ }
582
+ calculateCurrentSize() {
583
+ this.currentSize = 0;
584
+ for (let i = 0; i < localStorage.length; i++) {
585
+ const key = localStorage.key(i);
586
+ if (key?.startsWith(this.prefix)) {
587
+ const item = localStorage.getItem(key);
588
+ if (item) {
589
+ this.currentSize += new Blob([item]).size;
590
+ }
591
+ }
592
+ }
593
+ }
594
+ calculateStorageSize(data) {
595
+ return new Blob([JSON.stringify(data)]).size;
596
+ }
597
+ evictOldest() {
598
+ let oldestKey = null;
599
+ let oldestTime = Infinity;
600
+ for (let i = 0; i < localStorage.length; i++) {
601
+ const key = localStorage.key(i);
602
+ if (key?.startsWith(this.prefix)) {
603
+ const item = localStorage.getItem(key);
604
+ if (item) {
605
+ try {
606
+ const entry = JSON.parse(item);
607
+ if (entry.metadata.timestamp < oldestTime) {
608
+ oldestTime = entry.metadata.timestamp;
609
+ oldestKey = key;
610
+ }
611
+ } catch {
612
+ localStorage.removeItem(key);
613
+ }
614
+ }
615
+ }
616
+ }
617
+ if (oldestKey) {
618
+ const item = localStorage.getItem(oldestKey);
619
+ if (item) {
620
+ this.currentSize -= new Blob([item]).size;
621
+ }
622
+ localStorage.removeItem(oldestKey);
623
+ }
624
+ }
625
+ };
626
+
627
+ // src/content/cache.ts
628
+ var LocalCacheProxy = class {
629
+ constructor(cachePath) {
630
+ this.instance = null;
631
+ this.cachePath = cachePath;
632
+ }
633
+ async getInstance() {
634
+ if (this.instance) return this.instance;
635
+ if (typeof window === "undefined") {
636
+ const mod = await Promise.resolve().then(() => (init_local_cache_server(), local_cache_server_exports));
637
+ this.instance = new mod.LocalCache(this.cachePath);
638
+ } else {
639
+ const mod = await Promise.resolve().then(() => (init_local_cache_client(), local_cache_client_exports));
640
+ this.instance = new mod.LocalCache(this.cachePath);
641
+ }
642
+ return this.instance;
643
+ }
644
+ isLoaded() {
645
+ return this.instance?.isLoaded() || false;
646
+ }
647
+ async getPage(slug) {
648
+ const inst = await this.getInstance();
649
+ return inst.getPage(slug);
650
+ }
651
+ async getCollection(id) {
652
+ const inst = await this.getInstance();
653
+ return inst.getCollection(id);
654
+ }
655
+ async getGlobals() {
656
+ const inst = await this.getInstance();
657
+ return inst.getGlobals();
658
+ }
659
+ async getAllData() {
660
+ const inst = await this.getInstance();
661
+ return inst.getAllData();
662
+ }
663
+ };
664
+
665
+ // src/content/strategies.ts
666
+ var RateLimiter = class {
667
+ constructor(config) {
668
+ this.requests = [];
669
+ this.config = config;
670
+ }
671
+ async checkLimit() {
672
+ while (true) {
673
+ const now = Date.now();
674
+ const windowStart = now - this.config.timeWindow;
675
+ this.requests = this.requests.filter((time) => time > windowStart);
676
+ if (this.requests.length < this.config.maxRequests) {
677
+ this.requests.push(now);
678
+ return;
679
+ }
680
+ const oldestRequest = this.requests[0];
681
+ const waitTime = oldestRequest + this.config.timeWindow - now;
682
+ if (waitTime > 0) {
683
+ await new Promise((resolve) => setTimeout(resolve, waitTime));
684
+ } else {
685
+ }
686
+ }
687
+ }
688
+ getStats() {
689
+ const now = Date.now();
690
+ const windowStart = now - this.config.timeWindow;
691
+ const currentRequests = this.requests.filter(
692
+ (time) => time > windowStart
693
+ ).length;
694
+ return { currentRequests, limit: this.config.maxRequests };
695
+ }
696
+ };
697
+ var ExponentialBackoff = class {
698
+ constructor(config) {
699
+ this.config = { jitter: true, ...config };
700
+ }
701
+ async execute(fn, onRetry) {
702
+ let lastError = new Error("Unknown error");
703
+ for (let attempt = 0; attempt <= this.config.maxRetries; attempt++) {
704
+ try {
705
+ return await fn();
706
+ } catch (error) {
707
+ lastError = error;
708
+ if (this.isClientError(error) && !this.isRateLimitError(error)) {
709
+ throw error;
710
+ }
711
+ if (attempt === this.config.maxRetries) break;
712
+ const delay = this.calculateDelay(attempt);
713
+ if (onRetry) onRetry(attempt + 1, delay, error);
714
+ await new Promise((resolve) => setTimeout(resolve, delay));
715
+ }
716
+ }
717
+ throw lastError;
718
+ }
719
+ calculateDelay(attempt) {
720
+ let delay = this.config.baseDelay * Math.pow(2, attempt);
721
+ delay = Math.min(delay, this.config.maxDelay);
722
+ if (this.config.jitter) {
723
+ delay = delay * (0.5 + Math.random());
724
+ }
725
+ return delay;
726
+ }
727
+ isClientError(error) {
728
+ return error?.status >= 400 && error?.status < 500;
729
+ }
730
+ isRateLimitError(error) {
731
+ return error?.status === 429;
732
+ }
733
+ };
734
+ var CircuitBreaker = class {
735
+ constructor() {
736
+ this.state = 0 /* CLOSED */;
737
+ this.failures = 0;
738
+ this.lastFailureTime = 0;
739
+ this.failureThreshold = 5;
740
+ this.resetTimeout = 3e4;
741
+ }
742
+ // 30 seconds
743
+ isOpen() {
744
+ if (this.state === 1 /* OPEN */) {
745
+ if (Date.now() - this.lastFailureTime > this.resetTimeout) {
746
+ this.state = 2 /* HALF_OPEN */;
747
+ return false;
748
+ }
749
+ return true;
750
+ }
751
+ return false;
752
+ }
753
+ recordSuccess() {
754
+ this.failures = 0;
755
+ this.state = 0 /* CLOSED */;
756
+ }
757
+ recordFailure() {
758
+ this.failures++;
759
+ this.lastFailureTime = Date.now();
760
+ if (this.failures >= this.failureThreshold) {
761
+ this.state = 1 /* OPEN */;
762
+ if (process.env.NODE_ENV === "development") {
763
+ console.warn(
764
+ "[NexusHub] \u{1F50C} Circuit Breaker OPEN. Pausing network requests."
765
+ );
766
+ }
767
+ }
768
+ }
769
+ };
770
+ var RequestBatcher = class {
771
+ constructor(batchWindow = 10, maxBatchSize = 20) {
772
+ this.batchWindow = batchWindow;
773
+ this.maxBatchSize = maxBatchSize;
774
+ this.batch = [];
775
+ this.processing = false;
776
+ }
777
+ async schedule(key, request) {
778
+ return new Promise((resolve, reject) => {
779
+ this.batch.push({ key, resolve, reject });
780
+ if (this.batch.length >= this.maxBatchSize) {
781
+ this.processBatch(request);
782
+ } else if (!this.batchTimeout) {
783
+ this.batchTimeout = setTimeout(
784
+ () => this.processBatch(request),
785
+ this.batchWindow
786
+ );
787
+ }
788
+ });
789
+ }
790
+ async processBatch(request) {
791
+ if (this.processing || this.batch.length === 0) return;
792
+ this.processing = true;
793
+ if (this.batchTimeout) {
794
+ clearTimeout(this.batchTimeout);
795
+ this.batchTimeout = void 0;
796
+ }
797
+ const currentBatch = [...this.batch];
798
+ this.batch = [];
799
+ try {
800
+ const result = await request();
801
+ currentBatch.forEach((item) => item.resolve(result));
802
+ } catch (error) {
803
+ currentBatch.forEach((item) => item.reject(error));
804
+ } finally {
805
+ this.processing = false;
806
+ if (this.batch.length > 0) {
807
+ setTimeout(() => this.processBatch(request), 0);
808
+ }
809
+ }
810
+ }
811
+ };
812
+
813
+ // src/content/utils.ts
814
+ function validateSlug(slug) {
815
+ if (!slug || typeof slug !== "string") {
816
+ throw new Error("Slug must be a non-empty string");
817
+ }
818
+ if (!/^[a-z0-9-_]+$/.test(slug)) {
819
+ throw new Error("Slug can only contain lowercase letters, numbers, hyphens, and underscores");
820
+ }
821
+ }
822
+ function normalizeQuery(query) {
823
+ const normalized = { ...query };
824
+ normalized.page = Math.max(1, normalized.page || 1);
825
+ normalized.limit = Math.min(100, Math.max(1, normalized.limit || 10));
826
+ normalized.order = normalized.order || "desc";
827
+ if (normalized.page < 1) {
828
+ throw new Error("Page must be greater than 0");
829
+ }
830
+ if (normalized.limit < 1 || normalized.limit > 100) {
831
+ throw new Error("Limit must be between 1 and 100");
832
+ }
833
+ return normalized;
834
+ }
835
+ function buildQueryString(query) {
836
+ const params = new URLSearchParams();
837
+ if (query.page) params.append("page", query.page.toString());
838
+ if (query.limit) params.append("limit", query.limit.toString());
839
+ if (query.sort) params.append("sort", query.sort);
840
+ if (query.order) params.append("order", query.order);
841
+ if (query.search) params.append("search", query.search);
842
+ if (query.include?.length) {
843
+ params.append("include", query.include.join(","));
844
+ }
845
+ if (query.fields?.length) {
846
+ params.append("fields", query.fields.join(","));
847
+ }
848
+ if (query.filter) {
849
+ params.append("filter", JSON.stringify(query.filter));
850
+ }
851
+ return params.toString();
852
+ }
853
+ function measurePerformance(name, fn) {
854
+ const start = performance.now();
855
+ const result = fn();
856
+ const end = performance.now();
857
+ if (process.env.NODE_ENV === "development") {
858
+ console.log(`\u23F1\uFE0F ${name}: ${(end - start).toFixed(2)}ms`);
859
+ }
860
+ return { result, duration: end - start };
861
+ }
862
+
863
+ // src/content/index.ts
864
+ var ContentEngine = class {
865
+ constructor(config) {
866
+ this.config = config;
867
+ this.isServer = typeof window === "undefined";
868
+ this.localCache = new LocalCacheProxy();
869
+ this.memoryCache = new MemoryCache({
870
+ maxSize: 500,
871
+ ttl: 5 * 60 * 1e3
872
+ // 5 minutes
873
+ });
874
+ if (!this.isServer) {
875
+ this.browserCache = new BrowserCache(config.projectId);
876
+ }
877
+ this.rateLimiter = new RateLimiter({
878
+ maxRequests: config.debug ? 100 : 50,
879
+ timeWindow: 6e4
880
+ });
881
+ this.backoff = new ExponentialBackoff({
882
+ maxRetries: config.retries || 3,
883
+ baseDelay: 100,
884
+ maxDelay: 5e3,
885
+ jitter: true
886
+ });
887
+ this.requestBatcher = new RequestBatcher(20, 50);
888
+ this.circuitBreaker = new CircuitBreaker();
889
+ this.defaultRevalidate = config.revalidateTime || 60;
890
+ this.cacheStrategy = config.cacheStrategy || "memory";
891
+ if (!this.isServer) {
892
+ window.addEventListener("beforeunload", this.cleanup.bind(this));
893
+ }
894
+ }
895
+ /**
896
+ * Fetch a Single Page with full strategy pipeline
897
+ */
898
+ async getPage(slug, options = {}) {
899
+ const { result, duration } = measurePerformance(
900
+ `getPage("${slug}")`,
901
+ () => this._getPage(slug, options)
902
+ );
903
+ if (this.config.debug && duration > 100) {
904
+ console.warn(
905
+ `[NexusHub] \u26A0\uFE0F getPage("${slug}") took ${duration.toFixed(2)}ms`
906
+ );
907
+ }
908
+ return result;
909
+ }
910
+ async _getPage(slug, options = {}) {
911
+ validateSlug(slug);
912
+ const {
913
+ revalidate = this.defaultRevalidate,
914
+ tags = [],
915
+ forceRefresh = false,
916
+ includeMetadata = false
917
+ } = options;
918
+ const cacheKey = `page:${slug}`;
919
+ const cached = await this.checkCaches(
920
+ cacheKey,
921
+ forceRefresh,
922
+ includeMetadata
923
+ );
924
+ if (cached) {
925
+ if (this.config.debug) console.log(`[NexusHub] \u26A1 Cache hit: ${slug}`);
926
+ return includeMetadata ? cached : cached.data;
927
+ }
928
+ if (this.circuitBreaker.isOpen()) {
929
+ throw new Error(`[NexusHub] Circuit open. API is unavailable.`);
930
+ }
931
+ try {
932
+ await this.rateLimiter.checkLimit();
933
+ const data = await this.backoff.execute(
934
+ async () => {
935
+ return this.fetchPage(
936
+ slug,
937
+ cacheKey,
938
+ tags,
939
+ revalidate,
940
+ forceRefresh
941
+ );
942
+ },
943
+ (attempt, delay, error) => {
944
+ if (this.config.debug) {
945
+ console.log(
946
+ `[NexusHub] \u{1F504} Retry ${attempt} for '${slug}' after ${delay}ms: ${error.message}`
947
+ );
948
+ }
949
+ }
950
+ );
951
+ this.circuitBreaker.recordSuccess();
952
+ return includeMetadata ? data : data.data;
953
+ } catch (error) {
954
+ this.circuitBreaker.recordFailure();
955
+ const staleCache = this.memoryCache.get(cacheKey);
956
+ if (staleCache && !forceRefresh) {
957
+ console.warn(`[NexusHub] \u26A0\uFE0F Serving stale content for '${slug}'`);
958
+ return includeMetadata ? staleCache : staleCache.data;
959
+ }
960
+ throw this.normalizeError(error, `Failed to fetch page '${slug}'`);
961
+ }
962
+ }
963
+ /**
964
+ * Fetch a Collection (Optimized)
965
+ */
966
+ async getCollection(collectionId, query = {}, options = {}) {
967
+ const { result, duration } = measurePerformance(
968
+ `getCollection("${collectionId}")`,
969
+ () => this._getCollection(collectionId, query, options)
970
+ );
971
+ if (this.config.debug && duration > 100) {
972
+ console.warn(
973
+ `[NexusHub] \u26A0\uFE0F getCollection("${collectionId}") took ${duration.toFixed(2)}ms`
974
+ );
975
+ }
976
+ return result;
977
+ }
978
+ async _getCollection(collectionId, query = {}, options = {}) {
979
+ const normalizedQuery = normalizeQuery(query);
980
+ const {
981
+ revalidate = this.defaultRevalidate,
982
+ tags = [],
983
+ forceRefresh = false,
984
+ includeMetadata = false
985
+ } = options;
986
+ const queryString = buildQueryString(normalizedQuery);
987
+ const cacheKey = `collection:${collectionId}:${queryString}`;
988
+ const cached = await this.checkCaches(
989
+ cacheKey,
990
+ forceRefresh,
991
+ includeMetadata
992
+ );
993
+ if (cached) {
994
+ if (this.config.debug) {
995
+ console.log(
996
+ `[NexusHub] \u26A1 Served collection '${collectionId}' from memory cache.`
997
+ );
998
+ }
999
+ return includeMetadata ? cached : cached.data;
1000
+ }
1001
+ if (!forceRefresh && process.env.NODE_ENV === "development") {
1002
+ const localCollection = await this.localCache.getCollection(collectionId);
1003
+ if (localCollection) {
1004
+ const result = this.applyLocalQuery(
1005
+ localCollection,
1006
+ normalizedQuery
1007
+ );
1008
+ if (this.config.debug) {
1009
+ console.log(
1010
+ `[NexusHub] \u{1F4C1} Served collection '${collectionId}' from local cache.`
1011
+ );
1012
+ }
1013
+ this.memoryCache.set(cacheKey, result, {
1014
+ tags: [...tags, CacheTags.collection(collectionId)],
1015
+ revalidate
1016
+ });
1017
+ return result;
1018
+ }
1019
+ }
1020
+ if (this.circuitBreaker.isOpen()) throw new Error("Circuit open");
1021
+ try {
1022
+ await this.rateLimiter.checkLimit();
1023
+ const result = await this.backoff.execute(async () => {
1024
+ return this.fetchCollection(
1025
+ collectionId,
1026
+ normalizedQuery,
1027
+ cacheKey,
1028
+ tags,
1029
+ revalidate
1030
+ );
1031
+ });
1032
+ this.circuitBreaker.recordSuccess();
1033
+ return includeMetadata ? result : result.data;
1034
+ } catch (error) {
1035
+ this.circuitBreaker.recordFailure();
1036
+ const staleCache = this.memoryCache.get(cacheKey);
1037
+ if (staleCache && !forceRefresh) {
1038
+ console.warn(
1039
+ `[NexusHub] \u26A0\uFE0F Using stale cache for collection '${collectionId}'`
1040
+ );
1041
+ return includeMetadata ? staleCache : staleCache.data;
1042
+ }
1043
+ throw this.normalizeError(
1044
+ error,
1045
+ `Failed to fetch collection '${collectionId}'`
1046
+ );
1047
+ }
1048
+ }
1049
+ /**
1050
+ * Fetch Global Settings with nested includes support
1051
+ */
1052
+ async getGlobals(options = {}) {
1053
+ const {
1054
+ include = [],
1055
+ revalidate = this.defaultRevalidate,
1056
+ forceRefresh = false
1057
+ } = options;
1058
+ const cacheKey = `globals:${include.join(",")}`;
1059
+ if (!forceRefresh && this.cacheStrategy === "memory") {
1060
+ const cached = this.memoryCache.get(cacheKey);
1061
+ if (cached && this.isCacheValid(cached.metadata)) {
1062
+ if (this.config.debug)
1063
+ console.log("[NexusHub] \u26A1 Served globals from memory cache.");
1064
+ return cached.data;
1065
+ }
1066
+ }
1067
+ if (!forceRefresh && !this.isServer && this.cacheStrategy === "localStorage" && this.browserCache) {
1068
+ const cached = this.browserCache.get(cacheKey);
1069
+ if (cached) {
1070
+ return cached;
1071
+ }
1072
+ }
1073
+ if (!forceRefresh && process.env.NODE_ENV === "development") {
1074
+ const localGlobals = this.localCache.getGlobals();
1075
+ if (localGlobals) {
1076
+ this.memoryCache.set(cacheKey, localGlobals, {
1077
+ tags: [CacheTags.global],
1078
+ revalidate
1079
+ });
1080
+ return localGlobals;
1081
+ }
1082
+ }
1083
+ try {
1084
+ await this.rateLimiter.checkLimit();
1085
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/globals`;
1086
+ const params = include.length > 0 ? `?include=${include.join(",")}` : "";
1087
+ const res = await this.fetchWithTimeout(`${url}${params}`, {
1088
+ method: "GET",
1089
+ headers: this.getHeaders()
1090
+ });
1091
+ if (!res.ok) {
1092
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
1093
+ }
1094
+ const json = await res.json();
1095
+ const data = json.data || json;
1096
+ this.writeCache(cacheKey, data, {
1097
+ revalidate,
1098
+ tags: [CacheTags.project(this.config.projectId), CacheTags.global]
1099
+ });
1100
+ return data;
1101
+ } catch (error) {
1102
+ const staleCache = this.memoryCache.get(cacheKey);
1103
+ if (staleCache && !forceRefresh) {
1104
+ console.warn("[NexusHub] \u26A0\uFE0F Using stale cache for globals");
1105
+ return staleCache.data;
1106
+ }
1107
+ throw this.normalizeError(error, "Failed to fetch globals");
1108
+ }
1109
+ }
1110
+ /**
1111
+ * Get a single item from a collection (Uses Request Batching)
1112
+ * If you call this 10 times in a loop, it sends 1 HTTP request.
1113
+ */
1114
+ async getItem(collectionId, itemId, options = {}) {
1115
+ const cacheKey = `item:${collectionId}:${itemId}`;
1116
+ if (this.cacheStrategy === "memory") {
1117
+ const cached = this.memoryCache.get(cacheKey);
1118
+ if (cached && this.isCacheValid(cached.metadata)) {
1119
+ if (this.config.debug) {
1120
+ console.log(`[NexusHub] \u26A1 Served item '${itemId}' from cache.`);
1121
+ }
1122
+ return cached.data;
1123
+ }
1124
+ }
1125
+ return this.requestBatcher.schedule(cacheKey, async () => {
1126
+ const params = new URLSearchParams();
1127
+ if (options.include?.length) {
1128
+ params.append("include", options.include.join(","));
1129
+ }
1130
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/collection/${collectionId}/${itemId}?${params}`;
1131
+ const res = await this.fetchWithTimeout(url, {
1132
+ method: "GET",
1133
+ headers: this.getHeaders()
1134
+ });
1135
+ if (!res.ok) {
1136
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
1137
+ }
1138
+ const json = await res.json();
1139
+ const data = json.data || json;
1140
+ this.writeCache(cacheKey, data, {
1141
+ revalidate: options.revalidate || this.defaultRevalidate,
1142
+ tags: [
1143
+ CacheTags.project(this.config.projectId),
1144
+ CacheTags.collection(collectionId),
1145
+ `item_${itemId}`,
1146
+ ...options.tags || []
1147
+ ]
1148
+ });
1149
+ return data;
1150
+ });
1151
+ }
1152
+ /**
1153
+ * Search across collections
1154
+ */
1155
+ async search(query, options = {}) {
1156
+ const params = new URLSearchParams({
1157
+ q: query,
1158
+ limit: (options.limit || 20).toString()
1159
+ });
1160
+ if (options.collections?.length) {
1161
+ params.append("collections", options.collections.join(","));
1162
+ }
1163
+ if (options.fields?.length) {
1164
+ params.append("fields", options.fields.join(","));
1165
+ }
1166
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/search?${params}`;
1167
+ const res = await this.fetchWithTimeout(url, {
1168
+ method: "GET",
1169
+ headers: this.getHeaders()
1170
+ });
1171
+ if (!res.ok) {
1172
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
1173
+ }
1174
+ return await res.json();
1175
+ }
1176
+ /**
1177
+ * Prefetch content for better performance
1178
+ */
1179
+ async prefetch(urls) {
1180
+ if (typeof window !== "undefined" && "requestIdleCallback" in window) {
1181
+ requestIdleCallback(async () => {
1182
+ await Promise.allSettled(
1183
+ urls.map((url) => fetch(url, { priority: "low" }))
1184
+ );
1185
+ });
1186
+ }
1187
+ }
1188
+ /**
1189
+ * Robust Real-time Subscriptions (SSE) with Auto-Reconnect
1190
+ */
1191
+ subscribeToUpdates(callback) {
1192
+ if (this.isServer || typeof EventSource === "undefined") {
1193
+ console.warn("[NexusHub] EventSource not supported in this environment");
1194
+ return () => {
1195
+ };
1196
+ }
1197
+ let eventSource = null;
1198
+ let retryCount = 0;
1199
+ let isClosed = false;
1200
+ const connect = () => {
1201
+ if (isClosed) return;
1202
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/updates?key=${this.config.apiKey}`;
1203
+ eventSource = new EventSource(url);
1204
+ eventSource.onopen = () => {
1205
+ retryCount = 0;
1206
+ if (this.config.debug)
1207
+ console.log("[NexusHub] \u{1F7E2} Real-time stream connected");
1208
+ };
1209
+ eventSource.onmessage = (event) => {
1210
+ try {
1211
+ const data = JSON.parse(event.data);
1212
+ if (data.type === "content.updated" && data.slug) {
1213
+ this.invalidateCache([CacheTags.content(data.slug)]);
1214
+ }
1215
+ if (data.type === "collection.updated") {
1216
+ this.invalidateCache([CacheTags.collection(data.collectionId)]);
1217
+ }
1218
+ callback(data);
1219
+ } catch (e) {
1220
+ console.error("[NexusHub] SSE Parse Error", e);
1221
+ }
1222
+ };
1223
+ eventSource.onerror = () => {
1224
+ eventSource?.close();
1225
+ if (isClosed) return;
1226
+ const timeout = Math.min(1e3 * Math.pow(2, retryCount), 1e4);
1227
+ retryCount++;
1228
+ console.warn(
1229
+ `[NexusHub] \u{1F534} Stream disconnected. Reconnecting in ${timeout}ms...`
1230
+ );
1231
+ setTimeout(connect, timeout);
1232
+ };
1233
+ };
1234
+ connect();
1235
+ return () => {
1236
+ isClosed = true;
1237
+ eventSource?.close();
1238
+ };
1239
+ }
1240
+ // --- CACHE MANAGEMENT ---
1241
+ /**
1242
+ * Check all caches in order of speed
1243
+ */
1244
+ async checkCaches(key, forceRefresh, includeMetadata) {
1245
+ if (forceRefresh) return null;
1246
+ if (this.cacheStrategy === "memory") {
1247
+ const cached = this.memoryCache.get(key);
1248
+ if (cached && this.isCacheValid(cached.metadata)) {
1249
+ return cached;
1250
+ }
1251
+ }
1252
+ if (!this.isServer && this.cacheStrategy === "localStorage" && this.browserCache) {
1253
+ const cached = this.browserCache.get(key);
1254
+ if (cached) {
1255
+ return {
1256
+ data: cached,
1257
+ metadata: {
1258
+ timestamp: 0,
1259
+ expiresAt: Infinity,
1260
+ tags: [],
1261
+ etag: void 0
1262
+ }
1263
+ };
1264
+ }
1265
+ }
1266
+ if (process.env.NODE_ENV === "development") {
1267
+ if (key.startsWith("page:")) {
1268
+ const slug = key.split(":")[1];
1269
+ const local = await this.localCache.getPage(slug);
1270
+ if (local) {
1271
+ return {
1272
+ data: local,
1273
+ metadata: {
1274
+ timestamp: 0,
1275
+ expiresAt: Infinity,
1276
+ tags: [],
1277
+ etag: void 0
1278
+ }
1279
+ };
1280
+ }
1281
+ }
1282
+ }
1283
+ return null;
1284
+ }
1285
+ writeCache(key, data, options) {
1286
+ if (this.cacheStrategy === "memory") {
1287
+ this.memoryCache.set(key, data, {
1288
+ tags: options.tags,
1289
+ revalidate: options.revalidate
1290
+ });
1291
+ }
1292
+ if (!this.isServer && this.cacheStrategy === "localStorage" && this.browserCache) {
1293
+ this.browserCache.set(key, data, options.revalidate * 1e3);
1294
+ }
1295
+ }
1296
+ // packages/client-sdk/src/content/index.ts
1297
+ /**
1298
+ * ⚡ THE PULSE: Next.js Cache Revalidation Receiver
1299
+ * Used in app/api/nexus-revalidate/route.ts to handle instant updates from the NexusHub backend.
1300
+ *
1301
+ * @param req The incoming Request object from Next.js
1302
+ * @param revalidateFn The revalidateTag function imported from 'next/cache'
1303
+ */
1304
+ async handleRevalidation(req, revalidateFn) {
1305
+ try {
1306
+ if (!req.body) {
1307
+ return { success: false, message: "Missing Pulse Payload" };
1308
+ }
1309
+ const body = await req.json();
1310
+ const { secret, tag } = body;
1311
+ if (!secret || secret !== this.config.projectId) {
1312
+ if (this.config.debug) {
1313
+ console.warn(`[NexusHub] \u26A0\uFE0F Blocked unauthorized Pulse request.`);
1314
+ }
1315
+ return { success: false, message: "Invalid Pulse Signature" };
1316
+ }
1317
+ const targetTag = tag || "content_all";
1318
+ revalidateFn(targetTag);
1319
+ this.invalidateCache([targetTag]);
1320
+ if (this.config.debug) {
1321
+ console.log(
1322
+ `[NexusHub] \u26A1 Pulse Received: Successfully revalidated tag [${targetTag}]`
1323
+ );
1324
+ }
1325
+ return { success: true, now: Date.now() };
1326
+ } catch (e) {
1327
+ if (this.config.debug) {
1328
+ console.error(`[NexusHub] \u274C Pulse Processing Error:`, e.message);
1329
+ }
1330
+ return {
1331
+ success: false,
1332
+ message: "Malformed Pulse Payload or Processing Error"
1333
+ };
1334
+ }
1335
+ }
1336
+ /**
1337
+ * Invalidate cache by tags
1338
+ */
1339
+ invalidateCache(tags) {
1340
+ this.memoryCache.invalidateByTags(tags);
1341
+ if (this.config.debug) {
1342
+ console.log(
1343
+ `[NexusHub] \u267B\uFE0F Invalidated cache for tags: ${tags.join(", ")}`
1344
+ );
1345
+ }
1346
+ }
1347
+ /**
1348
+ * Clear all caches
1349
+ */
1350
+ clearCache() {
1351
+ this.memoryCache.clear();
1352
+ if (this.browserCache) {
1353
+ this.browserCache.clear();
1354
+ }
1355
+ if (this.config.debug) {
1356
+ console.log("[NexusHub] \u{1F9F9} Cleared all caches");
1357
+ }
1358
+ }
1359
+ /**
1360
+ * Get cache statistics
1361
+ */
1362
+ getCacheStats() {
1363
+ const stats = {
1364
+ memory: this.memoryCache.getStats(),
1365
+ local: { loaded: this.localCache.isLoaded() }
1366
+ };
1367
+ if (this.browserCache) {
1368
+ stats.browser = { size: 0 };
1369
+ }
1370
+ return stats;
1371
+ }
1372
+ // --- REQUEST METHODS ---
1373
+ async fetchPage(slug, cacheKey, tags, revalidate, forceRefresh) {
1374
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/page/${slug}`;
1375
+ if (this.config.debug) {
1376
+ console.log(`[NexusHub] \u{1F310} Fetching: ${url}`);
1377
+ }
1378
+ const res = await this.fetchWithTimeout(url, {
1379
+ method: "GET",
1380
+ headers: this.getHeaders(),
1381
+ tags,
1382
+ revalidate
1383
+ });
1384
+ if (!res.ok) {
1385
+ if (res.status === 404) {
1386
+ throw new Error(
1387
+ `Page '${slug}' not found. Check your Dashboard or Seed data.`
1388
+ );
1389
+ }
1390
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
1391
+ }
1392
+ const json = await res.json();
1393
+ const etag = res.headers.get("etag");
1394
+ const cacheEntry = {
1395
+ data: json.data,
1396
+ metadata: {
1397
+ timestamp: Date.now(),
1398
+ etag: etag || void 0,
1399
+ expiresAt: Date.now() + revalidate * 1e3,
1400
+ tags: [...tags, CacheTags.content(slug)]
1401
+ }
1402
+ };
1403
+ this.writeCache(cacheKey, cacheEntry.data, {
1404
+ revalidate,
1405
+ tags: [
1406
+ CacheTags.project(this.config.projectId),
1407
+ CacheTags.content(slug),
1408
+ ...tags
1409
+ ]
1410
+ });
1411
+ return cacheEntry;
1412
+ }
1413
+ async fetchCollection(collectionId, query, cacheKey, tags, revalidate) {
1414
+ const params = buildQueryString(query);
1415
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/collection/${collectionId}?${params}`;
1416
+ if (this.config.debug) {
1417
+ console.log(`[NexusHub] \u{1F310} Fetching Collection: ${url}`);
1418
+ }
1419
+ const res = await this.fetchWithTimeout(url, {
1420
+ method: "GET",
1421
+ headers: this.getHeaders(),
1422
+ tags,
1423
+ revalidate
1424
+ });
1425
+ if (!res.ok) {
1426
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
1427
+ }
1428
+ const json = await res.json();
1429
+ const etag = res.headers.get("etag");
1430
+ const cacheEntry = {
1431
+ data: json,
1432
+ metadata: {
1433
+ timestamp: Date.now(),
1434
+ etag: etag || void 0,
1435
+ expiresAt: Date.now() + revalidate * 1e3,
1436
+ tags: [...tags, CacheTags.collection(collectionId)]
1437
+ }
1438
+ };
1439
+ this.writeCache(cacheKey, cacheEntry.data, {
1440
+ revalidate,
1441
+ tags: [
1442
+ CacheTags.project(this.config.projectId),
1443
+ CacheTags.collection(collectionId),
1444
+ ...tags
1445
+ ]
1446
+ });
1447
+ return cacheEntry;
1448
+ }
1449
+ // --- HELPER METHODS ---
1450
+ applyLocalQuery(items, query) {
1451
+ let filtered = [...items];
1452
+ if (query.search) {
1453
+ const searchLower = query.search.toLowerCase();
1454
+ filtered = filtered.filter(
1455
+ (item) => JSON.stringify(item).toLowerCase().includes(searchLower)
1456
+ );
1457
+ }
1458
+ if (query.filter) {
1459
+ filtered = filtered.filter((item) => {
1460
+ return Object.entries(query.filter).every(([key, value]) => {
1461
+ const itemValue = item[key];
1462
+ if (itemValue === void 0) return false;
1463
+ if (Array.isArray(value)) {
1464
+ return value.includes(itemValue);
1465
+ }
1466
+ return itemValue === value;
1467
+ });
1468
+ });
1469
+ }
1470
+ if (query.sort) {
1471
+ filtered.sort((a, b) => {
1472
+ const aVal = a[query.sort];
1473
+ const bVal = b[query.sort];
1474
+ const order = query.order === "asc" ? 1 : -1;
1475
+ if (aVal < bVal) return -1 * order;
1476
+ if (aVal > bVal) return 1 * order;
1477
+ return 0;
1478
+ });
1479
+ }
1480
+ const page = query.page || 1;
1481
+ const limit = query.limit || 10;
1482
+ const start = (page - 1) * limit;
1483
+ const end = start + limit;
1484
+ const total = filtered.length;
1485
+ return {
1486
+ items: filtered.slice(start, end),
1487
+ total,
1488
+ page,
1489
+ limit,
1490
+ totalPages: Math.ceil(total / limit),
1491
+ hasNext: end < total,
1492
+ hasPrev: start > 0
1493
+ };
1494
+ }
1495
+ async fetchWithTimeout(url, options = {}) {
1496
+ const {
1497
+ timeout = this.config.timeout || 1e4,
1498
+ tags = [],
1499
+ revalidate,
1500
+ ...fetchOptions
1501
+ } = options;
1502
+ const controller = new AbortController();
1503
+ const id = setTimeout(() => controller.abort(), timeout);
1504
+ const nextConfig = this.isServer ? { next: { tags, revalidate } } : {};
1505
+ try {
1506
+ const response = await fetch(url, {
1507
+ ...fetchOptions,
1508
+ ...nextConfig,
1509
+ // Inject Next.js tags
1510
+ signal: controller.signal
1511
+ });
1512
+ clearTimeout(id);
1513
+ return response;
1514
+ } catch (error) {
1515
+ clearTimeout(id);
1516
+ throw error;
1517
+ }
1518
+ }
1519
+ getHeaders() {
1520
+ const headers = {
1521
+ "Content-Type": "application/json",
1522
+ "X-Nexus-Client": "client-sdk/1.0.0",
1523
+ "X-Nexus-Project": this.config.projectId
1524
+ };
1525
+ if (this.config.apiKey) {
1526
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
1527
+ }
1528
+ return headers;
1529
+ }
1530
+ isCacheValid(metadata) {
1531
+ return Date.now() < metadata.expiresAt;
1532
+ }
1533
+ normalizeError(error, context) {
1534
+ if (error instanceof Error) {
1535
+ if (error.name === "AbortError") {
1536
+ return new Error(`${context}: Request timeout`);
1537
+ }
1538
+ return error;
1539
+ }
1540
+ return new Error(`${context}: ${String(error)}`);
1541
+ }
1542
+ /**
1543
+ * Cancel ongoing requests
1544
+ */
1545
+ cancelRequests() {
1546
+ if (this.abortController) {
1547
+ this.abortController.abort();
1548
+ this.abortController = new AbortController();
1549
+ }
1550
+ }
1551
+ /**
1552
+ * Cleanup resources
1553
+ */
1554
+ cleanup() {
1555
+ this.cancelRequests();
1556
+ if (!this.isServer) {
1557
+ window.removeEventListener("beforeunload", this.cleanup.bind(this));
1558
+ }
1559
+ }
1560
+ };
1561
+
1562
+ // src/analytics/fingerprint.ts
1563
+ var cachedEntropy = null;
1564
+ var getDeviceEntropy = async () => {
1565
+ if (cachedEntropy) return cachedEntropy;
1566
+ if (typeof window === "undefined") return {};
1567
+ const nav = window.navigator;
1568
+ cachedEntropy = {
1569
+ screen_resolution: `${window.screen.width}x${window.screen.height}`,
1570
+ color_depth: window.screen.colorDepth,
1571
+ pixel_ratio: window.devicePixelRatio || 1,
1572
+ hardware_concurrency: nav.hardwareConcurrency,
1573
+ device_memory: nav.deviceMemory,
1574
+ // Chrome/Edge only
1575
+ timezone_offset: (/* @__PURE__ */ new Date()).getTimezoneOffset(),
1576
+ platform: nav.platform,
1577
+ language: nav.language,
1578
+ touch_support: "ontouchstart" in window || nav.maxTouchPoints > 0,
1579
+ canvas_hash: await generateCanvasHash()
1580
+ };
1581
+ return cachedEntropy;
1582
+ };
1583
+ var generateCanvasHash = async () => {
1584
+ try {
1585
+ const canvas = document.createElement("canvas");
1586
+ const ctx = canvas.getContext("2d");
1587
+ if (!ctx) return "";
1588
+ canvas.width = 200;
1589
+ canvas.height = 50;
1590
+ ctx.textBaseline = "top";
1591
+ ctx.font = '16px "Arial"';
1592
+ ctx.textBaseline = "alphabetic";
1593
+ ctx.fillStyle = "#f60";
1594
+ ctx.fillRect(125, 1, 62, 20);
1595
+ ctx.fillStyle = "#069";
1596
+ ctx.fillText("NexusHub Rocks! <canvas> 1.0", 2, 15);
1597
+ ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
1598
+ ctx.fillText("NexusHub Rocks! <canvas> 1.0", 4, 17);
1599
+ const dataUrl = canvas.toDataURL();
1600
+ let hash = 0;
1601
+ for (let i = 0; i < dataUrl.length; i++) {
1602
+ const char = dataUrl.charCodeAt(i);
1603
+ hash = (hash << 5) - hash + char;
1604
+ hash = hash & hash;
1605
+ }
1606
+ return hash.toString(16);
1607
+ } catch {
1608
+ return "";
1609
+ }
1610
+ };
1611
+ var getVisitorId = async () => {
1612
+ if (typeof window === "undefined") return "server_visitor";
1613
+ const STORAGE_KEY = "nexus_vid";
1614
+ let vid = localStorage.getItem(STORAGE_KEY);
1615
+ if (!vid) {
1616
+ const entropy = await getDeviceEntropy();
1617
+ const random = Math.random().toString(36).substring(2, 15);
1618
+ const timestamp = Date.now().toString(36);
1619
+ const fingerprint = [
1620
+ entropy.screen_resolution,
1621
+ entropy.hardware_concurrency,
1622
+ entropy.timezone_offset,
1623
+ entropy.platform,
1624
+ entropy.canvas_hash
1625
+ ].join("|");
1626
+ let hash = 0;
1627
+ for (let i = 0; i < fingerprint.length; i++) {
1628
+ hash = (hash << 5) - hash + fingerprint.charCodeAt(i);
1629
+ hash |= 0;
1630
+ }
1631
+ vid = `vis_${hash.toString(16)}_${timestamp}_${random}`;
1632
+ localStorage.setItem(STORAGE_KEY, vid);
1633
+ }
1634
+ return vid;
1635
+ };
1636
+
1637
+ // src/analytics/vitals.ts
1638
+ import { onCLS, onLCP, onTTFB, onINP, onFCP } from "web-vitals";
1639
+ var METRIC_KEY_MAP = {
1640
+ CLS: "cls",
1641
+ LCP: "lcp",
1642
+ INP: "inp",
1643
+ TTFB: "ttfb",
1644
+ FCP: "fcp"
1645
+ };
1646
+ var VitalsCollector = class {
1647
+ constructor() {
1648
+ this.metrics = {};
1649
+ this.hasUpdates = false;
1650
+ if (typeof window !== "undefined") {
1651
+ this.init();
1652
+ }
1653
+ }
1654
+ init() {
1655
+ const recordMetric = (metric) => {
1656
+ const key = METRIC_KEY_MAP[metric.name];
1657
+ this.metrics[key] = metric.value;
1658
+ this.hasUpdates = true;
1659
+ };
1660
+ onCLS(recordMetric);
1661
+ onLCP(recordMetric);
1662
+ onTTFB(recordMetric);
1663
+ onINP(recordMetric);
1664
+ onFCP(recordMetric);
1665
+ const navEntry = performance.getEntriesByType("navigation")[0];
1666
+ if (navEntry) {
1667
+ this.metrics.navigation_timing = {
1668
+ dns_lookup: navEntry.domainLookupEnd - navEntry.domainLookupStart,
1669
+ tcp_connect: navEntry.connectEnd - navEntry.connectStart,
1670
+ request_time: navEntry.responseEnd - navEntry.requestStart,
1671
+ dom_load: navEntry.domComplete - navEntry.domInteractive,
1672
+ // NEW: raw fields matching Rust NavigationTiming struct
1673
+ domain_lookup_start: navEntry.domainLookupStart,
1674
+ domain_lookup_end: navEntry.domainLookupEnd,
1675
+ connect_start: navEntry.connectStart,
1676
+ connect_end: navEntry.connectEnd,
1677
+ secure_connection_start: navEntry.secureConnectionStart > 0 ? navEntry.secureConnectionStart : void 0
1678
+ };
1679
+ this.hasUpdates = true;
1680
+ }
1681
+ const resourceEntries = performance.getEntriesByType(
1682
+ "resource"
1683
+ );
1684
+ if (resourceEntries.length > 0) {
1685
+ this.metrics.resources = resourceEntries.filter((r) => !r.name.includes("/api/collect")).sort((a, b) => b.duration - a.duration).slice(0, 20).map((r) => ({
1686
+ name: r.name,
1687
+ initiatorType: r.initiatorType,
1688
+ duration: Math.round(r.duration),
1689
+ transferSize: r.transferSize > 0 ? r.transferSize : void 0,
1690
+ encodedBodySize: r.encodedBodySize > 0 ? r.encodedBodySize : void 0,
1691
+ decodedBodySize: r.decodedBodySize > 0 ? r.decodedBodySize : void 0,
1692
+ startTime: Math.round(r.startTime),
1693
+ responseEnd: Math.round(r.responseEnd)
1694
+ }));
1695
+ this.hasUpdates = true;
1696
+ }
1697
+ const mem = performance.memory;
1698
+ if (mem) {
1699
+ this.metrics.memory_usage = {
1700
+ used_js_heap_size: mem.usedJSHeapSize,
1701
+ total_js_heap_size: mem.totalJSHeapSize,
1702
+ js_heap_size_limit: mem.jsHeapSizeLimit
1703
+ };
1704
+ this.hasUpdates = true;
1705
+ }
1706
+ }
1707
+ getMetricsSnapshot() {
1708
+ if (!this.hasUpdates) return null;
1709
+ this.hasUpdates = false;
1710
+ const snapshot = { ...this.metrics };
1711
+ this.metrics.resources = void 0;
1712
+ return snapshot;
1713
+ }
1714
+ };
1715
+ var vitalsCollector = new VitalsCollector();
1716
+ var initVitals = (_tracker) => {
1717
+ if (process.env.NODE_ENV === "development") {
1718
+ console.log("[NexusHub] Web Vitals monitoring active");
1719
+ }
1720
+ };
1721
+
1722
+ // src/analytics/storage.ts
1723
+ var DB_NAME = "NexusHub_Analytics";
1724
+ var STORE_NAME = "events_queue";
1725
+ var DB_VERSION = 2;
1726
+ var MAX_QUEUE_SIZE = 500;
1727
+ var EventStorage = class {
1728
+ constructor() {
1729
+ this.db = null;
1730
+ this.isReady = this.init();
1731
+ }
1732
+ init() {
1733
+ if (typeof window === "undefined" || !window.indexedDB) {
1734
+ return Promise.resolve();
1735
+ }
1736
+ return new Promise((resolve) => {
1737
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
1738
+ request.onerror = () => {
1739
+ console.warn(
1740
+ "[NexusHub] Failed to open IndexedDB. Falling back to memory."
1741
+ );
1742
+ resolve();
1743
+ };
1744
+ request.onsuccess = (event) => {
1745
+ this.db = event.target.result;
1746
+ resolve();
1747
+ };
1748
+ request.onupgradeneeded = (event) => {
1749
+ const db = event.target.result;
1750
+ if (db.objectStoreNames.contains(STORE_NAME)) {
1751
+ db.deleteObjectStore(STORE_NAME);
1752
+ }
1753
+ db.createObjectStore(STORE_NAME, {
1754
+ keyPath: "id",
1755
+ autoIncrement: true
1756
+ });
1757
+ };
1758
+ });
1759
+ }
1760
+ /**
1761
+ * Add an event to the persistent queue.
1762
+ * Evicts the oldest entry if the queue is already at MAX_QUEUE_SIZE.
1763
+ */
1764
+ async enqueue(payload) {
1765
+ await this.isReady;
1766
+ if (!this.db) return;
1767
+ const currentCount = await this.count();
1768
+ if (currentCount >= MAX_QUEUE_SIZE) {
1769
+ const oldest = await this.peek(1);
1770
+ if (oldest.length > 0 && oldest[0].id !== void 0) {
1771
+ await this.remove([oldest[0].id]);
1772
+ }
1773
+ }
1774
+ return new Promise((resolve, reject) => {
1775
+ const transaction = this.db.transaction([STORE_NAME], "readwrite");
1776
+ const store = transaction.objectStore(STORE_NAME);
1777
+ const request = store.add({
1778
+ payload,
1779
+ timestamp: Date.now(),
1780
+ retryCount: 0
1781
+ });
1782
+ request.onsuccess = () => resolve();
1783
+ request.onerror = () => reject(request.error);
1784
+ });
1785
+ }
1786
+ /**
1787
+ * Get a batch of the oldest events without removing them.
1788
+ */
1789
+ async peek(limit = 20) {
1790
+ await this.isReady;
1791
+ if (!this.db) return [];
1792
+ return new Promise((resolve) => {
1793
+ const transaction = this.db.transaction([STORE_NAME], "readonly");
1794
+ const store = transaction.objectStore(STORE_NAME);
1795
+ const request = store.getAll(null, limit);
1796
+ request.onsuccess = () => resolve(request.result);
1797
+ request.onerror = () => resolve([]);
1798
+ });
1799
+ }
1800
+ /**
1801
+ * Remove events by ID after a successful upload.
1802
+ */
1803
+ async remove(ids) {
1804
+ await this.isReady;
1805
+ if (!this.db || ids.length === 0) return;
1806
+ return new Promise((resolve, reject) => {
1807
+ const transaction = this.db.transaction([STORE_NAME], "readwrite");
1808
+ const store = transaction.objectStore(STORE_NAME);
1809
+ transaction.oncomplete = () => resolve();
1810
+ transaction.onerror = () => reject(transaction.error);
1811
+ transaction.onabort = () => reject(new Error("Delete transaction aborted"));
1812
+ ids.forEach((id) => {
1813
+ store.delete(id);
1814
+ });
1815
+ });
1816
+ }
1817
+ /**
1818
+ * Count pending events in the queue.
1819
+ */
1820
+ async count() {
1821
+ await this.isReady;
1822
+ if (!this.db) return 0;
1823
+ return new Promise((resolve) => {
1824
+ const transaction = this.db.transaction([STORE_NAME], "readonly");
1825
+ const store = transaction.objectStore(STORE_NAME);
1826
+ const request = store.count();
1827
+ request.onsuccess = () => resolve(request.result);
1828
+ request.onerror = () => resolve(0);
1829
+ });
1830
+ }
1831
+ };
1832
+ var eventStorage = new EventStorage();
1833
+
1834
+ // src/analytics/tracker.ts
1835
+ var SDK_VERSION = "0.1.0";
1836
+ var safeGetItem = (key) => {
1837
+ try {
1838
+ return localStorage.getItem(key);
1839
+ } catch {
1840
+ return null;
1841
+ }
1842
+ };
1843
+ var safeSetItem = (key, value) => {
1844
+ try {
1845
+ localStorage.setItem(key, value);
1846
+ } catch {
1847
+ }
1848
+ };
1849
+ var safeRemoveItem = (key) => {
1850
+ try {
1851
+ localStorage.removeItem(key);
1852
+ } catch {
1853
+ }
1854
+ };
1855
+ var generateUUID = () => {
1856
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
1857
+ return crypto.randomUUID();
1858
+ }
1859
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
1860
+ const r = Math.random() * 16 | 0;
1861
+ const v = c === "x" ? r : r & 3 | 8;
1862
+ return v.toString(16);
1863
+ });
1864
+ };
1865
+ var Tracker = class {
1866
+ constructor(config) {
1867
+ this.sessionId = "";
1868
+ this.visitorId = "";
1869
+ this.anonymousId = "";
1870
+ this.isFlushing = false;
1871
+ this.config = config;
1872
+ this.endpoint = `${this.config.analyticsUrl}/api/collect`;
1873
+ this.circuitBreaker = new CircuitBreaker();
1874
+ this.sessionStart = Date.now();
1875
+ if (typeof window !== "undefined") {
1876
+ this.initSession();
1877
+ this.startFlushing();
1878
+ }
1879
+ }
1880
+ async initSession() {
1881
+ this.visitorId = await getVisitorId();
1882
+ let anonId = safeGetItem("nexus_anon_id");
1883
+ if (!anonId) {
1884
+ anonId = `anon_${generateUUID().replace(/-/g, "")}`;
1885
+ safeSetItem("nexus_anon_id", anonId);
1886
+ }
1887
+ this.anonymousId = anonId;
1888
+ let sid = safeGetItem("nexus_sid");
1889
+ const lastActivity = safeGetItem("nexus_last_active");
1890
+ const now = Date.now();
1891
+ const SESSION_TIMEOUT = 30 * 60 * 1e3;
1892
+ const isExpired = !sid || !lastActivity || now - parseInt(lastActivity, 10) > SESSION_TIMEOUT;
1893
+ if (isExpired) {
1894
+ const uuid = generateUUID().replace(/-/g, "").substring(0, 16);
1895
+ sid = `sess_${uuid}_${now}`;
1896
+ safeSetItem("nexus_sid", sid);
1897
+ this.sessionStart = now;
1898
+ }
1899
+ safeSetItem("nexus_last_active", now.toString());
1900
+ this.sessionId = sid;
1901
+ }
1902
+ async send(eventType, data = {}, eventName, ecommerce) {
1903
+ if (typeof window === "undefined") return;
1904
+ safeSetItem("nexus_last_active", Date.now().toString());
1905
+ const entropy = await getDeviceEntropy();
1906
+ const perfMetrics = vitalsCollector.getMetricsSnapshot();
1907
+ const utmParams = extractUtmParams(window.location.href);
1908
+ const payload = {
1909
+ projectId: this.config.projectId,
1910
+ sessionId: this.sessionId,
1911
+ visitorId: this.visitorId,
1912
+ anonymousId: this.anonymousId,
1913
+ messageId: generateUUID(),
1914
+ sentAt: (/* @__PURE__ */ new Date()).toISOString(),
1915
+ version: SDK_VERSION,
1916
+ url: window.location.href,
1917
+ referrer: document.referrer,
1918
+ userAgent: window.navigator.userAgent,
1919
+ screenWidth: window.screen.width,
1920
+ screenHeight: window.screen.height,
1921
+ language: window.navigator.language,
1922
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
1923
+ eventType,
1924
+ eventName,
1925
+ eventData: data,
1926
+ ecommerce: ecommerce ?? void 0,
1927
+ performance: perfMetrics || void 0,
1928
+ context: {
1929
+ device: {
1930
+ hardwareConcurrency: entropy.hardware_concurrency,
1931
+ deviceMemory: entropy.device_memory,
1932
+ pixelRatio: entropy.pixel_ratio,
1933
+ canvasFingerprint: entropy.canvas_hash,
1934
+ platform: entropy.platform
1935
+ },
1936
+ visitorIdLocal: this.visitorId,
1937
+ utm: utmParams
1938
+ },
1939
+ clientTimestamp: (/* @__PURE__ */ new Date()).toISOString()
1940
+ };
1941
+ await eventStorage.enqueue(payload);
1942
+ const count = await eventStorage.count();
1943
+ if (count >= 10 || eventType === "purchase" || eventType === "identify") {
1944
+ this.flushQueue();
1945
+ }
1946
+ }
1947
+ startFlushing() {
1948
+ this.flushInterval = setInterval(() => this.flushQueue(), 5e3);
1949
+ window.addEventListener("visibilitychange", () => {
1950
+ if (document.visibilityState === "hidden") this.flushQueue(true);
1951
+ });
1952
+ }
1953
+ async flushQueue(useBeacon = false) {
1954
+ if (this.isFlushing) return;
1955
+ if (this.circuitBreaker.isOpen()) return;
1956
+ this.isFlushing = true;
1957
+ try {
1958
+ const storedEvents = await eventStorage.peek(20);
1959
+ if (storedEvents.length === 0) {
1960
+ this.isFlushing = false;
1961
+ return;
1962
+ }
1963
+ const payloads = storedEvents.map((e) => e.payload);
1964
+ const promises = payloads.map(
1965
+ (event) => fetch(this.endpoint, {
1966
+ method: "POST",
1967
+ headers: {
1968
+ "Content-Type": "application/json",
1969
+ Authorization: `Bearer ${this.config.apiKey}`
1970
+ },
1971
+ body: JSON.stringify(event),
1972
+ keepalive: useBeacon
1973
+ })
1974
+ );
1975
+ const results = await Promise.allSettled(promises);
1976
+ const successIds = [];
1977
+ let failureCount = 0;
1978
+ results.forEach((res, index) => {
1979
+ if (res.status === "fulfilled" && res.value.ok) {
1980
+ successIds.push(storedEvents[index].id);
1981
+ } else {
1982
+ failureCount++;
1983
+ }
1984
+ });
1985
+ if (successIds.length > 0) {
1986
+ await eventStorage.remove(successIds);
1987
+ this.circuitBreaker.recordSuccess();
1988
+ }
1989
+ if (failureCount > 0) {
1990
+ this.circuitBreaker.recordFailure();
1991
+ }
1992
+ } catch (err) {
1993
+ console.error("[NexusHub] Network Error:", err);
1994
+ this.circuitBreaker.recordFailure();
1995
+ } finally {
1996
+ this.isFlushing = false;
1997
+ if (!this.circuitBreaker.isOpen() && await eventStorage.count() > 0) {
1998
+ setTimeout(() => this.flushQueue(), 100);
1999
+ }
2000
+ }
2001
+ }
2002
+ getSession() {
2003
+ return this.sessionId;
2004
+ }
2005
+ getVisitorId() {
2006
+ return this.visitorId;
2007
+ }
2008
+ getAnonymousId() {
2009
+ return this.anonymousId;
2010
+ }
2011
+ getSessionDuration() {
2012
+ return Date.now() - this.sessionStart;
2013
+ }
2014
+ clearIdentity() {
2015
+ safeRemoveItem("nexus_anon_id");
2016
+ this.anonymousId = "";
2017
+ }
2018
+ stop() {
2019
+ if (this.flushInterval) {
2020
+ clearInterval(this.flushInterval);
2021
+ }
2022
+ this.flushQueue(true);
2023
+ }
2024
+ };
2025
+ function extractUtmParams(url) {
2026
+ try {
2027
+ const params = new URL(url).searchParams;
2028
+ const utmKeys = [
2029
+ "utm_source",
2030
+ "utm_medium",
2031
+ "utm_campaign",
2032
+ "utm_term",
2033
+ "utm_content"
2034
+ ];
2035
+ const result = {};
2036
+ utmKeys.forEach((key) => {
2037
+ const val = params.get(key);
2038
+ if (val) result[key] = val;
2039
+ });
2040
+ return result;
2041
+ } catch {
2042
+ return {};
2043
+ }
2044
+ }
2045
+
2046
+ // src/analytics/index.ts
2047
+ var safeRemoveItem2 = (key) => {
2048
+ try {
2049
+ localStorage.removeItem(key);
2050
+ } catch {
2051
+ }
2052
+ };
2053
+ var AnalyticsEngine = class {
2054
+ constructor(config) {
2055
+ this.cleanupFns = [];
2056
+ this.isInitialized = false;
2057
+ this.maxScrollDepth = 0;
2058
+ this.scrollThresholdsFired = /* @__PURE__ */ new Set();
2059
+ this.lastPath = typeof window !== "undefined" ? window.location.pathname : "";
2060
+ this.clickBuffer = [];
2061
+ this.tracker = new Tracker(config);
2062
+ }
2063
+ start() {
2064
+ if (this.isInitialized || typeof window === "undefined") return;
2065
+ this.isInitialized = true;
2066
+ this.pageView();
2067
+ initVitals(this.tracker);
2068
+ this.setupClickTracking();
2069
+ this.setupFormTracking();
2070
+ this.setupRouteTracking();
2071
+ this.setupShareTracking();
2072
+ this.setupScrollTracking();
2073
+ this.setupOutboundTracking();
2074
+ this.setupVideoTracking();
2075
+ this.setupErrorTracking();
2076
+ if (process.env.NODE_ENV === "development") {
2077
+ console.log("[NexusHub] \u{1F680} Analytics Engine Started");
2078
+ }
2079
+ }
2080
+ pageView(customReferrer) {
2081
+ if (typeof window === "undefined") return;
2082
+ const currentPath = window.location.pathname;
2083
+ this.maxScrollDepth = 0;
2084
+ this.scrollThresholdsFired.clear();
2085
+ this.tracker.send("page_view", {
2086
+ path: currentPath,
2087
+ search: window.location.search,
2088
+ title: document.title,
2089
+ timezone_offset: (/* @__PURE__ */ new Date()).getTimezoneOffset(),
2090
+ referrer: customReferrer || (this.lastPath !== currentPath ? this.lastPath : document.referrer)
2091
+ });
2092
+ this.lastPath = currentPath;
2093
+ }
2094
+ setupShareTracking() {
2095
+ if (typeof window === "undefined") return;
2096
+ const copyHandler = () => {
2097
+ this.tracker.send("social_share", {
2098
+ method: "clipboard_copy",
2099
+ url: window.location.href
2100
+ });
2101
+ };
2102
+ window.addEventListener("copy", copyHandler, { passive: true });
2103
+ this.cleanupFns.push(() => window.removeEventListener("copy", copyHandler));
2104
+ if (typeof navigator !== "undefined" && navigator.share) {
2105
+ const originalShare = navigator.share.bind(navigator);
2106
+ navigator.share = (data) => {
2107
+ this.tracker.send("social_share", {
2108
+ method: "native_share_menu",
2109
+ url: data?.url || window.location.href,
2110
+ title: data?.title
2111
+ });
2112
+ return originalShare(data);
2113
+ };
2114
+ this.cleanupFns.push(() => {
2115
+ navigator.share = originalShare;
2116
+ });
2117
+ }
2118
+ }
2119
+ setupScrollTracking() {
2120
+ if (typeof window === "undefined") return;
2121
+ const THRESHOLDS = [25, 50, 75, 100];
2122
+ const scrollHandler = () => {
2123
+ const scrollTop = window.scrollY || document.documentElement.scrollTop;
2124
+ const docHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
2125
+ if (docHeight <= 0) return;
2126
+ const pct = Math.round(scrollTop / docHeight * 100);
2127
+ if (pct > this.maxScrollDepth) {
2128
+ this.maxScrollDepth = pct;
2129
+ }
2130
+ clearTimeout(this.scrollTimer);
2131
+ this.scrollTimer = setTimeout(() => {
2132
+ for (const threshold of THRESHOLDS) {
2133
+ if (this.maxScrollDepth >= threshold && !this.scrollThresholdsFired.has(threshold)) {
2134
+ this.scrollThresholdsFired.add(threshold);
2135
+ this.tracker.send("scroll", {
2136
+ depth: threshold / 100,
2137
+ depth_percent: threshold,
2138
+ path: window.location.pathname
2139
+ });
2140
+ }
2141
+ }
2142
+ }, 300);
2143
+ };
2144
+ window.addEventListener("scroll", scrollHandler, { passive: true });
2145
+ this.cleanupFns.push(() => {
2146
+ window.removeEventListener("scroll", scrollHandler);
2147
+ clearTimeout(this.scrollTimer);
2148
+ });
2149
+ }
2150
+ setupClickTracking() {
2151
+ if (typeof window === "undefined") return;
2152
+ const clickHandler = (e) => {
2153
+ const target = e.target;
2154
+ const link = target.closest("a");
2155
+ if (link) {
2156
+ this.tracker.send("click", {
2157
+ element_type: "link",
2158
+ href: link.href,
2159
+ text: link.innerText?.substring(0, 50),
2160
+ id: link.id,
2161
+ classes: link.className,
2162
+ dataset: { ...link.dataset },
2163
+ coordinates: { x: e.clientX, y: e.clientY }
2164
+ });
2165
+ }
2166
+ const button = target.closest("button");
2167
+ if (button) {
2168
+ this.tracker.send("click", {
2169
+ element_type: "button",
2170
+ text: button.innerText?.substring(0, 50),
2171
+ id: button.id,
2172
+ classes: button.className,
2173
+ coordinates: { x: e.clientX, y: e.clientY }
2174
+ });
2175
+ }
2176
+ const now = Date.now();
2177
+ const ZONE = 400;
2178
+ const WINDOW_MS = 1e3;
2179
+ const RAGE_THRESHOLD = 3;
2180
+ this.clickBuffer.push({ x: e.clientX, y: e.clientY, t: now });
2181
+ this.clickBuffer = this.clickBuffer.filter((c) => now - c.t < WINDOW_MS);
2182
+ const zone = {
2183
+ x: Math.floor(e.clientX / ZONE),
2184
+ y: Math.floor(e.clientY / ZONE)
2185
+ };
2186
+ const zoneClicks = this.clickBuffer.filter(
2187
+ (c) => Math.floor(c.x / ZONE) === zone.x && Math.floor(c.y / ZONE) === zone.y
2188
+ );
2189
+ if (zoneClicks.length >= RAGE_THRESHOLD) {
2190
+ this.tracker.send(
2191
+ "click",
2192
+ {
2193
+ element_type: target.tagName.toLowerCase(),
2194
+ event_name: "rage_click",
2195
+ coordinates: { x: e.clientX, y: e.clientY },
2196
+ click_count: zoneClicks.length,
2197
+ path: window.location.pathname
2198
+ },
2199
+ "rage_click"
2200
+ );
2201
+ this.clickBuffer = [];
2202
+ }
2203
+ const isInteractive = target.closest(
2204
+ "a, button, input, select, textarea, [onclick], [role='button']"
2205
+ );
2206
+ if (!isInteractive) {
2207
+ const pathBefore = window.location.pathname;
2208
+ setTimeout(() => {
2209
+ const pathAfter = window.location.pathname;
2210
+ if (pathBefore === pathAfter) {
2211
+ this.tracker.send(
2212
+ "click",
2213
+ {
2214
+ element_type: target.tagName.toLowerCase(),
2215
+ event_name: "dead_click",
2216
+ selector: getSelector(target),
2217
+ coordinates: { x: e.clientX, y: e.clientY },
2218
+ path: window.location.pathname
2219
+ },
2220
+ "dead_click"
2221
+ );
2222
+ }
2223
+ }, 300);
2224
+ }
2225
+ };
2226
+ window.addEventListener("click", clickHandler, { passive: true });
2227
+ this.cleanupFns.push(
2228
+ () => window.removeEventListener("click", clickHandler)
2229
+ );
2230
+ }
2231
+ setupFormTracking() {
2232
+ if (typeof document === "undefined") return;
2233
+ const submitHandler = (e) => {
2234
+ const form = e.target;
2235
+ if (form) {
2236
+ this.tracker.send("form_submit", {
2237
+ form_id: form.id || form.name || "unknown_form",
2238
+ action: form.action,
2239
+ method: form.method,
2240
+ field_count: form.elements.length
2241
+ });
2242
+ }
2243
+ };
2244
+ document.addEventListener("submit", submitHandler, { passive: true });
2245
+ this.cleanupFns.push(
2246
+ () => document.removeEventListener("submit", submitHandler)
2247
+ );
2248
+ }
2249
+ setupOutboundTracking() {
2250
+ if (typeof window === "undefined") return;
2251
+ const outboundHandler = (e) => {
2252
+ const link = e.target.closest("a");
2253
+ if (!link || !link.href) return;
2254
+ try {
2255
+ const linkHost = new URL(link.href).hostname;
2256
+ if (linkHost && linkHost !== window.location.hostname) {
2257
+ this.tracker.send(
2258
+ "click",
2259
+ {
2260
+ event_name: "outbound_click",
2261
+ href: link.href,
2262
+ text: link.innerText?.substring(0, 50),
2263
+ destination_host: linkHost,
2264
+ coordinates: { x: e.clientX, y: e.clientY }
2265
+ },
2266
+ "outbound_click"
2267
+ );
2268
+ }
2269
+ } catch {
2270
+ }
2271
+ };
2272
+ window.addEventListener("click", outboundHandler, { passive: true });
2273
+ this.cleanupFns.push(
2274
+ () => window.removeEventListener("click", outboundHandler)
2275
+ );
2276
+ }
2277
+ setupVideoTracking() {
2278
+ if (typeof document === "undefined") return;
2279
+ const attachVideoListeners = (video) => {
2280
+ if (video.__nexus_tracked) return;
2281
+ video.__nexus_tracked = true;
2282
+ const src = video.src || video.currentSrc || "unknown";
2283
+ let milestone50Fired = false;
2284
+ video.addEventListener("play", () => {
2285
+ this.tracker.send(
2286
+ "custom_event",
2287
+ { event_name: "video_play", src },
2288
+ "video_play"
2289
+ );
2290
+ });
2291
+ video.addEventListener("pause", () => {
2292
+ this.tracker.send(
2293
+ "custom_event",
2294
+ {
2295
+ event_name: "video_pause",
2296
+ src,
2297
+ position_seconds: Math.round(video.currentTime)
2298
+ },
2299
+ "video_pause"
2300
+ );
2301
+ });
2302
+ video.addEventListener("timeupdate", () => {
2303
+ if (!video.duration || video.duration === Infinity) return;
2304
+ const pct = video.currentTime / video.duration;
2305
+ if (pct >= 0.5 && !milestone50Fired) {
2306
+ milestone50Fired = true;
2307
+ this.tracker.send(
2308
+ "custom_event",
2309
+ {
2310
+ event_name: "video_50_percent",
2311
+ src
2312
+ },
2313
+ "video_50_percent"
2314
+ );
2315
+ }
2316
+ });
2317
+ video.addEventListener("ended", () => {
2318
+ this.tracker.send(
2319
+ "custom_event",
2320
+ {
2321
+ event_name: "video_complete",
2322
+ src,
2323
+ duration_seconds: Math.round(video.duration)
2324
+ },
2325
+ "video_complete"
2326
+ );
2327
+ });
2328
+ };
2329
+ document.querySelectorAll("video").forEach((v) => attachVideoListeners(v));
2330
+ const observer = new MutationObserver((mutations) => {
2331
+ mutations.forEach((m) => {
2332
+ m.addedNodes.forEach((node) => {
2333
+ if (node instanceof HTMLVideoElement) {
2334
+ attachVideoListeners(node);
2335
+ }
2336
+ if (node instanceof Element) {
2337
+ node.querySelectorAll("video").forEach((v) => attachVideoListeners(v));
2338
+ }
2339
+ });
2340
+ });
2341
+ });
2342
+ observer.observe(document.body, { childList: true, subtree: true });
2343
+ this.cleanupFns.push(() => observer.disconnect());
2344
+ }
2345
+ setupErrorTracking() {
2346
+ if (typeof window === "undefined") return;
2347
+ const errorHandler = (e) => {
2348
+ this.tracker.send("error", {
2349
+ message: e.message,
2350
+ filename: e.filename,
2351
+ lineno: e.lineno,
2352
+ colno: e.colno,
2353
+ stack: e.error?.stack,
2354
+ url: window.location.href,
2355
+ type: "uncaught_error"
2356
+ });
2357
+ };
2358
+ const rejectionHandler = (e) => {
2359
+ const reason = e.reason instanceof Error ? e.reason.message : String(e.reason);
2360
+ const stack = e.reason instanceof Error ? e.reason.stack : void 0;
2361
+ this.tracker.send("error", {
2362
+ message: reason,
2363
+ stack,
2364
+ url: window.location.href,
2365
+ type: "unhandled_rejection"
2366
+ });
2367
+ };
2368
+ window.addEventListener("error", errorHandler);
2369
+ window.addEventListener("unhandledrejection", rejectionHandler);
2370
+ this.cleanupFns.push(() => {
2371
+ window.removeEventListener("error", errorHandler);
2372
+ window.removeEventListener("unhandledrejection", rejectionHandler);
2373
+ });
2374
+ }
2375
+ setupRouteTracking() {
2376
+ if (typeof window === "undefined" || typeof window.history === "undefined")
2377
+ return;
2378
+ const originalPushState = history.pushState.bind(history);
2379
+ const originalReplaceState = history.replaceState.bind(history);
2380
+ history.pushState = (...args) => {
2381
+ const prevPath = window.location.pathname;
2382
+ originalPushState(...args);
2383
+ if (!this.isInitializedByReactProvider()) {
2384
+ this.pageView(prevPath);
2385
+ }
2386
+ };
2387
+ history.replaceState = (...args) => {
2388
+ originalReplaceState(...args);
2389
+ };
2390
+ const popStateHandler = () => {
2391
+ if (!this.isInitializedByReactProvider()) {
2392
+ this.pageView();
2393
+ }
2394
+ };
2395
+ window.addEventListener("popstate", popStateHandler);
2396
+ this.cleanupFns.push(() => {
2397
+ history.pushState = originalPushState;
2398
+ history.replaceState = originalReplaceState;
2399
+ window.removeEventListener("popstate", popStateHandler);
2400
+ });
2401
+ }
2402
+ isInitializedByReactProvider() {
2403
+ return !!document.getElementById("__nexus_react_active");
2404
+ }
2405
+ async identify(userId, traits = {}) {
2406
+ return this.sendIdentityRequest("identify", { user_id: userId, traits });
2407
+ }
2408
+ async group(groupId, traits = {}) {
2409
+ return this.sendIdentityRequest("group", { group_id: groupId, traits });
2410
+ }
2411
+ async alias(newId) {
2412
+ return this.sendIdentityRequest("alias", {
2413
+ previous_id: this.tracker.getSession(),
2414
+ user_id: newId
2415
+ });
2416
+ }
2417
+ reset(performGdprScrub = false) {
2418
+ const config = this.tracker.config;
2419
+ this.tracker.stop();
2420
+ localStorage.removeItem("nexus_sid");
2421
+ localStorage.removeItem("nexus_vid");
2422
+ safeRemoveItem2("nexus_anon_id");
2423
+ this.tracker.clearIdentity();
2424
+ if (performGdprScrub) {
2425
+ const endpoint = `${config.analyticsUrl}/api/privacy/scrub`;
2426
+ const userId = this.tracker.getVisitorId();
2427
+ fetch(endpoint, {
2428
+ method: "DELETE",
2429
+ headers: {
2430
+ "Content-Type": "application/json",
2431
+ Authorization: `Bearer ${config.apiKey}`
2432
+ },
2433
+ body: JSON.stringify({
2434
+ project_id: config.projectId,
2435
+ user_id: userId
2436
+ })
2437
+ }).catch((err) => console.error("[NexusHub] Privacy scrub failed:", err));
2438
+ }
2439
+ window.location.reload();
2440
+ }
2441
+ track(eventName, properties = {}) {
2442
+ this.tracker.send(
2443
+ "custom_event",
2444
+ { event_name: eventName, ...properties },
2445
+ eventName
2446
+ );
2447
+ }
2448
+ trackPurchase(orderData) {
2449
+ const ecommerce = {
2450
+ orderId: orderData.orderId,
2451
+ total: orderData.total,
2452
+ revenue: orderData.revenue ?? orderData.total,
2453
+ currency: orderData.currency || "USD",
2454
+ products: orderData.products.map((p) => ({
2455
+ productId: p.id,
2456
+ sku: p.sku,
2457
+ name: p.name,
2458
+ price: p.price,
2459
+ quantity: p.quantity
2460
+ }))
2461
+ };
2462
+ this.tracker.send(
2463
+ "purchase",
2464
+ { order_id: orderData.orderId },
2465
+ "purchase",
2466
+ ecommerce
2467
+ );
2468
+ }
2469
+ trackError(error, context) {
2470
+ this.tracker.send("error", {
2471
+ message: error.message,
2472
+ stack: error.stack,
2473
+ context,
2474
+ url: typeof window !== "undefined" ? window.location.href : "",
2475
+ type: "manual"
2476
+ });
2477
+ }
2478
+ async sendIdentityRequest(type, data) {
2479
+ try {
2480
+ const config = this.tracker.config;
2481
+ const endpoint = `${config.analyticsUrl}/api/${type}`;
2482
+ const payload = {
2483
+ projectId: config.projectId,
2484
+ sessionId: this.tracker.getSession(),
2485
+ visitorId: this.tracker.getVisitorId(),
2486
+ anonymousId: this.tracker.getAnonymousId(),
2487
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2488
+ ...data
2489
+ };
2490
+ const response = await fetch(endpoint, {
2491
+ method: "POST",
2492
+ headers: {
2493
+ "Content-Type": "application/json",
2494
+ Authorization: `Bearer ${config.apiKey}`
2495
+ },
2496
+ body: JSON.stringify(payload)
2497
+ });
2498
+ return response.ok;
2499
+ } catch (error) {
2500
+ console.error(`[NexusHub] ${type} failed:`, error);
2501
+ return false;
2502
+ }
2503
+ }
2504
+ getSessionId() {
2505
+ return this.tracker.getSession();
2506
+ }
2507
+ stop(isFinalShutdown = false) {
2508
+ this.cleanupFns.forEach((fn) => fn());
2509
+ this.cleanupFns = [];
2510
+ if (isFinalShutdown) {
2511
+ this.tracker.send("session_end", {
2512
+ session_id: this.tracker.getSession(),
2513
+ duration: this.tracker.getSessionDuration(),
2514
+ max_scroll_depth: this.maxScrollDepth / 100
2515
+ });
2516
+ }
2517
+ this.tracker.stop();
2518
+ this.isInitialized = false;
2519
+ }
2520
+ };
2521
+ function getSelector(el, depth = 0) {
2522
+ if (!el || depth > 2) return "";
2523
+ const tag = el.tagName.toLowerCase();
2524
+ const id = el.id ? `#${el.id}` : "";
2525
+ const cls = el.className && typeof el.className === "string" ? `.${el.className.trim().split(/\s+/).slice(0, 2).join(".")}` : "";
2526
+ const self = `${tag}${id}${cls}`;
2527
+ const parent = el.parentElement && depth < 2 ? `${getSelector(el.parentElement, depth + 1)} > ` : "";
2528
+ return `${parent}${self}`;
2529
+ }
2530
+
2531
+ // src/client.ts
2532
+ var NexusClient = class {
2533
+ constructor(config) {
2534
+ const fullConfig = getFullConfig(config);
2535
+ this.config = {
2536
+ debug: config?.debug ?? false,
2537
+ cacheStrategy: config?.cacheStrategy ?? "memory",
2538
+ revalidateTime: config?.revalidateTime ?? 60,
2539
+ timeout: config?.timeout ?? 1e4,
2540
+ retries: config?.retries ?? 3,
2541
+ ...fullConfig
2542
+ };
2543
+ const errors = validateConfig(this.config);
2544
+ if (errors.length > 0) {
2545
+ console.warn("\u26A0\uFE0F NexusHub: Configuration issues:", errors.join(", "));
2546
+ if (!this.config.projectId) {
2547
+ console.warn("\u26A0\uFE0F NexusHub: No Project ID found. Tracking will fail.");
2548
+ }
2549
+ }
2550
+ this.content = new ContentEngine(this.config);
2551
+ if (typeof window !== "undefined") {
2552
+ this.analytics = new AnalyticsEngine(this.config);
2553
+ this.analytics.start();
2554
+ }
2555
+ }
2556
+ /**
2557
+ * Helper alias for cleaner content fetching.
2558
+ */
2559
+ getPage(slug, options) {
2560
+ return this.content.getPage(slug, options);
2561
+ }
2562
+ /**
2563
+ * Returns a readonly snapshot of the current config.
2564
+ */
2565
+ getConfig() {
2566
+ return { ...this.config };
2567
+ }
2568
+ /**
2569
+ * Updates specific config fields at runtime.
2570
+ * Replaces the previous pattern of `(nexus as any).config.projectId = x`
2571
+ * which bypassed TypeScript and mutated internal state unsafely.
2572
+ */
2573
+ updateConfig(updates) {
2574
+ this.config = { ...this.config, ...updates };
2575
+ }
2576
+ };
2577
+ var nexus = new NexusClient();
2578
+ var createNexusClient = (config) => new NexusClient(config);
25
2579
 
26
2580
  // src/index.ts
2581
+ init_config();
27
2582
  var VERSION = "0.0.1";
28
2583
  export {
29
2584
  AnalyticsEngine,
30
- AuthProvider,
31
2585
  BrowserCache,
32
2586
  CacheTags,
33
2587
  ContentEngine,
@@ -38,14 +2592,11 @@ export {
38
2592
  LocalCacheProxy as LocalCache,
39
2593
  MemoryCache,
40
2594
  NexusClient,
41
- NexusProvider,
42
2595
  VERSION,
43
2596
  createNexusClient,
44
2597
  getEnvConfig,
45
2598
  getFullConfig,
46
2599
  mergeConfigs,
47
2600
  nexus,
48
- useNexus,
49
- useNexusAuth,
50
2601
  validateConfig
51
2602
  };