@nexushub/client 0.0.6 → 0.0.8

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.cjs ADDED
@@ -0,0 +1,2087 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+ var _chunkOBGZSXTJcjs = require('./chunk-OBGZSXTJ.cjs');
4
+
5
+ // src/config.ts
6
+ var DEFAULT_API_URL = "http://localhost:3001";
7
+ var DEFAULT_ANALYTICS_URL = "http://localhost:3002";
8
+ var LOCAL_NEST_URL = "http://localhost:3001";
9
+ var LOCAL_RUST_URL = "http://localhost:3002";
10
+ var hasEnv = () => {
11
+ return typeof process !== "undefined" && typeof process.env !== "undefined" && Object.keys(process.env).length > 0;
12
+ };
13
+ var getEnvConfig = () => {
14
+ const env = hasEnv() ? process.env : {};
15
+ const isDev = env.NODE_ENV === "development" || env.NEXT_PUBLIC_NODE_ENV === "development";
16
+ const projectId = _nullishCoalesce(env.NEXT_PUBLIC_NEXUS_ID, () => ( env.NEXUS_PROJECT_ID));
17
+ const apiKey = _nullishCoalesce(env.NEXT_PUBLIC_NEXUS_KEY, () => ( env.NEXUS_API_KEY));
18
+ const apiUrl = _nullishCoalesce(_nullishCoalesce(env.NEXT_PUBLIC_NEXUS_API_URL, () => ( env.NEXUS_API_URL)), () => ( (isDev ? LOCAL_NEST_URL : DEFAULT_API_URL)));
19
+ const analyticsUrl = _nullishCoalesce(env.NEXT_PUBLIC_NEXUS_ANALYTICS_URL, () => ( (apiUrl.includes("localhost") ? LOCAL_RUST_URL : DEFAULT_ANALYTICS_URL)));
20
+ return {
21
+ projectId,
22
+ apiKey,
23
+ apiUrl,
24
+ analyticsUrl
25
+ };
26
+ };
27
+ var mergeConfigs = (base, override) => {
28
+ const mergedApiUrl = override.apiUrl || base.apiUrl || DEFAULT_API_URL;
29
+ const mergedAnalyticsUrl = override.analyticsUrl || base.analyticsUrl || (mergedApiUrl.includes("localhost") ? LOCAL_RUST_URL : DEFAULT_ANALYTICS_URL);
30
+ return {
31
+ ...base,
32
+ ...override,
33
+ apiUrl: mergedApiUrl,
34
+ analyticsUrl: mergedAnalyticsUrl,
35
+ projectId: override.projectId || base.projectId
36
+ };
37
+ };
38
+ var getFullConfig = (partialConfig) => {
39
+ const envConfig = getEnvConfig();
40
+ return mergeConfigs(envConfig, partialConfig || {});
41
+ };
42
+ var validateConfig = (config) => {
43
+ const errors = [];
44
+ if (!config.projectId) errors.push("Missing projectId");
45
+ if (!config.apiUrl) errors.push("Missing apiUrl");
46
+ if (config.apiUrl && !config.apiUrl.startsWith("http")) {
47
+ errors.push("apiUrl must be a valid URL (http:// or https://)");
48
+ }
49
+ return errors;
50
+ };
51
+
52
+ // src/content/cache-implementations.ts
53
+ var CacheTags = {
54
+ project: (projectId) => `nexus_project_${projectId}`,
55
+ content: (slug) => `content_${slug}`,
56
+ collection: (collectionId) => `collection_${collectionId}`,
57
+ global: "nexus_global_config",
58
+ user: (userId) => `user_${userId}`,
59
+ media: (mediaId) => `media_${mediaId}`
60
+ };
61
+ var MemoryCache = class {
62
+ constructor(options = {}) {
63
+ this.cache = /* @__PURE__ */ new Map();
64
+ this.tagIndex = /* @__PURE__ */ new Map();
65
+ this.stats = {
66
+ size: 0,
67
+ hits: 0,
68
+ misses: 0,
69
+ hitRate: 0,
70
+ evictions: 0
71
+ };
72
+ this.maxSize = options.maxSize || 1e3;
73
+ this.defaultTTL = options.ttl || 5 * 60 * 1e3;
74
+ }
75
+ set(key, data, options = {}) {
76
+ if (this.cache.size >= this.maxSize) {
77
+ this.evictLRU();
78
+ }
79
+ const metadata = {
80
+ timestamp: Date.now(),
81
+ expiresAt: Date.now() + (options.ttl || this.defaultTTL),
82
+ tags: options.tags || [],
83
+ size: this.calculateSize(data)
84
+ };
85
+ this.cache.set(key, { data, metadata });
86
+ this.stats.size = this.cache.size;
87
+ metadata.tags.forEach((tag) => {
88
+ if (!this.tagIndex.has(tag)) {
89
+ this.tagIndex.set(tag, /* @__PURE__ */ new Set());
90
+ }
91
+ this.tagIndex.get(tag).add(key);
92
+ });
93
+ }
94
+ get(key) {
95
+ const entry = this.cache.get(key);
96
+ if (!entry) {
97
+ this.stats.misses++;
98
+ this.updateHitRate();
99
+ return null;
100
+ }
101
+ if (Date.now() > entry.metadata.expiresAt) {
102
+ this.delete(key);
103
+ this.stats.misses++;
104
+ this.updateHitRate();
105
+ return null;
106
+ }
107
+ entry.metadata.timestamp = Date.now();
108
+ this.stats.hits++;
109
+ this.updateHitRate();
110
+ return entry;
111
+ }
112
+ delete(key) {
113
+ const entry = this.cache.get(key);
114
+ if (!entry) return false;
115
+ entry.metadata.tags.forEach((tag) => {
116
+ const keys = this.tagIndex.get(tag);
117
+ if (keys) {
118
+ keys.delete(key);
119
+ if (keys.size === 0) {
120
+ this.tagIndex.delete(tag);
121
+ }
122
+ }
123
+ });
124
+ this.cache.delete(key);
125
+ this.stats.size = this.cache.size;
126
+ return true;
127
+ }
128
+ invalidateByTags(tags) {
129
+ const keysToDelete = /* @__PURE__ */ new Set();
130
+ tags.forEach((tag) => {
131
+ const keys = this.tagIndex.get(tag);
132
+ if (keys) {
133
+ keys.forEach((key) => keysToDelete.add(key));
134
+ this.tagIndex.delete(tag);
135
+ }
136
+ });
137
+ keysToDelete.forEach((key) => this.delete(key));
138
+ if (process.env.NODE_ENV === "development") {
139
+ console.log(
140
+ `[MemoryCache] Invalidated ${keysToDelete.size} entries by tags: ${tags.join(", ")}`
141
+ );
142
+ }
143
+ }
144
+ clear() {
145
+ this.cache.clear();
146
+ this.tagIndex.clear();
147
+ this.stats = {
148
+ size: 0,
149
+ hits: 0,
150
+ misses: 0,
151
+ hitRate: 0,
152
+ evictions: 0
153
+ };
154
+ }
155
+ getStats() {
156
+ return { ...this.stats };
157
+ }
158
+ evictLRU() {
159
+ let oldestKey = null;
160
+ let oldestTime = Infinity;
161
+ for (const [key, entry] of this.cache.entries()) {
162
+ if (entry.metadata.timestamp < oldestTime) {
163
+ oldestTime = entry.metadata.timestamp;
164
+ oldestKey = key;
165
+ }
166
+ }
167
+ if (oldestKey) {
168
+ this.delete(oldestKey);
169
+ this.stats.evictions++;
170
+ }
171
+ }
172
+ calculateSize(data) {
173
+ try {
174
+ const jsonString = JSON.stringify(data);
175
+ return new Blob([jsonString]).size;
176
+ } catch (e2) {
177
+ return 0;
178
+ }
179
+ }
180
+ updateHitRate() {
181
+ const total = this.stats.hits + this.stats.misses;
182
+ this.stats.hitRate = total > 0 ? this.stats.hits / total : 0;
183
+ }
184
+ };
185
+ var BrowserCache = class {
186
+ constructor(projectId) {
187
+ this.projectId = projectId;
188
+ this.prefix = "nexushub_";
189
+ this.maxSize = 5 * 1024 * 1024;
190
+ // 5MB standard LocalStorage limit
191
+ this.currentSize = 0;
192
+ if (typeof window !== "undefined") {
193
+ this.calculateCurrentSize();
194
+ }
195
+ }
196
+ set(key, data, ttl = 5 * 60 * 1e3) {
197
+ if (typeof window === "undefined") return;
198
+ const storageKey = this.getStorageKey(key);
199
+ const entry = {
200
+ data,
201
+ metadata: {
202
+ timestamp: Date.now(),
203
+ expiresAt: Date.now() + ttl,
204
+ size: this.calculateStorageSize(data)
205
+ }
206
+ };
207
+ const serialized = JSON.stringify(entry);
208
+ const newSize = new Blob([serialized]).size;
209
+ if (this.currentSize + newSize > this.maxSize) {
210
+ this.evictOldest();
211
+ }
212
+ try {
213
+ localStorage.setItem(storageKey, serialized);
214
+ this.currentSize += newSize;
215
+ } catch (error) {
216
+ console.warn("[BrowserCache] Failed to save to localStorage:", error);
217
+ this.evictOldest();
218
+ try {
219
+ localStorage.setItem(storageKey, serialized);
220
+ } catch (e) {
221
+ }
222
+ }
223
+ }
224
+ get(key) {
225
+ if (typeof window === "undefined") return null;
226
+ const storageKey = this.getStorageKey(key);
227
+ const item = localStorage.getItem(storageKey);
228
+ if (!item) return null;
229
+ try {
230
+ const entry = JSON.parse(item);
231
+ if (Date.now() > entry.metadata.expiresAt) {
232
+ this.delete(key);
233
+ return null;
234
+ }
235
+ return entry.data;
236
+ } catch (e3) {
237
+ this.delete(key);
238
+ return null;
239
+ }
240
+ }
241
+ delete(key) {
242
+ if (typeof window === "undefined") return;
243
+ const storageKey = this.getStorageKey(key);
244
+ const item = localStorage.getItem(storageKey);
245
+ if (item) {
246
+ this.currentSize -= new Blob([item]).size;
247
+ }
248
+ localStorage.removeItem(storageKey);
249
+ }
250
+ clear() {
251
+ if (typeof window === "undefined") return;
252
+ const keysToRemove = [];
253
+ for (let i = 0; i < localStorage.length; i++) {
254
+ const key = localStorage.key(i);
255
+ if (_optionalChain([key, 'optionalAccess', _ => _.startsWith, 'call', _2 => _2(this.prefix)])) {
256
+ keysToRemove.push(key);
257
+ }
258
+ }
259
+ keysToRemove.forEach((key) => localStorage.removeItem(key));
260
+ this.currentSize = 0;
261
+ }
262
+ getStorageKey(key) {
263
+ return `${this.prefix}${this.projectId}_${key}`;
264
+ }
265
+ calculateCurrentSize() {
266
+ this.currentSize = 0;
267
+ for (let i = 0; i < localStorage.length; i++) {
268
+ const key = localStorage.key(i);
269
+ if (_optionalChain([key, 'optionalAccess', _3 => _3.startsWith, 'call', _4 => _4(this.prefix)])) {
270
+ const item = localStorage.getItem(key);
271
+ if (item) {
272
+ this.currentSize += new Blob([item]).size;
273
+ }
274
+ }
275
+ }
276
+ }
277
+ calculateStorageSize(data) {
278
+ return new Blob([JSON.stringify(data)]).size;
279
+ }
280
+ evictOldest() {
281
+ let oldestKey = null;
282
+ let oldestTime = Infinity;
283
+ for (let i = 0; i < localStorage.length; i++) {
284
+ const key = localStorage.key(i);
285
+ if (_optionalChain([key, 'optionalAccess', _5 => _5.startsWith, 'call', _6 => _6(this.prefix)])) {
286
+ const item = localStorage.getItem(key);
287
+ if (item) {
288
+ try {
289
+ const entry = JSON.parse(item);
290
+ if (entry.metadata.timestamp < oldestTime) {
291
+ oldestTime = entry.metadata.timestamp;
292
+ oldestKey = key;
293
+ }
294
+ } catch (e4) {
295
+ localStorage.removeItem(key);
296
+ }
297
+ }
298
+ }
299
+ }
300
+ if (oldestKey) {
301
+ const item = localStorage.getItem(oldestKey);
302
+ if (item) {
303
+ this.currentSize -= new Blob([item]).size;
304
+ }
305
+ localStorage.removeItem(oldestKey);
306
+ }
307
+ }
308
+ };
309
+
310
+ // src/content/cache.ts
311
+ var LocalCacheConstructor;
312
+ if (typeof window === "undefined") {
313
+ try {
314
+ const serverPath = "./local-cache-server";
315
+ LocalCacheConstructor = _chunkOBGZSXTJcjs.__require.call(void 0, serverPath).LocalCache;
316
+ } catch (e) {
317
+ LocalCacheConstructor = class Dummy {
318
+ };
319
+ }
320
+ } else {
321
+ const clientPath = "./local-cache-client";
322
+ LocalCacheConstructor = _chunkOBGZSXTJcjs.__require.call(void 0, clientPath).LocalCache;
323
+ }
324
+ var LocalCache = LocalCacheConstructor;
325
+
326
+ // src/content/strategies.ts
327
+ var RateLimiter = class {
328
+ constructor(config) {
329
+ this.requests = [];
330
+ this.config = config;
331
+ }
332
+ async checkLimit() {
333
+ const now = Date.now();
334
+ const windowStart = now - this.config.timeWindow;
335
+ this.requests = this.requests.filter((time) => time > windowStart);
336
+ if (this.requests.length >= this.config.maxRequests) {
337
+ const oldestRequest = this.requests[0];
338
+ const waitTime = windowStart + this.config.timeWindow - now;
339
+ if (waitTime > 0) {
340
+ await new Promise((resolve) => setTimeout(resolve, waitTime));
341
+ return this.checkLimit();
342
+ }
343
+ }
344
+ this.requests.push(now);
345
+ }
346
+ getStats() {
347
+ const now = Date.now();
348
+ const windowStart = now - this.config.timeWindow;
349
+ const currentRequests = this.requests.filter((time) => time > windowStart).length;
350
+ return {
351
+ currentRequests,
352
+ limit: this.config.maxRequests
353
+ };
354
+ }
355
+ };
356
+ var ExponentialBackoff = class {
357
+ constructor(config) {
358
+ this.config = {
359
+ jitter: true,
360
+ ...config
361
+ };
362
+ }
363
+ async execute(fn, onRetry) {
364
+ let lastError;
365
+ for (let attempt = 0; attempt <= this.config.maxRetries; attempt++) {
366
+ try {
367
+ return await fn();
368
+ } catch (error) {
369
+ lastError = error;
370
+ if (this.isClientError(error) && !this.isRateLimitError(error)) {
371
+ throw error;
372
+ }
373
+ if (attempt === this.config.maxRetries) {
374
+ break;
375
+ }
376
+ const delay = this.calculateDelay(attempt);
377
+ if (onRetry) {
378
+ onRetry(attempt + 1, delay, error);
379
+ }
380
+ await new Promise((resolve) => setTimeout(resolve, delay));
381
+ }
382
+ }
383
+ throw lastError;
384
+ }
385
+ calculateDelay(attempt) {
386
+ let delay = this.config.baseDelay * Math.pow(2, attempt);
387
+ delay = Math.min(delay, this.config.maxDelay);
388
+ if (this.config.jitter) {
389
+ delay = delay * (0.5 + Math.random());
390
+ }
391
+ return delay;
392
+ }
393
+ isClientError(error) {
394
+ return _optionalChain([error, 'optionalAccess', _7 => _7.status]) >= 400 && _optionalChain([error, 'optionalAccess', _8 => _8.status]) < 500;
395
+ }
396
+ isRateLimitError(error) {
397
+ return _optionalChain([error, 'optionalAccess', _9 => _9.status]) === 429;
398
+ }
399
+ };
400
+ var CircuitBreaker = class {
401
+ constructor() {
402
+ this.state = 0 /* CLOSED */;
403
+ this.failures = 0;
404
+ this.lastFailureTime = 0;
405
+ this.failureThreshold = 5;
406
+ this.resetTimeout = 3e4;
407
+ }
408
+ // 30 seconds
409
+ isOpen() {
410
+ if (this.state === 1 /* OPEN */) {
411
+ const now = Date.now();
412
+ if (now - this.lastFailureTime > this.resetTimeout) {
413
+ this.state = 2 /* HALF_OPEN */;
414
+ return false;
415
+ }
416
+ return true;
417
+ }
418
+ return false;
419
+ }
420
+ recordSuccess() {
421
+ this.failures = 0;
422
+ this.state = 0 /* CLOSED */;
423
+ }
424
+ recordFailure() {
425
+ this.failures++;
426
+ this.lastFailureTime = Date.now();
427
+ if (this.failures >= this.failureThreshold) {
428
+ this.state = 1 /* OPEN */;
429
+ if (process.env.NODE_ENV === "development") {
430
+ console.warn(`[NexusHub] \u{1F50C} Circuit Breaker OPEN. Pausing network requests.`);
431
+ }
432
+ }
433
+ }
434
+ };
435
+ var RequestBatcher = class {
436
+ constructor(batchWindow = 10, maxBatchSize = 20) {
437
+ this.batchWindow = batchWindow;
438
+ this.maxBatchSize = maxBatchSize;
439
+ this.batch = [];
440
+ this.processing = false;
441
+ }
442
+ async schedule(key, request) {
443
+ return new Promise((resolve, reject) => {
444
+ this.batch.push({ key, resolve, reject });
445
+ if (this.batch.length >= this.maxBatchSize) {
446
+ this.processBatch(request);
447
+ } else if (!this.batchTimeout) {
448
+ this.batchTimeout = setTimeout(
449
+ () => this.processBatch(request),
450
+ this.batchWindow
451
+ );
452
+ }
453
+ });
454
+ }
455
+ async processBatch(request) {
456
+ if (this.processing || this.batch.length === 0) return;
457
+ this.processing = true;
458
+ if (this.batchTimeout) {
459
+ clearTimeout(this.batchTimeout);
460
+ this.batchTimeout = void 0;
461
+ }
462
+ const currentBatch = [...this.batch];
463
+ this.batch = [];
464
+ try {
465
+ const result = await request();
466
+ currentBatch.forEach((item) => {
467
+ item.resolve(result);
468
+ });
469
+ } catch (error) {
470
+ currentBatch.forEach((item) => {
471
+ item.reject(error);
472
+ });
473
+ } finally {
474
+ this.processing = false;
475
+ if (this.batch.length > 0) {
476
+ setTimeout(() => this.processBatch(request), 0);
477
+ }
478
+ }
479
+ }
480
+ };
481
+
482
+ // src/content/utils.ts
483
+ function validateSlug(slug) {
484
+ if (!slug || typeof slug !== "string") {
485
+ throw new Error("Slug must be a non-empty string");
486
+ }
487
+ if (!/^[a-z0-9-_]+$/.test(slug)) {
488
+ throw new Error("Slug can only contain lowercase letters, numbers, hyphens, and underscores");
489
+ }
490
+ }
491
+ function normalizeQuery(query) {
492
+ const normalized = { ...query };
493
+ normalized.page = Math.max(1, normalized.page || 1);
494
+ normalized.limit = Math.min(100, Math.max(1, normalized.limit || 10));
495
+ normalized.order = normalized.order || "desc";
496
+ if (normalized.page < 1) {
497
+ throw new Error("Page must be greater than 0");
498
+ }
499
+ if (normalized.limit < 1 || normalized.limit > 100) {
500
+ throw new Error("Limit must be between 1 and 100");
501
+ }
502
+ return normalized;
503
+ }
504
+ function buildQueryString(query) {
505
+ const params = new URLSearchParams();
506
+ if (query.page) params.append("page", query.page.toString());
507
+ if (query.limit) params.append("limit", query.limit.toString());
508
+ if (query.sort) params.append("sort", query.sort);
509
+ if (query.order) params.append("order", query.order);
510
+ if (query.search) params.append("search", query.search);
511
+ if (_optionalChain([query, 'access', _10 => _10.include, 'optionalAccess', _11 => _11.length])) {
512
+ params.append("include", query.include.join(","));
513
+ }
514
+ if (_optionalChain([query, 'access', _12 => _12.fields, 'optionalAccess', _13 => _13.length])) {
515
+ params.append("fields", query.fields.join(","));
516
+ }
517
+ if (query.filter) {
518
+ params.append("filter", JSON.stringify(query.filter));
519
+ }
520
+ return params.toString();
521
+ }
522
+ function measurePerformance(name, fn) {
523
+ const start = performance.now();
524
+ const result = fn();
525
+ const end = performance.now();
526
+ if (process.env.NODE_ENV === "development") {
527
+ console.log(`\u23F1\uFE0F ${name}: ${(end - start).toFixed(2)}ms`);
528
+ }
529
+ return { result, duration: end - start };
530
+ }
531
+
532
+ // src/content/index.ts
533
+ var ContentEngine = class {
534
+ constructor(config) {
535
+ this.config = config;
536
+ this.isServer = typeof window === "undefined";
537
+ this.localCache = new LocalCache();
538
+ this.memoryCache = new MemoryCache({
539
+ maxSize: 500,
540
+ ttl: 5 * 60 * 1e3
541
+ // 5 minutes
542
+ });
543
+ if (!this.isServer) {
544
+ this.browserCache = new BrowserCache(config.projectId);
545
+ }
546
+ this.rateLimiter = new RateLimiter({
547
+ maxRequests: config.debug ? 100 : 50,
548
+ timeWindow: 6e4
549
+ });
550
+ this.backoff = new ExponentialBackoff({
551
+ maxRetries: config.retries || 3,
552
+ baseDelay: 100,
553
+ maxDelay: 5e3,
554
+ jitter: true
555
+ });
556
+ this.requestBatcher = new RequestBatcher(20, 50);
557
+ this.circuitBreaker = new CircuitBreaker();
558
+ this.defaultRevalidate = config.revalidateTime || 60;
559
+ this.cacheStrategy = config.cacheStrategy || "memory";
560
+ if (!this.isServer) {
561
+ window.addEventListener("beforeunload", this.cleanup.bind(this));
562
+ }
563
+ }
564
+ /**
565
+ * Fetch a Single Page with full strategy pipeline
566
+ */
567
+ async getPage(slug, options = {}) {
568
+ const { result, duration } = measurePerformance(
569
+ `getPage("${slug}")`,
570
+ () => this._getPage(slug, options)
571
+ );
572
+ if (this.config.debug && duration > 100) {
573
+ console.warn(
574
+ `[NexusHub] \u26A0\uFE0F getPage("${slug}") took ${duration.toFixed(2)}ms`
575
+ );
576
+ }
577
+ return result;
578
+ }
579
+ async _getPage(slug, options = {}) {
580
+ validateSlug(slug);
581
+ const {
582
+ revalidate = this.defaultRevalidate,
583
+ tags = [],
584
+ forceRefresh = false,
585
+ includeMetadata = false
586
+ } = options;
587
+ const cacheKey = `page:${slug}`;
588
+ const cached = this.checkCaches(cacheKey, forceRefresh, includeMetadata);
589
+ if (cached) {
590
+ if (this.config.debug) console.log(`[NexusHub] \u26A1 Cache hit: ${slug}`);
591
+ return includeMetadata ? cached : cached.data;
592
+ }
593
+ if (this.circuitBreaker.isOpen()) {
594
+ throw new Error(`[NexusHub] Circuit open. API is unavailable.`);
595
+ }
596
+ try {
597
+ await this.rateLimiter.checkLimit();
598
+ const data = await this.backoff.execute(
599
+ async () => {
600
+ return this.fetchPage(
601
+ slug,
602
+ cacheKey,
603
+ tags,
604
+ revalidate,
605
+ forceRefresh
606
+ );
607
+ },
608
+ (attempt, delay, error) => {
609
+ if (this.config.debug) {
610
+ console.log(
611
+ `[NexusHub] \u{1F504} Retry ${attempt} for '${slug}' after ${delay}ms: ${error.message}`
612
+ );
613
+ }
614
+ }
615
+ );
616
+ this.circuitBreaker.recordSuccess();
617
+ return includeMetadata ? data : data.data;
618
+ } catch (error) {
619
+ this.circuitBreaker.recordFailure();
620
+ const staleCache = this.memoryCache.get(cacheKey);
621
+ if (staleCache && !forceRefresh) {
622
+ console.warn(`[NexusHub] \u26A0\uFE0F Serving stale content for '${slug}'`);
623
+ return includeMetadata ? staleCache : staleCache.data;
624
+ }
625
+ throw this.normalizeError(error, `Failed to fetch page '${slug}'`);
626
+ }
627
+ }
628
+ /**
629
+ * Fetch a Collection (Optimized)
630
+ */
631
+ async getCollection(collectionId, query = {}, options = {}) {
632
+ const { result, duration } = measurePerformance(
633
+ `getCollection("${collectionId}")`,
634
+ () => this._getCollection(collectionId, query, options)
635
+ );
636
+ if (this.config.debug && duration > 100) {
637
+ console.warn(
638
+ `[NexusHub] \u26A0\uFE0F getCollection("${collectionId}") took ${duration.toFixed(2)}ms`
639
+ );
640
+ }
641
+ return result;
642
+ }
643
+ async _getCollection(collectionId, query = {}, options = {}) {
644
+ const normalizedQuery = normalizeQuery(query);
645
+ const {
646
+ revalidate = this.defaultRevalidate,
647
+ tags = [],
648
+ forceRefresh = false,
649
+ includeMetadata = false
650
+ } = options;
651
+ const queryString = buildQueryString(normalizedQuery);
652
+ const cacheKey = `collection:${collectionId}:${queryString}`;
653
+ const cached = this.checkCaches(
654
+ cacheKey,
655
+ forceRefresh,
656
+ includeMetadata
657
+ );
658
+ if (cached) {
659
+ if (this.config.debug) {
660
+ console.log(
661
+ `[NexusHub] \u26A1 Served collection '${collectionId}' from memory cache.`
662
+ );
663
+ }
664
+ return includeMetadata ? cached : cached.data;
665
+ }
666
+ if (!forceRefresh && process.env.NODE_ENV === "development") {
667
+ const localCollection = this.localCache.getCollection(collectionId);
668
+ if (localCollection) {
669
+ const result = this.applyLocalQuery(
670
+ localCollection,
671
+ normalizedQuery
672
+ );
673
+ if (this.config.debug) {
674
+ console.log(
675
+ `[NexusHub] \u{1F4C1} Served collection '${collectionId}' from local cache.`
676
+ );
677
+ }
678
+ this.memoryCache.set(cacheKey, result, {
679
+ tags: [...tags, CacheTags.collection(collectionId)],
680
+ revalidate
681
+ });
682
+ return result;
683
+ }
684
+ }
685
+ if (this.circuitBreaker.isOpen()) throw new Error("Circuit open");
686
+ try {
687
+ await this.rateLimiter.checkLimit();
688
+ const result = await this.backoff.execute(async () => {
689
+ return this.fetchCollection(
690
+ collectionId,
691
+ normalizedQuery,
692
+ cacheKey,
693
+ tags,
694
+ revalidate
695
+ );
696
+ });
697
+ this.circuitBreaker.recordSuccess();
698
+ return includeMetadata ? result : result.data;
699
+ } catch (error) {
700
+ this.circuitBreaker.recordFailure();
701
+ const staleCache = this.memoryCache.get(cacheKey);
702
+ if (staleCache && !forceRefresh) {
703
+ console.warn(
704
+ `[NexusHub] \u26A0\uFE0F Using stale cache for collection '${collectionId}'`
705
+ );
706
+ return includeMetadata ? staleCache : staleCache.data;
707
+ }
708
+ throw this.normalizeError(
709
+ error,
710
+ `Failed to fetch collection '${collectionId}'`
711
+ );
712
+ }
713
+ }
714
+ /**
715
+ * Fetch Global Settings with nested includes support
716
+ */
717
+ async getGlobals(options = {}) {
718
+ const {
719
+ include = [],
720
+ revalidate = this.defaultRevalidate,
721
+ forceRefresh = false
722
+ } = options;
723
+ const cacheKey = `globals:${include.join(",")}`;
724
+ if (!forceRefresh && this.cacheStrategy === "memory") {
725
+ const cached = this.memoryCache.get(cacheKey);
726
+ if (cached && this.isCacheValid(cached.metadata)) {
727
+ if (this.config.debug)
728
+ console.log("[NexusHub] \u26A1 Served globals from memory cache.");
729
+ return cached.data;
730
+ }
731
+ }
732
+ if (!forceRefresh && !this.isServer && this.cacheStrategy === "localStorage" && this.browserCache) {
733
+ const cached = this.browserCache.get(cacheKey);
734
+ if (cached) {
735
+ return cached;
736
+ }
737
+ }
738
+ if (!forceRefresh && process.env.NODE_ENV === "development") {
739
+ const localGlobals = this.localCache.getGlobals();
740
+ if (localGlobals) {
741
+ this.memoryCache.set(cacheKey, localGlobals, {
742
+ tags: [CacheTags.global],
743
+ revalidate
744
+ });
745
+ return localGlobals;
746
+ }
747
+ }
748
+ try {
749
+ await this.rateLimiter.checkLimit();
750
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/globals`;
751
+ const params = include.length > 0 ? `?include=${include.join(",")}` : "";
752
+ const res = await this.fetchWithTimeout(`${url}${params}`, {
753
+ method: "GET",
754
+ headers: this.getHeaders()
755
+ });
756
+ if (!res.ok) {
757
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
758
+ }
759
+ const json = await res.json();
760
+ const data = json.data || json;
761
+ this.writeCache(cacheKey, data, {
762
+ revalidate,
763
+ tags: [CacheTags.project(this.config.projectId), CacheTags.global]
764
+ });
765
+ return data;
766
+ } catch (error) {
767
+ const staleCache = this.memoryCache.get(cacheKey);
768
+ if (staleCache && !forceRefresh) {
769
+ console.warn("[NexusHub] \u26A0\uFE0F Using stale cache for globals");
770
+ return staleCache.data;
771
+ }
772
+ throw this.normalizeError(error, "Failed to fetch globals");
773
+ }
774
+ }
775
+ /**
776
+ * Get a single item from a collection (Uses Request Batching)
777
+ * If you call this 10 times in a loop, it sends 1 HTTP request.
778
+ */
779
+ async getItem(collectionId, itemId, options = {}) {
780
+ const cacheKey = `item:${collectionId}:${itemId}`;
781
+ if (this.cacheStrategy === "memory") {
782
+ const cached = this.memoryCache.get(cacheKey);
783
+ if (cached && this.isCacheValid(cached.metadata)) {
784
+ if (this.config.debug) {
785
+ console.log(`[NexusHub] \u26A1 Served item '${itemId}' from cache.`);
786
+ }
787
+ return cached.data;
788
+ }
789
+ }
790
+ return this.requestBatcher.schedule(cacheKey, async () => {
791
+ const params = new URLSearchParams();
792
+ if (_optionalChain([options, 'access', _14 => _14.include, 'optionalAccess', _15 => _15.length])) {
793
+ params.append("include", options.include.join(","));
794
+ }
795
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/collection/${collectionId}/${itemId}?${params}`;
796
+ const res = await this.fetchWithTimeout(url, {
797
+ method: "GET",
798
+ headers: this.getHeaders()
799
+ });
800
+ if (!res.ok) {
801
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
802
+ }
803
+ const json = await res.json();
804
+ const data = json.data || json;
805
+ this.writeCache(cacheKey, data, {
806
+ revalidate: options.revalidate || this.defaultRevalidate,
807
+ tags: [
808
+ CacheTags.project(this.config.projectId),
809
+ CacheTags.collection(collectionId),
810
+ `item_${itemId}`,
811
+ ...options.tags || []
812
+ ]
813
+ });
814
+ return data;
815
+ });
816
+ }
817
+ /**
818
+ * Search across collections
819
+ */
820
+ async search(query, options = {}) {
821
+ const params = new URLSearchParams({
822
+ q: query,
823
+ limit: (options.limit || 20).toString()
824
+ });
825
+ if (_optionalChain([options, 'access', _16 => _16.collections, 'optionalAccess', _17 => _17.length])) {
826
+ params.append("collections", options.collections.join(","));
827
+ }
828
+ if (_optionalChain([options, 'access', _18 => _18.fields, 'optionalAccess', _19 => _19.length])) {
829
+ params.append("fields", options.fields.join(","));
830
+ }
831
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/search?${params}`;
832
+ const res = await this.fetchWithTimeout(url, {
833
+ method: "GET",
834
+ headers: this.getHeaders()
835
+ });
836
+ if (!res.ok) {
837
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
838
+ }
839
+ return await res.json();
840
+ }
841
+ /**
842
+ * Prefetch content for better performance
843
+ */
844
+ async prefetch(urls) {
845
+ if (typeof window !== "undefined" && "requestIdleCallback" in window) {
846
+ requestIdleCallback(async () => {
847
+ await Promise.allSettled(
848
+ urls.map((url) => fetch(url, { priority: "low" }))
849
+ );
850
+ });
851
+ }
852
+ }
853
+ /**
854
+ * Robust Real-time Subscriptions (SSE) with Auto-Reconnect
855
+ */
856
+ subscribeToUpdates(callback) {
857
+ if (this.isServer || typeof EventSource === "undefined") {
858
+ console.warn("[NexusHub] EventSource not supported in this environment");
859
+ return () => {
860
+ };
861
+ }
862
+ let eventSource = null;
863
+ let retryCount = 0;
864
+ let isClosed = false;
865
+ const connect = () => {
866
+ if (isClosed) return;
867
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/updates?key=${this.config.apiKey}`;
868
+ eventSource = new EventSource(url);
869
+ eventSource.onopen = () => {
870
+ retryCount = 0;
871
+ if (this.config.debug)
872
+ console.log("[NexusHub] \u{1F7E2} Real-time stream connected");
873
+ };
874
+ eventSource.onmessage = (event) => {
875
+ try {
876
+ const data = JSON.parse(event.data);
877
+ if (data.type === "content.updated" && data.slug) {
878
+ this.invalidateCache([CacheTags.content(data.slug)]);
879
+ }
880
+ if (data.type === "collection.updated") {
881
+ this.invalidateCache([CacheTags.collection(data.collectionId)]);
882
+ }
883
+ callback(data);
884
+ } catch (e) {
885
+ console.error("[NexusHub] SSE Parse Error", e);
886
+ }
887
+ };
888
+ eventSource.onerror = () => {
889
+ _optionalChain([eventSource, 'optionalAccess', _20 => _20.close, 'call', _21 => _21()]);
890
+ if (isClosed) return;
891
+ const timeout = Math.min(1e3 * Math.pow(2, retryCount), 1e4);
892
+ retryCount++;
893
+ console.warn(
894
+ `[NexusHub] \u{1F534} Stream disconnected. Reconnecting in ${timeout}ms...`
895
+ );
896
+ setTimeout(connect, timeout);
897
+ };
898
+ };
899
+ connect();
900
+ return () => {
901
+ isClosed = true;
902
+ _optionalChain([eventSource, 'optionalAccess', _22 => _22.close, 'call', _23 => _23()]);
903
+ };
904
+ }
905
+ // --- CACHE MANAGEMENT ---
906
+ /**
907
+ * Check all caches in order of speed
908
+ */
909
+ checkCaches(key, forceRefresh, includeMetadata) {
910
+ if (forceRefresh) return null;
911
+ if (this.cacheStrategy === "memory") {
912
+ const cached = this.memoryCache.get(key);
913
+ if (cached && this.isCacheValid(cached.metadata)) {
914
+ return cached;
915
+ }
916
+ }
917
+ if (!this.isServer && this.cacheStrategy === "localStorage" && this.browserCache) {
918
+ const cached = this.browserCache.get(key);
919
+ if (cached) {
920
+ return {
921
+ data: cached,
922
+ metadata: {
923
+ timestamp: 0,
924
+ expiresAt: Infinity,
925
+ tags: [],
926
+ etag: void 0
927
+ }
928
+ };
929
+ }
930
+ }
931
+ if (process.env.NODE_ENV === "development") {
932
+ if (key.startsWith("page:")) {
933
+ const slug = key.split(":")[1];
934
+ const local = this.localCache.getPage(slug);
935
+ if (local) {
936
+ return {
937
+ data: local,
938
+ metadata: {
939
+ timestamp: 0,
940
+ expiresAt: Infinity,
941
+ tags: [],
942
+ etag: void 0
943
+ }
944
+ };
945
+ }
946
+ }
947
+ }
948
+ return null;
949
+ }
950
+ writeCache(key, data, options) {
951
+ if (this.cacheStrategy === "memory") {
952
+ this.memoryCache.set(key, data, {
953
+ tags: options.tags,
954
+ revalidate: options.revalidate
955
+ });
956
+ }
957
+ if (!this.isServer && this.cacheStrategy === "localStorage" && this.browserCache) {
958
+ this.browserCache.set(key, data, options.revalidate * 1e3);
959
+ }
960
+ }
961
+ /**
962
+ * Invalidate cache by tags
963
+ */
964
+ invalidateCache(tags) {
965
+ this.memoryCache.invalidateByTags(tags);
966
+ if (this.config.debug) {
967
+ console.log(
968
+ `[NexusHub] \u267B\uFE0F Invalidated cache for tags: ${tags.join(", ")}`
969
+ );
970
+ }
971
+ }
972
+ /**
973
+ * Clear all caches
974
+ */
975
+ clearCache() {
976
+ this.memoryCache.clear();
977
+ if (this.browserCache) {
978
+ this.browserCache.clear();
979
+ }
980
+ if (this.config.debug) {
981
+ console.log("[NexusHub] \u{1F9F9} Cleared all caches");
982
+ }
983
+ }
984
+ /**
985
+ * Get cache statistics
986
+ */
987
+ getCacheStats() {
988
+ const stats = {
989
+ memory: this.memoryCache.getStats(),
990
+ local: { loaded: this.localCache.isLoaded() }
991
+ };
992
+ if (this.browserCache) {
993
+ stats.browser = { size: 0 };
994
+ }
995
+ return stats;
996
+ }
997
+ // --- REQUEST METHODS ---
998
+ async fetchPage(slug, cacheKey, tags, revalidate, forceRefresh) {
999
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/page/${slug}`;
1000
+ if (this.config.debug) {
1001
+ console.log(`[NexusHub] \u{1F310} Fetching: ${url}`);
1002
+ }
1003
+ const res = await this.fetchWithTimeout(url, {
1004
+ method: "GET",
1005
+ headers: this.getHeaders()
1006
+ });
1007
+ if (!res.ok) {
1008
+ if (res.status === 404) {
1009
+ throw new Error(
1010
+ `Page '${slug}' not found. Check your Dashboard or Seed data.`
1011
+ );
1012
+ }
1013
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
1014
+ }
1015
+ const json = await res.json();
1016
+ const etag = res.headers.get("etag");
1017
+ const cacheEntry = {
1018
+ data: json.data,
1019
+ metadata: {
1020
+ timestamp: Date.now(),
1021
+ etag: etag || void 0,
1022
+ expiresAt: Date.now() + revalidate * 1e3,
1023
+ tags: [...tags, CacheTags.content(slug)]
1024
+ }
1025
+ };
1026
+ this.writeCache(cacheKey, cacheEntry.data, {
1027
+ revalidate,
1028
+ tags: [
1029
+ CacheTags.project(this.config.projectId),
1030
+ CacheTags.content(slug),
1031
+ ...tags
1032
+ ]
1033
+ });
1034
+ return cacheEntry;
1035
+ }
1036
+ async fetchCollection(collectionId, query, cacheKey, tags, revalidate) {
1037
+ const params = buildQueryString(query);
1038
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/collection/${collectionId}?${params}`;
1039
+ if (this.config.debug) {
1040
+ console.log(`[NexusHub] \u{1F310} Fetching Collection: ${url}`);
1041
+ }
1042
+ const res = await this.fetchWithTimeout(url, {
1043
+ method: "GET",
1044
+ headers: this.getHeaders()
1045
+ });
1046
+ if (!res.ok) {
1047
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
1048
+ }
1049
+ const json = await res.json();
1050
+ const etag = res.headers.get("etag");
1051
+ const cacheEntry = {
1052
+ data: json,
1053
+ metadata: {
1054
+ timestamp: Date.now(),
1055
+ etag: etag || void 0,
1056
+ expiresAt: Date.now() + revalidate * 1e3,
1057
+ tags: [...tags, CacheTags.collection(collectionId)]
1058
+ }
1059
+ };
1060
+ this.writeCache(cacheKey, cacheEntry.data, {
1061
+ revalidate,
1062
+ tags: [
1063
+ CacheTags.project(this.config.projectId),
1064
+ CacheTags.collection(collectionId),
1065
+ ...tags
1066
+ ]
1067
+ });
1068
+ return cacheEntry;
1069
+ }
1070
+ // --- HELPER METHODS ---
1071
+ applyLocalQuery(items, query) {
1072
+ let filtered = [...items];
1073
+ if (query.search) {
1074
+ const searchLower = query.search.toLowerCase();
1075
+ filtered = filtered.filter(
1076
+ (item) => JSON.stringify(item).toLowerCase().includes(searchLower)
1077
+ );
1078
+ }
1079
+ if (query.filter) {
1080
+ filtered = filtered.filter((item) => {
1081
+ return Object.entries(query.filter).every(([key, value]) => {
1082
+ const itemValue = item[key];
1083
+ if (itemValue === void 0) return false;
1084
+ if (Array.isArray(value)) {
1085
+ return value.includes(itemValue);
1086
+ }
1087
+ return itemValue === value;
1088
+ });
1089
+ });
1090
+ }
1091
+ if (query.sort) {
1092
+ filtered.sort((a, b) => {
1093
+ const aVal = a[query.sort];
1094
+ const bVal = b[query.sort];
1095
+ const order = query.order === "asc" ? 1 : -1;
1096
+ if (aVal < bVal) return -1 * order;
1097
+ if (aVal > bVal) return 1 * order;
1098
+ return 0;
1099
+ });
1100
+ }
1101
+ const page = query.page || 1;
1102
+ const limit = query.limit || 10;
1103
+ const start = (page - 1) * limit;
1104
+ const end = start + limit;
1105
+ const total = filtered.length;
1106
+ return {
1107
+ items: filtered.slice(start, end),
1108
+ total,
1109
+ page,
1110
+ limit,
1111
+ totalPages: Math.ceil(total / limit),
1112
+ hasNext: end < total,
1113
+ hasPrev: start > 0
1114
+ };
1115
+ }
1116
+ async fetchWithTimeout(url, options = {}) {
1117
+ const { timeout = this.config.timeout || 1e4, ...fetchOptions } = options;
1118
+ const controller = new AbortController();
1119
+ const id = setTimeout(() => controller.abort(), timeout);
1120
+ try {
1121
+ const response = await fetch(url, {
1122
+ ...fetchOptions,
1123
+ signal: controller.signal
1124
+ });
1125
+ clearTimeout(id);
1126
+ return response;
1127
+ } catch (error) {
1128
+ clearTimeout(id);
1129
+ throw error;
1130
+ }
1131
+ }
1132
+ getHeaders() {
1133
+ const headers = {
1134
+ "Content-Type": "application/json",
1135
+ "X-Nexus-Client": "client-sdk/1.0.0",
1136
+ "X-Nexus-Project": this.config.projectId
1137
+ };
1138
+ if (this.config.apiKey) {
1139
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
1140
+ }
1141
+ return headers;
1142
+ }
1143
+ isCacheValid(metadata) {
1144
+ return Date.now() < metadata.expiresAt;
1145
+ }
1146
+ normalizeError(error, context) {
1147
+ if (error instanceof Error) {
1148
+ if (error.name === "AbortError") {
1149
+ return new Error(`${context}: Request timeout`);
1150
+ }
1151
+ return error;
1152
+ }
1153
+ return new Error(`${context}: ${String(error)}`);
1154
+ }
1155
+ /**
1156
+ * Cancel ongoing requests
1157
+ */
1158
+ cancelRequests() {
1159
+ if (this.abortController) {
1160
+ this.abortController.abort();
1161
+ this.abortController = new AbortController();
1162
+ }
1163
+ }
1164
+ /**
1165
+ * Cleanup resources
1166
+ */
1167
+ cleanup() {
1168
+ this.cancelRequests();
1169
+ if (!this.isServer) {
1170
+ window.removeEventListener("beforeunload", this.cleanup.bind(this));
1171
+ }
1172
+ }
1173
+ };
1174
+
1175
+ // src/analytics/fingerprint.ts
1176
+ var getDeviceEntropy = async () => {
1177
+ if (typeof window === "undefined") return {};
1178
+ const nav = window.navigator;
1179
+ return {
1180
+ screen_resolution: `${window.screen.width}x${window.screen.height}`,
1181
+ color_depth: window.screen.colorDepth,
1182
+ pixel_ratio: window.devicePixelRatio || 1,
1183
+ hardware_concurrency: nav.hardwareConcurrency,
1184
+ device_memory: nav.deviceMemory,
1185
+ // Only available in Chrome/Edge
1186
+ timezone_offset: (/* @__PURE__ */ new Date()).getTimezoneOffset(),
1187
+ platform: nav.platform,
1188
+ language: nav.language,
1189
+ touch_support: "ontouchstart" in window || nav.maxTouchPoints > 0,
1190
+ // Optional: Calculate Canvas Fingerprint for high-security modes
1191
+ canvas_hash: await generateCanvasHash()
1192
+ };
1193
+ };
1194
+ var generateCanvasHash = async () => {
1195
+ try {
1196
+ const canvas = document.createElement("canvas");
1197
+ const ctx = canvas.getContext("2d");
1198
+ if (!ctx) return "";
1199
+ canvas.width = 200;
1200
+ canvas.height = 50;
1201
+ ctx.textBaseline = "top";
1202
+ ctx.font = '16px "Arial"';
1203
+ ctx.textBaseline = "alphabetic";
1204
+ ctx.fillStyle = "#f60";
1205
+ ctx.fillRect(125, 1, 62, 20);
1206
+ ctx.fillStyle = "#069";
1207
+ ctx.fillText("NexusHub Rocks! <canvas> 1.0", 2, 15);
1208
+ ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
1209
+ ctx.fillText("NexusHub Rocks! <canvas> 1.0", 4, 17);
1210
+ const dataUrl = canvas.toDataURL();
1211
+ let hash = 0;
1212
+ for (let i = 0; i < dataUrl.length; i++) {
1213
+ const char = dataUrl.charCodeAt(i);
1214
+ hash = (hash << 5) - hash + char;
1215
+ hash = hash & hash;
1216
+ }
1217
+ return hash.toString(16);
1218
+ } catch (e5) {
1219
+ return "";
1220
+ }
1221
+ };
1222
+ var getVisitorId = async () => {
1223
+ if (typeof window === "undefined") return "server_visitor";
1224
+ const STORAGE_KEY = "nexus_vid";
1225
+ let vid = localStorage.getItem(STORAGE_KEY);
1226
+ if (!vid) {
1227
+ const entropy = await getDeviceEntropy();
1228
+ const random = Math.random().toString(36).substring(2, 15);
1229
+ const timestamp = Date.now().toString(36);
1230
+ const fingerprint = [
1231
+ entropy.screen_resolution,
1232
+ entropy.hardware_concurrency,
1233
+ entropy.timezone_offset,
1234
+ entropy.platform,
1235
+ entropy.canvas_hash
1236
+ ].join("|");
1237
+ let hash = 0;
1238
+ for (let i = 0; i < fingerprint.length; i++) {
1239
+ hash = (hash << 5) - hash + fingerprint.charCodeAt(i);
1240
+ hash |= 0;
1241
+ }
1242
+ vid = `vis_${hash.toString(16)}_${timestamp}_${random}`;
1243
+ localStorage.setItem(STORAGE_KEY, vid);
1244
+ }
1245
+ return vid;
1246
+ };
1247
+
1248
+ // src/analytics/vitals.ts
1249
+
1250
+
1251
+
1252
+
1253
+
1254
+
1255
+ var _webvitals = require('web-vitals');
1256
+ var METRIC_KEY_MAP = {
1257
+ CLS: "cls",
1258
+ LCP: "lcp",
1259
+ INP: "inp",
1260
+ TTFB: "ttfb",
1261
+ FCP: "fcp"
1262
+ };
1263
+ var VitalsCollector = class {
1264
+ constructor() {
1265
+ this.metrics = {};
1266
+ this.hasUpdates = false;
1267
+ if (typeof window !== "undefined") {
1268
+ this.init();
1269
+ }
1270
+ }
1271
+ init() {
1272
+ const recordMetric = (metric) => {
1273
+ const key = METRIC_KEY_MAP[metric.name];
1274
+ this.metrics[key] = metric.value;
1275
+ this.hasUpdates = true;
1276
+ };
1277
+ _webvitals.onCLS.call(void 0, recordMetric);
1278
+ _webvitals.onLCP.call(void 0, recordMetric);
1279
+ _webvitals.onTTFB.call(void 0, recordMetric);
1280
+ _webvitals.onINP.call(void 0, recordMetric);
1281
+ _webvitals.onFCP.call(void 0, recordMetric);
1282
+ const navEntry = performance.getEntriesByType("navigation")[0];
1283
+ if (navEntry) {
1284
+ this.metrics.navigation_timing = {
1285
+ dns_lookup: navEntry.domainLookupEnd - navEntry.domainLookupStart,
1286
+ tcp_connect: navEntry.connectEnd - navEntry.connectStart,
1287
+ request_time: navEntry.responseEnd - navEntry.requestStart,
1288
+ dom_load: navEntry.domComplete - navEntry.domInteractive
1289
+ };
1290
+ this.hasUpdates = true;
1291
+ }
1292
+ }
1293
+ getMetricsSnapshot() {
1294
+ if (!this.hasUpdates) return null;
1295
+ this.hasUpdates = false;
1296
+ return { ...this.metrics };
1297
+ }
1298
+ };
1299
+ var vitalsCollector = new VitalsCollector();
1300
+ var initVitals = (tracker) => {
1301
+ if (process.env.NODE_ENV === "development") {
1302
+ console.log("[NexusHub] Web Vitals monitoring active");
1303
+ }
1304
+ };
1305
+
1306
+ // src/analytics/storage.ts
1307
+ var DB_NAME = "NexusHub_Analytics";
1308
+ var STORE_NAME = "events_queue";
1309
+ var DB_VERSION = 1;
1310
+ var EventStorage = class {
1311
+ constructor() {
1312
+ this.db = null;
1313
+ this.isReady = this.init();
1314
+ }
1315
+ init() {
1316
+ if (typeof window === "undefined" || !window.indexedDB) {
1317
+ return Promise.resolve();
1318
+ }
1319
+ return new Promise((resolve, reject) => {
1320
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
1321
+ request.onerror = () => {
1322
+ console.warn("[NexusHub] Failed to open IndexedDB. Falling back to memory.");
1323
+ resolve();
1324
+ };
1325
+ request.onsuccess = (event) => {
1326
+ this.db = event.target.result;
1327
+ resolve();
1328
+ };
1329
+ request.onupgradeneeded = (event) => {
1330
+ const db = event.target.result;
1331
+ if (!db.objectStoreNames.contains(STORE_NAME)) {
1332
+ db.createObjectStore(STORE_NAME, { keyPath: "id", autoIncrement: true });
1333
+ }
1334
+ };
1335
+ });
1336
+ }
1337
+ /**
1338
+ * Add an event to the persistent queue
1339
+ */
1340
+ async enqueue(payload) {
1341
+ await this.isReady;
1342
+ if (!this.db) return;
1343
+ return new Promise((resolve, reject) => {
1344
+ const transaction = this.db.transaction([STORE_NAME], "readwrite");
1345
+ const store = transaction.objectStore(STORE_NAME);
1346
+ const request = store.add({
1347
+ payload,
1348
+ timestamp: Date.now(),
1349
+ retryCount: 0
1350
+ });
1351
+ request.onsuccess = () => resolve();
1352
+ request.onerror = () => reject(request.error);
1353
+ });
1354
+ }
1355
+ /**
1356
+ * Get a batch of oldest events
1357
+ */
1358
+ async peek(limit = 20) {
1359
+ await this.isReady;
1360
+ if (!this.db) return [];
1361
+ return new Promise((resolve) => {
1362
+ const transaction = this.db.transaction([STORE_NAME], "readonly");
1363
+ const store = transaction.objectStore(STORE_NAME);
1364
+ const request = store.getAll(null, limit);
1365
+ request.onsuccess = () => resolve(request.result);
1366
+ request.onerror = () => resolve([]);
1367
+ });
1368
+ }
1369
+ /**
1370
+ * Remove events after successful upload
1371
+ */
1372
+ async remove(ids) {
1373
+ await this.isReady;
1374
+ if (!this.db || ids.length === 0) return;
1375
+ return new Promise((resolve, reject) => {
1376
+ const transaction = this.db.transaction([STORE_NAME], "readwrite");
1377
+ const store = transaction.objectStore(STORE_NAME);
1378
+ let processed = 0;
1379
+ let errors = 0;
1380
+ transaction.oncomplete = () => resolve();
1381
+ transaction.onerror = () => reject(transaction.error);
1382
+ ids.forEach((id) => {
1383
+ const req = store.delete(id);
1384
+ });
1385
+ });
1386
+ }
1387
+ /**
1388
+ * Count pending events
1389
+ */
1390
+ async count() {
1391
+ await this.isReady;
1392
+ if (!this.db) return 0;
1393
+ return new Promise((resolve) => {
1394
+ const transaction = this.db.transaction([STORE_NAME], "readonly");
1395
+ const store = transaction.objectStore(STORE_NAME);
1396
+ const request = store.count();
1397
+ request.onsuccess = () => resolve(request.result);
1398
+ request.onerror = () => resolve(0);
1399
+ });
1400
+ }
1401
+ };
1402
+ var eventStorage = new EventStorage();
1403
+
1404
+ // src/analytics/tracker.ts
1405
+ var Tracker = class {
1406
+ // 🆕
1407
+ constructor(config) {
1408
+ this.sessionId = "";
1409
+ this.visitorId = "";
1410
+ // FIX: Add this property
1411
+ this.isFlushing = false;
1412
+ this.config = config;
1413
+ const baseUrl = this.config.apiUrl.replace("/v1", "").replace(/\/$/, "");
1414
+ this.endpoint = `${this.config.analyticsUrl}/api/collect`;
1415
+ this.circuitBreaker = new CircuitBreaker();
1416
+ this.sessionStart = Date.now();
1417
+ if (typeof window !== "undefined") {
1418
+ this.initSession();
1419
+ this.startFlushing();
1420
+ }
1421
+ }
1422
+ async initSession() {
1423
+ this.visitorId = await getVisitorId();
1424
+ let sid = localStorage.getItem("nexus_sid");
1425
+ let lastActivity = localStorage.getItem("nexus_last_active");
1426
+ const now = Date.now();
1427
+ const SESSION_TIMEOUT = 30 * 60 * 1e3;
1428
+ if (!sid || !lastActivity || now - parseInt(lastActivity) > SESSION_TIMEOUT) {
1429
+ sid = `sess_${Math.random().toString(36).substring(2, 9)}_${now}`;
1430
+ localStorage.setItem("nexus_sid", sid);
1431
+ this.sessionStart = now;
1432
+ }
1433
+ localStorage.setItem("nexus_last_active", now.toString());
1434
+ this.sessionId = sid;
1435
+ }
1436
+ async send(eventType, data = {}, eventName) {
1437
+ if (typeof window === "undefined") return;
1438
+ localStorage.setItem("nexus_last_active", Date.now().toString());
1439
+ const entropy = await getDeviceEntropy();
1440
+ const perfMetrics = vitalsCollector.getMetricsSnapshot();
1441
+ const payload = {
1442
+ project_id: this.config.projectId,
1443
+ session_id: this.sessionId,
1444
+ // We send this, Rust verifies it
1445
+ url: window.location.href,
1446
+ referrer: document.referrer,
1447
+ user_agent: window.navigator.userAgent,
1448
+ screen_width: window.screen.width,
1449
+ screen_height: window.screen.height,
1450
+ language: window.navigator.language,
1451
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
1452
+ event_type: eventType,
1453
+ event_name: eventName,
1454
+ event_data: data,
1455
+ // 3. Attach Performance Data (Rust: Option<PerformanceMetrics>)
1456
+ performance: perfMetrics || void 0,
1457
+ // 4. Attach Hardware Signals for Anomaly Detection (Rust: DeviceData)
1458
+ context: {
1459
+ device: {
1460
+ hardware_concurrency: entropy.hardware_concurrency,
1461
+ device_memory: entropy.device_memory,
1462
+ pixel_ratio: entropy.pixel_ratio,
1463
+ canvas_fingerprint: entropy.canvas_hash,
1464
+ platform: entropy.platform
1465
+ },
1466
+ visitor_id_local: this.visitorId
1467
+ // Hint for stitching
1468
+ },
1469
+ client_timestamp: (/* @__PURE__ */ new Date()).toISOString()
1470
+ };
1471
+ await eventStorage.enqueue(payload);
1472
+ const count = await eventStorage.count();
1473
+ if (count >= 10 || eventType === "purchase" || eventType === "identify") {
1474
+ this.flushQueue();
1475
+ }
1476
+ }
1477
+ startFlushing() {
1478
+ this.flushInterval = setInterval(() => this.flushQueue(), 5e3);
1479
+ window.addEventListener("visibilitychange", () => {
1480
+ if (document.visibilityState === "hidden") this.flushQueue(true);
1481
+ });
1482
+ }
1483
+ async flushQueue(useBeacon = false) {
1484
+ if (this.isFlushing) return;
1485
+ if (this.circuitBreaker.isOpen()) {
1486
+ return;
1487
+ }
1488
+ this.isFlushing = true;
1489
+ try {
1490
+ const storedEvents = await eventStorage.peek(20);
1491
+ if (storedEvents.length === 0) {
1492
+ this.isFlushing = false;
1493
+ return;
1494
+ }
1495
+ const payloads = storedEvents.map((e) => e.payload);
1496
+ const promises = payloads.map(
1497
+ (event) => fetch(this.endpoint, {
1498
+ method: "POST",
1499
+ headers: {
1500
+ "Content-Type": "application/json",
1501
+ Authorization: `Bearer ${this.config.apiKey}`
1502
+ },
1503
+ body: JSON.stringify(event),
1504
+ keepalive: useBeacon
1505
+ })
1506
+ );
1507
+ const results = await Promise.allSettled(promises);
1508
+ const successIds = [];
1509
+ let failureCount = 0;
1510
+ results.forEach((res, index) => {
1511
+ if (res.status === "fulfilled" && res.value.ok) {
1512
+ successIds.push(storedEvents[index].id);
1513
+ } else {
1514
+ failureCount++;
1515
+ }
1516
+ });
1517
+ if (successIds.length > 0) {
1518
+ await eventStorage.remove(successIds);
1519
+ this.circuitBreaker.recordSuccess();
1520
+ }
1521
+ if (failureCount > 0) {
1522
+ this.circuitBreaker.recordFailure();
1523
+ }
1524
+ } catch (err) {
1525
+ console.error("[NexusHub] Network Error:", err);
1526
+ this.circuitBreaker.recordFailure();
1527
+ } finally {
1528
+ this.isFlushing = false;
1529
+ if (!this.circuitBreaker.isOpen() && await eventStorage.count() > 0) {
1530
+ setTimeout(() => this.flushQueue(), 100);
1531
+ }
1532
+ }
1533
+ }
1534
+ getSession() {
1535
+ return this.sessionId;
1536
+ }
1537
+ // FIX: Add this method to satisfy AnalyticsEngine
1538
+ getSessionDuration() {
1539
+ return Date.now() - this.sessionStart;
1540
+ }
1541
+ // FIX: Add this method to satisfy AnalyticsEngine
1542
+ stop() {
1543
+ if (this.flushInterval) {
1544
+ clearInterval(this.flushInterval);
1545
+ }
1546
+ this.flushQueue(true);
1547
+ }
1548
+ };
1549
+
1550
+ // src/analytics/index.ts
1551
+ var AnalyticsEngine = class {
1552
+ constructor(config) {
1553
+ this.cleanupFns = [];
1554
+ this.isInitialized = false;
1555
+ this.tracker = new Tracker(config);
1556
+ }
1557
+ start() {
1558
+ if (this.isInitialized || typeof window === "undefined") return;
1559
+ this.isInitialized = true;
1560
+ this.pageView();
1561
+ initVitals(this.tracker);
1562
+ this.setupClickTracking();
1563
+ this.setupFormTracking();
1564
+ this.setupRouteTracking();
1565
+ this.setupShareTracking();
1566
+ console.log("[NexusHub] \u{1F680} Analytics Engine Started");
1567
+ }
1568
+ pageView() {
1569
+ if (typeof window === "undefined") return;
1570
+ this.tracker.send("page_view", {
1571
+ path: window.location.pathname,
1572
+ search: window.location.search,
1573
+ title: document.title,
1574
+ timezone_offset: (/* @__PURE__ */ new Date()).getTimezoneOffset()
1575
+ });
1576
+ }
1577
+ // 🆕 PRIVATE: Track "Dark Social" Intent
1578
+ setupShareTracking() {
1579
+ if (typeof window === "undefined") return;
1580
+ const copyHandler = () => {
1581
+ this.tracker.send("social_share", {
1582
+ method: "clipboard_copy",
1583
+ url: window.location.href
1584
+ });
1585
+ };
1586
+ if (navigator.share) {
1587
+ const originalShare = navigator.share;
1588
+ navigator.share = (data) => {
1589
+ this.tracker.send("social_share", {
1590
+ method: "native_share_menu",
1591
+ url: _optionalChain([data, 'optionalAccess', _24 => _24.url]) || window.location.href,
1592
+ title: _optionalChain([data, 'optionalAccess', _25 => _25.title])
1593
+ });
1594
+ return originalShare.apply(navigator, [data]);
1595
+ };
1596
+ }
1597
+ window.addEventListener("copy", copyHandler, { passive: true });
1598
+ this.cleanupFns.push(() => window.removeEventListener("copy", copyHandler));
1599
+ }
1600
+ // --- IDENTITY & B2B (The Missing Pieces) ---
1601
+ /**
1602
+ * 1. IDENTIFY: Link anonymous session to a User ID
1603
+ */
1604
+ async identify(userId, traits = {}) {
1605
+ return this.sendIdentityRequest("identify", {
1606
+ user_id: userId,
1607
+ traits
1608
+ });
1609
+ }
1610
+ /**
1611
+ * 2. GROUP: Link the current user to a Company/Organization (B2B)
1612
+ * Required for the /api/group Rust route.
1613
+ */
1614
+ async group(groupId, traits = {}) {
1615
+ return this.sendIdentityRequest("group", {
1616
+ group_id: groupId,
1617
+ // The Rust backend handles looking up the user from the session if not provided,
1618
+ // but passing the user_id if known is safer.
1619
+ traits
1620
+ });
1621
+ }
1622
+ /**
1623
+ * 3. ALIAS: Merge two identities (e.g. "Guest_123" -> "User_99")
1624
+ * Required for the /api/alias Rust route.
1625
+ */
1626
+ async alias(newId) {
1627
+ return this.sendIdentityRequest("alias", {
1628
+ previous_id: this.tracker.getSession(),
1629
+ // Or the old visitor_id
1630
+ user_id: newId
1631
+ });
1632
+ }
1633
+ /**
1634
+ * 4. RESET: Clear local data and (optionally) request GDPR scrub
1635
+ */
1636
+ reset(performGdprScrub = false) {
1637
+ const config = this.tracker["config"];
1638
+ this.tracker.stop();
1639
+ localStorage.removeItem("nexus_sid");
1640
+ localStorage.removeItem("nexus_vid");
1641
+ if (performGdprScrub) {
1642
+ const endpoint = `${config.analyticsUrl}/api/privacy/scrub`;
1643
+ const userId = this.tracker.visitorId;
1644
+ fetch(endpoint, {
1645
+ method: "DELETE",
1646
+ headers: {
1647
+ "Content-Type": "application/json",
1648
+ Authorization: `Bearer ${config.apiKey}`
1649
+ },
1650
+ body: JSON.stringify({
1651
+ project_id: config.projectId,
1652
+ user_id: userId
1653
+ })
1654
+ }).catch((err) => console.error("[NexusHub] Privacy scrub failed:", err));
1655
+ }
1656
+ window.location.reload();
1657
+ }
1658
+ // --- E-COMMERCE & CUSTOM ---
1659
+ track(eventName, properties = {}) {
1660
+ this.tracker.send(
1661
+ "custom_event",
1662
+ { event_name: eventName, ...properties },
1663
+ eventName
1664
+ );
1665
+ }
1666
+ trackPurchase(orderData) {
1667
+ this.tracker.send("purchase", {
1668
+ ...orderData,
1669
+ currency: orderData.currency || "USD",
1670
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1671
+ });
1672
+ }
1673
+ trackError(error, context) {
1674
+ this.tracker.send("error", {
1675
+ message: error.message,
1676
+ stack: error.stack,
1677
+ context,
1678
+ url: typeof window !== "undefined" ? window.location.href : ""
1679
+ });
1680
+ }
1681
+ // --- INTERNAL HELPER ---
1682
+ async sendIdentityRequest(type, data) {
1683
+ try {
1684
+ const config = this.tracker["config"];
1685
+ const endpoint = `${config.analyticsUrl}/api/${type}`;
1686
+ const payload = {
1687
+ project_id: this.tracker["config"].projectId,
1688
+ session_id: this.tracker.getSession(),
1689
+ visitor_id: this.tracker.visitorId,
1690
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1691
+ ...data
1692
+ };
1693
+ if (type === "group" && !payload.user_id) {
1694
+ }
1695
+ const response = await fetch(endpoint, {
1696
+ method: "POST",
1697
+ headers: {
1698
+ "Content-Type": "application/json",
1699
+ Authorization: `Bearer ${this.tracker["config"].apiKey}`
1700
+ },
1701
+ body: JSON.stringify(payload)
1702
+ });
1703
+ if (response.ok) {
1704
+ this.tracker.send(type, data);
1705
+ return true;
1706
+ }
1707
+ return false;
1708
+ } catch (error) {
1709
+ console.error(`[NexusHub] ${type} failed:`, error);
1710
+ return false;
1711
+ }
1712
+ }
1713
+ // --- PRIVATE EVENT LISTENERS (Keep existing setupClickTracking, setupFormTracking, setupRouteTracking) ---
1714
+ setupClickTracking() {
1715
+ if (typeof window === "undefined") return;
1716
+ const clickHandler = (e) => {
1717
+ const target = e.target;
1718
+ const link = target.closest("a");
1719
+ if (link) {
1720
+ this.tracker.send("click", {
1721
+ element_type: "link",
1722
+ href: link.href,
1723
+ text: _optionalChain([link, 'access', _26 => _26.innerText, 'optionalAccess', _27 => _27.substring, 'call', _28 => _28(0, 50)]),
1724
+ id: link.id,
1725
+ classes: link.className,
1726
+ dataset: { ...link.dataset }
1727
+ });
1728
+ }
1729
+ const button = target.closest("button");
1730
+ if (button) {
1731
+ this.tracker.send("click", {
1732
+ element_type: "button",
1733
+ text: _optionalChain([button, 'access', _29 => _29.innerText, 'optionalAccess', _30 => _30.substring, 'call', _31 => _31(0, 50)]),
1734
+ id: button.id,
1735
+ classes: button.className,
1736
+ coordinates: { x: e.clientX, y: e.clientY }
1737
+ });
1738
+ }
1739
+ };
1740
+ window.addEventListener("click", clickHandler, { passive: true });
1741
+ this.cleanupFns.push(
1742
+ () => window.removeEventListener("click", clickHandler)
1743
+ );
1744
+ }
1745
+ setupFormTracking() {
1746
+ if (typeof document === "undefined") return;
1747
+ const submitHandler = (e) => {
1748
+ const form = e.target;
1749
+ if (form) {
1750
+ this.tracker.send("form_submit", {
1751
+ form_id: form.id || form.name || "unknown_form",
1752
+ action: form.action,
1753
+ method: form.method,
1754
+ field_count: form.elements.length
1755
+ });
1756
+ }
1757
+ };
1758
+ document.addEventListener("submit", submitHandler, { passive: true });
1759
+ this.cleanupFns.push(
1760
+ () => document.removeEventListener("submit", submitHandler)
1761
+ );
1762
+ }
1763
+ setupRouteTracking() {
1764
+ if (typeof window === "undefined" || typeof window.history === "undefined")
1765
+ return;
1766
+ const originalPushState = history.pushState;
1767
+ const originalReplaceState = history.replaceState;
1768
+ history.pushState = (...args) => {
1769
+ originalPushState.apply(history, args);
1770
+ this.pageView();
1771
+ };
1772
+ history.replaceState = (...args) => {
1773
+ originalReplaceState.apply(history, args);
1774
+ this.pageView();
1775
+ };
1776
+ const popStateHandler = () => this.pageView();
1777
+ window.addEventListener("popstate", popStateHandler);
1778
+ this.cleanupFns.push(
1779
+ () => window.removeEventListener("popstate", popStateHandler)
1780
+ );
1781
+ }
1782
+ getSessionId() {
1783
+ return this.tracker.getSession();
1784
+ }
1785
+ stop() {
1786
+ this.cleanupFns.forEach((fn) => fn());
1787
+ this.cleanupFns = [];
1788
+ this.tracker.send("session_end", {
1789
+ session_id: this.tracker.getSession(),
1790
+ duration: this.tracker.getSessionDuration()
1791
+ });
1792
+ this.tracker.stop();
1793
+ this.isInitialized = false;
1794
+ }
1795
+ };
1796
+
1797
+ // src/client.ts
1798
+ var NexusClient = class {
1799
+ // Make this public/accessible
1800
+ constructor(config) {
1801
+ const fullConfig = getFullConfig(config);
1802
+ this.config = {
1803
+ debug: _optionalChain([config, 'optionalAccess', _32 => _32.debug]) || false,
1804
+ cacheStrategy: _optionalChain([config, 'optionalAccess', _33 => _33.cacheStrategy]) || "memory",
1805
+ revalidateTime: _optionalChain([config, 'optionalAccess', _34 => _34.revalidateTime]) || 60,
1806
+ timeout: _optionalChain([config, 'optionalAccess', _35 => _35.timeout]) || 1e4,
1807
+ retries: _optionalChain([config, 'optionalAccess', _36 => _36.retries]) || 3,
1808
+ ...fullConfig
1809
+ };
1810
+ this.content = new ContentEngine(this.config);
1811
+ if (typeof window !== "undefined") {
1812
+ this.analytics = new AnalyticsEngine(this.config);
1813
+ this.analytics.start();
1814
+ }
1815
+ const errors = validateConfig(this.config);
1816
+ if (errors.length > 0) {
1817
+ console.warn("\u26A0\uFE0F NexusHub: Configuration issues:", errors.join(", "));
1818
+ if (!this.config.projectId) {
1819
+ console.warn("\u26A0\uFE0F NexusHub: No Project ID found. Content fetching will fail.");
1820
+ }
1821
+ }
1822
+ this.content = new ContentEngine(this.config);
1823
+ }
1824
+ // Helper alias for cleaner code
1825
+ getPage(slug, options) {
1826
+ return this.content.getPage(slug, options);
1827
+ }
1828
+ // Get current config (readonly)
1829
+ getConfig() {
1830
+ return { ...this.config };
1831
+ }
1832
+ };
1833
+ var nexus = new NexusClient();
1834
+ var createNexusClient = (config) => new NexusClient(config);
1835
+
1836
+ // src/components/NexusProvider.tsx
1837
+ var _react = require('react'); var _react2 = _interopRequireDefault(_react);
1838
+ var _navigation = require('next/navigation');
1839
+
1840
+ // src/auth/context.tsx
1841
+
1842
+ var _jsxruntime = require('react/jsx-runtime');
1843
+ var AuthContext = _react.createContext.call(void 0, null);
1844
+ var AuthProvider = ({
1845
+ children,
1846
+ config
1847
+ }) => {
1848
+ const [user, setUser] = _react.useState.call(void 0, null);
1849
+ const [isLoading, setIsLoading] = _react.useState.call(void 0, true);
1850
+ const [error, setError] = _react.useState.call(void 0, null);
1851
+ const AUTH_BASE = `${config.apiUrl}/auth/project/${config.projectId}`;
1852
+ const checkSession = _react.useCallback.call(void 0, async () => {
1853
+ try {
1854
+ const res = await fetch(`${AUTH_BASE}/me`, {
1855
+ headers: getHeaders(config)
1856
+ });
1857
+ if (res.ok) {
1858
+ const data = await res.json();
1859
+ setUser(data.user);
1860
+ if (nexus.analytics) {
1861
+ nexus.analytics.identify(data.user.id, {
1862
+ email: data.user.email,
1863
+ role: data.user.role,
1864
+ ...data.user.metadata
1865
+ });
1866
+ }
1867
+ } else {
1868
+ setUser(null);
1869
+ }
1870
+ } catch (err) {
1871
+ console.debug("[NexusHub Auth] Session check failed:", err);
1872
+ setUser(null);
1873
+ } finally {
1874
+ setIsLoading(false);
1875
+ }
1876
+ }, [AUTH_BASE, config]);
1877
+ _react.useEffect.call(void 0, () => {
1878
+ checkSession();
1879
+ }, [checkSession]);
1880
+ const login = async (creds) => {
1881
+ setIsLoading(true);
1882
+ setError(null);
1883
+ try {
1884
+ const res = await fetch(`${AUTH_BASE}/login`, {
1885
+ method: "POST",
1886
+ headers: getHeaders(config),
1887
+ body: JSON.stringify(creds)
1888
+ });
1889
+ if (!res.ok) throw await parseError(res);
1890
+ const data = await res.json();
1891
+ setUser(data.user);
1892
+ if (nexus.analytics) {
1893
+ await nexus.analytics.identify(data.user.id, {
1894
+ email: data.user.email,
1895
+ role: data.user.role,
1896
+ login_method: "email",
1897
+ ...data.user.metadata
1898
+ });
1899
+ }
1900
+ } catch (err) {
1901
+ setError(err);
1902
+ throw err;
1903
+ } finally {
1904
+ setIsLoading(false);
1905
+ }
1906
+ };
1907
+ const register = async (creds) => {
1908
+ setIsLoading(true);
1909
+ setError(null);
1910
+ try {
1911
+ const res = await fetch(`${AUTH_BASE}/register`, {
1912
+ method: "POST",
1913
+ headers: getHeaders(config),
1914
+ body: JSON.stringify(creds)
1915
+ });
1916
+ if (!res.ok) throw await parseError(res);
1917
+ const data = await res.json();
1918
+ setUser(data.user);
1919
+ if (nexus.analytics) {
1920
+ nexus.analytics.track("signup", { method: "email" });
1921
+ nexus.analytics.identify(data.user.id, {
1922
+ email: data.user.email,
1923
+ role: data.user.role,
1924
+ ...data.user.metadata
1925
+ });
1926
+ }
1927
+ } catch (err) {
1928
+ setError(err);
1929
+ throw err;
1930
+ } finally {
1931
+ setIsLoading(false);
1932
+ }
1933
+ };
1934
+ const logout = async () => {
1935
+ setIsLoading(true);
1936
+ try {
1937
+ await fetch(`${AUTH_BASE}/logout`, { method: "POST", headers: getHeaders(config) });
1938
+ } catch (e) {
1939
+ console.warn("Logout network error", e);
1940
+ } finally {
1941
+ setUser(null);
1942
+ setIsLoading(false);
1943
+ if (nexus.analytics) {
1944
+ nexus.analytics.track("logout");
1945
+ }
1946
+ }
1947
+ };
1948
+ const updateProfile = async (updates) => {
1949
+ try {
1950
+ const res = await fetch(`${AUTH_BASE}/profile`, {
1951
+ method: "PATCH",
1952
+ headers: getHeaders(config),
1953
+ body: JSON.stringify(updates)
1954
+ });
1955
+ if (!res.ok) throw await parseError(res);
1956
+ const data = await res.json();
1957
+ setUser(data.user);
1958
+ if (nexus.analytics) {
1959
+ nexus.analytics.identify(data.user.id, updates);
1960
+ }
1961
+ } catch (err) {
1962
+ setError(err);
1963
+ throw err;
1964
+ }
1965
+ };
1966
+ const requestPasswordReset = async (email) => {
1967
+ const res = await fetch(`${AUTH_BASE}/password/reset-request`, {
1968
+ method: "POST",
1969
+ headers: getHeaders(config),
1970
+ body: JSON.stringify({ email })
1971
+ });
1972
+ if (!res.ok) throw await parseError(res);
1973
+ };
1974
+ return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, AuthContext.Provider, { value: {
1975
+ user,
1976
+ isLoading,
1977
+ error,
1978
+ isAuthenticated: !!user,
1979
+ login,
1980
+ register,
1981
+ logout,
1982
+ updateProfile,
1983
+ requestPasswordReset
1984
+ }, children });
1985
+ };
1986
+ var useNexusAuth = () => {
1987
+ const context = _react.useContext.call(void 0, AuthContext);
1988
+ if (!context) {
1989
+ throw new Error("useNexusAuth must be used within a NexusProvider");
1990
+ }
1991
+ return context;
1992
+ };
1993
+ function getHeaders(config) {
1994
+ return {
1995
+ "Content-Type": "application/json",
1996
+ "x-nexus-project": config.projectId
1997
+ // Note: We do NOT send the Master API Key here.
1998
+ // This is client-side. The backend uses Cookies or public tokens.
1999
+ };
2000
+ }
2001
+ async function parseError(res) {
2002
+ try {
2003
+ const json = await res.json();
2004
+ return {
2005
+ status: res.status,
2006
+ code: json.code || "UNKNOWN_ERROR",
2007
+ message: json.message || "An error occurred during authentication"
2008
+ };
2009
+ } catch (e6) {
2010
+ return {
2011
+ status: res.status,
2012
+ code: "NETWORK_ERROR",
2013
+ message: res.statusText
2014
+ };
2015
+ }
2016
+ }
2017
+
2018
+ // src/components/NexusProvider.tsx
2019
+
2020
+ var NexusContext = _react.createContext.call(void 0, nexus);
2021
+ var NexusProvider = ({
2022
+ children,
2023
+ projectId,
2024
+ disableAnalytics = false
2025
+ }) => {
2026
+ const pathname = _navigation.usePathname.call(void 0, );
2027
+ const searchParams = _navigation.useSearchParams.call(void 0, );
2028
+ const isInitialized = _react.useRef.call(void 0, false);
2029
+ const config = _react.useMemo.call(void 0, () => {
2030
+ const currentConfig = nexus.getConfig();
2031
+ if (projectId && currentConfig.projectId !== projectId) {
2032
+ nexus.config.projectId = projectId;
2033
+ }
2034
+ return nexus.getConfig();
2035
+ }, [projectId]);
2036
+ _react.useEffect.call(void 0, () => {
2037
+ if (typeof window === "undefined" || disableAnalytics) return;
2038
+ if (!isInitialized.current) {
2039
+ if (!nexus.analytics) {
2040
+ nexus.analytics = new AnalyticsEngine(nexus.getConfig());
2041
+ }
2042
+ nexus.analytics.start();
2043
+ isInitialized.current = true;
2044
+ if (nexus.getConfig().debug) {
2045
+ console.log("[NexusHub] \u{1F680} Provider initialized analytics");
2046
+ }
2047
+ }
2048
+ return () => {
2049
+ if (nexus.analytics) {
2050
+ nexus.analytics.stop();
2051
+ isInitialized.current = false;
2052
+ }
2053
+ };
2054
+ }, [disableAnalytics]);
2055
+ _react.useEffect.call(void 0, () => {
2056
+ if (nexus.analytics && !disableAnalytics) {
2057
+ nexus.analytics.pageView();
2058
+ }
2059
+ }, [pathname, searchParams, disableAnalytics]);
2060
+ return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, NexusContext.Provider, { value: nexus, children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, AuthProvider, { config, children }) });
2061
+ };
2062
+
2063
+ // src/index.ts
2064
+ var VERSION = "0.0.1";
2065
+
2066
+
2067
+
2068
+
2069
+
2070
+
2071
+
2072
+
2073
+
2074
+
2075
+
2076
+
2077
+
2078
+
2079
+
2080
+
2081
+
2082
+
2083
+
2084
+
2085
+
2086
+
2087
+ exports.AnalyticsEngine = AnalyticsEngine; exports.AuthProvider = AuthProvider; exports.BrowserCache = BrowserCache; exports.CacheTags = CacheTags; exports.ContentEngine = ContentEngine; exports.DEFAULT_ANALYTICS_URL = DEFAULT_ANALYTICS_URL; exports.DEFAULT_API_URL = DEFAULT_API_URL; exports.LOCAL_NEST_URL = LOCAL_NEST_URL; exports.LOCAL_RUST_URL = LOCAL_RUST_URL; exports.LocalCache = LocalCache; exports.MemoryCache = MemoryCache; exports.NexusClient = NexusClient; exports.NexusProvider = NexusProvider; exports.VERSION = VERSION; exports.createNexusClient = createNexusClient; exports.getEnvConfig = getEnvConfig; exports.getFullConfig = getFullConfig; exports.mergeConfigs = mergeConfigs; exports.nexus = nexus; exports.useNexusAuth = useNexusAuth; exports.validateConfig = validateConfig;