@entrolytics/api-client 2.2.1 → 2.2.3

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 ADDED
@@ -0,0 +1,1708 @@
1
+ import { API_ENDPOINTS, API_ROUTES, API_ROUTES as API_ROUTES$1, BILLING_ERRORS, CLI_CONFIG, CLI_TOKEN_STATUS, DEFAULT_API_HOST, DEPLOYMENT_ENV_VARS, DEPLOYMENT_SOURCES, ENV_VAR_NAMES, ERROR_MESSAGES, EVENT_TYPES, FORM_EVENT_TYPES, FORM_FIELD_TYPES, FRAMEWORK_PACKAGES, FRAMEWORK_PATTERNS, HTTP_STATUS, NAVIGATION_TYPES, ONBOARDING_STEPS, PLANS, PLAN_FEATURES, RATE_LIMITS, SDK_EVENT_TYPES, SUCCESS_MESSAGES, USAGE_THRESHOLDS, USER_ROLES, VITAL_RATINGS, VITAL_THRESHOLDS, VITAL_TYPES, detectDeploymentContext, getApiRoute, getEnvVarNames, getFrameworkPackage, getPlan, getPlanLimit, getVitalRating, isPlanFeatureEnabled, isUsageCritical, isUsageWarning, isValidFramework } from "@entrolytics/shared";
2
+
3
+ //#region src/client.ts
4
+ function isRecord(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+ function unwrapSuccessPayload(payload) {
8
+ if (payload === void 0) return;
9
+ if (isRecord(payload) && "data" in payload) return payload.data;
10
+ return payload;
11
+ }
12
+ /**
13
+ * Core API client for making authenticated requests.
14
+ */
15
+ var ApiClient = class {
16
+ endpoint;
17
+ bearerToken;
18
+ apiKey;
19
+ fetchFn;
20
+ retries;
21
+ retryDelay;
22
+ constructor(config = {}) {
23
+ const getEnv = (key) => {
24
+ if (typeof process !== "undefined" && process.env) return process.env[key];
25
+ };
26
+ const rawEndpoint = config.endpoint || getEnv("ENTROLYTICS_API_ENDPOINT") || "";
27
+ this.endpoint = rawEndpoint ? rawEndpoint.endsWith("/") ? rawEndpoint : `${rawEndpoint}/` : "";
28
+ this.bearerToken = config.bearerToken || getEnv("ENTROLYTICS_BEARER_TOKEN");
29
+ this.apiKey = config.apiKey || getEnv("ENTROLYTICS_API_KEY");
30
+ this.fetchFn = config.fetch || globalThis.fetch;
31
+ this.retries = config.retries ?? 3;
32
+ this.retryDelay = config.retryDelay ?? 1e3;
33
+ if (!this.endpoint) throw new Error("Entrolytics API endpoint is required. Set ENTROLYTICS_API_ENDPOINT or pass endpoint in config.");
34
+ }
35
+ /**
36
+ * Update the bearer token (useful for token refresh).
37
+ */
38
+ setBearerToken(token) {
39
+ this.bearerToken = token;
40
+ }
41
+ /**
42
+ * Generate authentication headers.
43
+ * Priority: Bearer token > API key
44
+ */
45
+ getAuthHeaders() {
46
+ const headers = {};
47
+ if (this.bearerToken) headers.Authorization = `Bearer ${this.bearerToken}`;
48
+ else if (this.apiKey) headers["x-api-key"] = this.apiKey;
49
+ return headers;
50
+ }
51
+ /**
52
+ * Sleep helper for retry delays.
53
+ */
54
+ sleep(ms) {
55
+ return new Promise((resolve) => setTimeout(resolve, ms));
56
+ }
57
+ /**
58
+ * Check if error is retryable.
59
+ */
60
+ isRetryable(status) {
61
+ return status === 0 || status === 429 || status >= 500;
62
+ }
63
+ /**
64
+ * Build URL with query parameters.
65
+ */
66
+ buildUrl(path, params) {
67
+ const normalizedPath = path.startsWith("/") ? path.slice(1) : path;
68
+ const url = new URL(normalizedPath, this.endpoint);
69
+ if (params) Object.entries(params).forEach(([key, value]) => {
70
+ if (value !== void 0) url.searchParams.set(key, String(value));
71
+ });
72
+ return url.toString();
73
+ }
74
+ /**
75
+ * Make an authenticated API request with automatic retries.
76
+ */
77
+ async request(path, options = {}) {
78
+ const { method = "GET", body, params, headers = {} } = options;
79
+ const url = this.buildUrl(path, params);
80
+ let lastError = null;
81
+ for (let attempt = 0; attempt <= this.retries; attempt++) try {
82
+ const fetchOptions = {
83
+ method,
84
+ headers: {
85
+ "Content-Type": "application/json",
86
+ ...this.getAuthHeaders(),
87
+ ...headers
88
+ }
89
+ };
90
+ if (body) fetchOptions.body = JSON.stringify(body);
91
+ const response = await this.fetchFn(url, fetchOptions);
92
+ const data = response.status === 204 ? void 0 : await response.json().catch(() => void 0);
93
+ if (!response.ok) {
94
+ const errorMessage = isRecord(data) && typeof data.error === "string" ? data.error : isRecord(data) && typeof data.message === "string" ? data.message : `HTTP ${response.status}`;
95
+ lastError = {
96
+ ok: false,
97
+ status: response.status,
98
+ error: errorMessage
99
+ };
100
+ if (this.isRetryable(response.status) && attempt < this.retries) {
101
+ const delay = this.retryDelay * 2 ** attempt;
102
+ await this.sleep(delay);
103
+ continue;
104
+ }
105
+ return lastError;
106
+ }
107
+ return {
108
+ ok: true,
109
+ status: response.status,
110
+ data: unwrapSuccessPayload(data)
111
+ };
112
+ } catch (error) {
113
+ lastError = {
114
+ ok: false,
115
+ status: 0,
116
+ error: error instanceof Error ? error.message : "Network error"
117
+ };
118
+ if (attempt < this.retries) {
119
+ const delay = this.retryDelay * 2 ** attempt;
120
+ await this.sleep(delay);
121
+ }
122
+ }
123
+ return lastError ?? {
124
+ ok: false,
125
+ status: 0,
126
+ error: "Request failed after retries"
127
+ };
128
+ }
129
+ /**
130
+ * GET request helper.
131
+ */
132
+ get(path, params) {
133
+ return this.request(path, {
134
+ method: "GET",
135
+ params
136
+ });
137
+ }
138
+ /**
139
+ * POST request helper.
140
+ */
141
+ post(path, body) {
142
+ return this.request(path, {
143
+ method: "POST",
144
+ body
145
+ });
146
+ }
147
+ /**
148
+ * PUT request helper.
149
+ */
150
+ put(path, body) {
151
+ return this.request(path, {
152
+ method: "PUT",
153
+ body
154
+ });
155
+ }
156
+ /**
157
+ * DELETE request helper.
158
+ */
159
+ delete(path) {
160
+ return this.request(path, { method: "DELETE" });
161
+ }
162
+ /**
163
+ * PATCH request helper.
164
+ */
165
+ patch(path, body) {
166
+ return this.request(path, {
167
+ method: "PATCH",
168
+ body
169
+ });
170
+ }
171
+ };
172
+
173
+ //#endregion
174
+ //#region src/endpoints/admin.ts
175
+ function createAdminEndpoints(client) {
176
+ return {
177
+ /**
178
+ * Get all organizations (admin only)
179
+ */
180
+ getOrgs: () => client.get("/admin/orgs"),
181
+ /**
182
+ * Get organization details (admin only)
183
+ */
184
+ getOrg: ({ orgId }) => client.get(`/admin/orgs/${orgId}`),
185
+ /**
186
+ * Get all users (admin only)
187
+ */
188
+ getUsers: () => client.get("/admin/users"),
189
+ /**
190
+ * Get user details (admin only)
191
+ */
192
+ getUser: ({ userId }) => client.get(`/admin/users/${userId}`),
193
+ /**
194
+ * Get all websites (admin only)
195
+ */
196
+ getWebsites: () => client.get("/admin/websites"),
197
+ /**
198
+ * Get website details (admin only)
199
+ */
200
+ getWebsite: ({ websiteId }) => client.get(`/admin/websites/${websiteId}`),
201
+ /**
202
+ * Run admin setup
203
+ */
204
+ setup: () => client.post("/admin/setup", {})
205
+ };
206
+ }
207
+
208
+ //#endregion
209
+ //#region src/endpoints/auth.ts
210
+ function createAuthEndpoints(client) {
211
+ return {
212
+ /**
213
+ * List all active CLI access tokens for the current user.
214
+ */
215
+ listCliTokens() {
216
+ return client.get("/auth/cli/tokens");
217
+ },
218
+ /**
219
+ * Revoke a specific CLI access token by its JTI.
220
+ *
221
+ * @param jti - The JWT ID of the token to revoke
222
+ */
223
+ revokeCliToken(jti) {
224
+ return client["request"]("/auth/cli/tokens", {
225
+ method: "DELETE",
226
+ body: { jti }
227
+ });
228
+ },
229
+ /**
230
+ * Revoke all CLI access tokens for the current user.
231
+ */
232
+ revokeAllCliTokens() {
233
+ return client["request"]("/auth/cli/tokens", {
234
+ method: "DELETE",
235
+ body: { revokeAll: true }
236
+ });
237
+ }
238
+ };
239
+ }
240
+
241
+ //#endregion
242
+ //#region src/endpoints/billing.ts
243
+ function createBillingEndpoints(client) {
244
+ return {
245
+ /**
246
+ * Get current account usage for the billing period.
247
+ */
248
+ getUsage() {
249
+ return client.get("/billing/usage");
250
+ },
251
+ /**
252
+ * Get account entitlements based on current plan.
253
+ */
254
+ getEntitlements() {
255
+ return client.get("/billing/entitlements");
256
+ },
257
+ /**
258
+ * Get current subscription details.
259
+ */
260
+ getSubscription() {
261
+ return client.get("/billing/subscription");
262
+ },
263
+ /**
264
+ * Create a Stripe checkout session for upgrading/changing plan.
265
+ */
266
+ createCheckoutSession(options) {
267
+ return client.post("/billing/checkout", options);
268
+ },
269
+ /**
270
+ * Create a Stripe billing portal session for managing subscription.
271
+ */
272
+ createPortalSession() {
273
+ return client.post("/billing/portal");
274
+ }
275
+ };
276
+ }
277
+
278
+ //#endregion
279
+ //#region src/endpoints/boards.ts
280
+ function createBoardsEndpoints(client) {
281
+ return {
282
+ /**
283
+ * Get all boards for a website.
284
+ */
285
+ getBoards(websiteId) {
286
+ return client.get(`/websites/${websiteId}/boards`);
287
+ },
288
+ /**
289
+ * Get a specific board by ID.
290
+ */
291
+ getBoard(boardId) {
292
+ return client.get(`/boards/${boardId}`);
293
+ },
294
+ /**
295
+ * Create a new board.
296
+ */
297
+ createBoard(data) {
298
+ return client.post("/boards", data);
299
+ },
300
+ /**
301
+ * Update a board.
302
+ */
303
+ updateBoard(boardId, data) {
304
+ return client.post(`/boards/${boardId}`, data);
305
+ },
306
+ /**
307
+ * Delete a board.
308
+ */
309
+ deleteBoard(boardId) {
310
+ return client.delete(`/boards/${boardId}`);
311
+ },
312
+ /**
313
+ * Get all widgets for a board.
314
+ */
315
+ getBoardWidgets(boardId) {
316
+ return client.get(`/boards/${boardId}/widgets`);
317
+ },
318
+ /**
319
+ * Get a specific widget by ID.
320
+ */
321
+ getBoardWidget(boardId, widgetId) {
322
+ return client.get(`/boards/${boardId}/widgets/${widgetId}`);
323
+ },
324
+ /**
325
+ * Create a new widget on a board.
326
+ */
327
+ createBoardWidget(boardId, data) {
328
+ return client.post(`/boards/${boardId}/widgets`, data);
329
+ },
330
+ /**
331
+ * Update a widget.
332
+ */
333
+ updateBoardWidget(boardId, widgetId, data) {
334
+ return client.post(`/boards/${boardId}/widgets/${widgetId}`, data);
335
+ },
336
+ /**
337
+ * Delete a widget.
338
+ */
339
+ deleteBoardWidget(boardId, widgetId) {
340
+ return client.delete(`/boards/${boardId}/widgets/${widgetId}`);
341
+ }
342
+ };
343
+ }
344
+
345
+ //#endregion
346
+ //#region src/endpoints/config.ts
347
+ function createConfigEndpoints(client) {
348
+ return {
349
+ /**
350
+ * Get system configuration
351
+ */
352
+ get: () => client.get("/config") };
353
+ }
354
+
355
+ //#endregion
356
+ //#region src/endpoints/events.ts
357
+ function generateUuid() {
358
+ if (typeof globalThis.crypto !== "undefined" && typeof globalThis.crypto.randomUUID === "function") return globalThis.crypto.randomUUID();
359
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
360
+ const r = Math.floor(Math.random() * 16);
361
+ return (c === "x" ? r : r & 3 | 8).toString(16);
362
+ });
363
+ }
364
+ function createEventsEndpoints(client) {
365
+ return {
366
+ /**
367
+ * Get event data statistics.
368
+ */
369
+ getEventDataStats(websiteId, params) {
370
+ return client.get(`/websites/${websiteId}/event-data/stats`, params);
371
+ },
372
+ /**
373
+ * Get event data events (distinct event names).
374
+ */
375
+ getEventDataEvents(websiteId, params) {
376
+ return client.get(`/websites/${websiteId}/event-data/events`, params);
377
+ },
378
+ /**
379
+ * Get event data fields for a specific event.
380
+ */
381
+ getEventDataFields(websiteId, params) {
382
+ return client.get(`/websites/${websiteId}/event-data/fields`, params);
383
+ },
384
+ /**
385
+ * Get event data values for a specific field.
386
+ */
387
+ getEventDataValues(websiteId, params) {
388
+ return client.get(`/websites/${websiteId}/event-data/values`, params);
389
+ },
390
+ /**
391
+ * Get event data properties breakdown.
392
+ */
393
+ getEventDataProperties(websiteId, params) {
394
+ return client.get(`/websites/${websiteId}/event-data/properties`, params);
395
+ },
396
+ /**
397
+ * Get specific event data by ID.
398
+ */
399
+ getEventData(websiteId, eventId) {
400
+ return client.get(`/websites/${websiteId}/event-data/${eventId}`);
401
+ },
402
+ /**
403
+ * Get session data properties.
404
+ */
405
+ getSessionDataProperties(websiteId, params) {
406
+ return client.get(`/websites/${websiteId}/session-data/properties`, params);
407
+ },
408
+ getSessionDataValues(websiteId, params) {
409
+ return client.get(`/websites/${websiteId}/session-data/values`, params);
410
+ },
411
+ /**
412
+ * Send a test event to verify setup.
413
+ */
414
+ sendTestEvent(websiteId) {
415
+ return client.post("/collect", {
416
+ websiteId,
417
+ eventId: generateUuid(),
418
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
419
+ sessionId: generateUuid(),
420
+ visitorId: generateUuid(),
421
+ url: "https://entrolytics.click/test-event",
422
+ eventType: "custom_event",
423
+ eventName: "cli_test_event",
424
+ properties: {
425
+ source: "entro-cli",
426
+ timestamp: Date.now()
427
+ }
428
+ });
429
+ }
430
+ };
431
+ }
432
+
433
+ //#endregion
434
+ //#region src/endpoints/integrations.ts
435
+ function createIntegrationsEndpoints(client) {
436
+ return {
437
+ /**
438
+ * Handle WordPress integration
439
+ */
440
+ wordpress: (params) => client.post("/integrations/wordpress", params.data) };
441
+ }
442
+
443
+ //#endregion
444
+ //#region src/endpoints/links.ts
445
+ function createLinksEndpoints(client) {
446
+ return {
447
+ /**
448
+ * Get all links.
449
+ */
450
+ getLinks() {
451
+ return client.get("/links");
452
+ },
453
+ /**
454
+ * Get links for an organization.
455
+ */
456
+ getOrgLinks(orgId) {
457
+ return client.get(`/orgs/${orgId}/links`);
458
+ },
459
+ /**
460
+ * Create a new link.
461
+ */
462
+ createLink(orgId, data) {
463
+ return client.post(`/orgs/${orgId}/links`, data);
464
+ },
465
+ /**
466
+ * Get a link by ID.
467
+ */
468
+ getLink(linkId) {
469
+ return client.get(`/links/${linkId}`);
470
+ },
471
+ /**
472
+ * Update a link.
473
+ */
474
+ updateLink(linkId, data) {
475
+ return client.post(`/links/${linkId}`, data);
476
+ },
477
+ /**
478
+ * Delete a link.
479
+ */
480
+ deleteLink(linkId) {
481
+ return client.delete(`/links/${linkId}`);
482
+ },
483
+ /**
484
+ * Get link statistics.
485
+ */
486
+ getLinkStats(linkId) {
487
+ return client.get(`/links/${linkId}/stats`);
488
+ }
489
+ };
490
+ }
491
+
492
+ //#endregion
493
+ //#region src/endpoints/me.ts
494
+ function createMeEndpoints(client) {
495
+ return {
496
+ /**
497
+ * Get current user profile.
498
+ */
499
+ getMe() {
500
+ return client.get("/me");
501
+ },
502
+ /**
503
+ * Update current user's password.
504
+ */
505
+ updateMyPassword(data) {
506
+ return client.post("/me/password", data);
507
+ },
508
+ /**
509
+ * Get current user's websites.
510
+ */
511
+ getMyWebsites() {
512
+ return client.get("/me/websites");
513
+ },
514
+ /**
515
+ * Get current user's organizations.
516
+ */
517
+ getMyOrgs() {
518
+ return client.get("/me/orgs");
519
+ }
520
+ };
521
+ }
522
+
523
+ //#endregion
524
+ //#region src/endpoints/orgs.ts
525
+ function createOrgsEndpoints(client) {
526
+ return {
527
+ /**
528
+ * Get all organizations for the current user.
529
+ */
530
+ getOrgs() {
531
+ return client.get("/orgs");
532
+ },
533
+ /**
534
+ * Create a new organization.
535
+ */
536
+ createOrg(data) {
537
+ return client.post("/orgs", data);
538
+ },
539
+ /**
540
+ * Join an organization using access code.
541
+ */
542
+ joinOrg(data) {
543
+ return client.post("/orgs/join", data);
544
+ },
545
+ /**
546
+ * Get an organization by ID.
547
+ */
548
+ getOrg(orgId) {
549
+ return client.get(`/orgs/${orgId}`);
550
+ },
551
+ /**
552
+ * Update an organization.
553
+ */
554
+ updateOrg(orgId, data) {
555
+ return client.patch(`/orgs/${orgId}`, data);
556
+ },
557
+ /**
558
+ * Delete an organization.
559
+ */
560
+ deleteOrg(orgId) {
561
+ return client.delete(`/orgs/${orgId}`);
562
+ },
563
+ /**
564
+ * Get organization members.
565
+ */
566
+ getOrgMembers(orgId) {
567
+ return client.get(`/orgs/${orgId}/members`);
568
+ },
569
+ /**
570
+ * Invite a member to an organization.
571
+ */
572
+ inviteOrgMember(orgId, data) {
573
+ return client.post(`/orgs/${orgId}/members`, data);
574
+ },
575
+ /**
576
+ * Update an organization member's role.
577
+ */
578
+ updateOrgMember(orgId, memberId, data) {
579
+ return client.patch(`/orgs/${orgId}/members/${memberId}`, data);
580
+ },
581
+ /**
582
+ * Remove a member from an organization.
583
+ */
584
+ removeOrgMember(orgId, memberId) {
585
+ return client.delete(`/orgs/${orgId}/members/${memberId}`);
586
+ },
587
+ /**
588
+ * Get organization websites.
589
+ */
590
+ getOrgWebsites(orgId) {
591
+ return client.get(`/orgs/${orgId}/websites`);
592
+ },
593
+ /**
594
+ * Add a website to an organization.
595
+ */
596
+ addOrgWebsite(orgId, data) {
597
+ return client.post(`/orgs/${orgId}/websites`, data);
598
+ },
599
+ /**
600
+ * Remove a website from an organization.
601
+ */
602
+ removeOrgWebsite(orgId, websiteId) {
603
+ return client.delete(`/orgs/${orgId}/websites/${websiteId}`);
604
+ }
605
+ };
606
+ }
607
+
608
+ //#endregion
609
+ //#region src/endpoints/pixels.ts
610
+ function createPixelsEndpoints(client) {
611
+ return {
612
+ /**
613
+ * Get all pixels.
614
+ */
615
+ getPixels() {
616
+ return client.get("/pixels");
617
+ },
618
+ /**
619
+ * Get pixels for an organization.
620
+ */
621
+ getOrgPixels(orgId) {
622
+ return client.get(`/orgs/${orgId}/pixels`);
623
+ },
624
+ /**
625
+ * Create a new pixel.
626
+ */
627
+ createPixel(orgId, data) {
628
+ return client.post(`/orgs/${orgId}/pixels`, data);
629
+ },
630
+ /**
631
+ * Get a pixel by ID.
632
+ */
633
+ getPixel(pixelId) {
634
+ return client.get(`/pixels/${pixelId}`);
635
+ },
636
+ /**
637
+ * Update a pixel.
638
+ */
639
+ updatePixel(pixelId, data) {
640
+ return client.post(`/pixels/${pixelId}`, data);
641
+ },
642
+ /**
643
+ * Delete a pixel.
644
+ */
645
+ deletePixel(pixelId) {
646
+ return client.delete(`/pixels/${pixelId}`);
647
+ }
648
+ };
649
+ }
650
+
651
+ //#endregion
652
+ //#region src/endpoints/reports.ts
653
+ function createReportsEndpoints(client) {
654
+ return {
655
+ /**
656
+ * Get all reports for a website.
657
+ */
658
+ getReports(websiteId) {
659
+ return client.get(`/websites/${websiteId}/reports`);
660
+ },
661
+ /**
662
+ * Create a new report.
663
+ */
664
+ createReport(data) {
665
+ return client.post("/reports", data);
666
+ },
667
+ /**
668
+ * Get a report by ID.
669
+ */
670
+ getReport(reportId) {
671
+ return client.get(`/reports/${reportId}`);
672
+ },
673
+ /**
674
+ * Update a report.
675
+ */
676
+ updateReport(reportId, data) {
677
+ return client.post(`/reports/${reportId}`, data);
678
+ },
679
+ /**
680
+ * Delete a report.
681
+ */
682
+ deleteReport(reportId) {
683
+ return client.delete(`/reports/${reportId}`);
684
+ },
685
+ /**
686
+ * Run a funnel report.
687
+ */
688
+ runFunnelReport(params) {
689
+ const { websiteId, steps, window = 30, startAt, endAt, ...rest } = params;
690
+ return client.post("/reports/funnel", {
691
+ websiteId,
692
+ parameters: {
693
+ startDate: startAt,
694
+ endDate: endAt,
695
+ window,
696
+ steps
697
+ },
698
+ filters: rest
699
+ });
700
+ },
701
+ /**
702
+ * Run a retention report.
703
+ */
704
+ runRetentionReport(params) {
705
+ const { websiteId, startAt, endAt, timezone, ...rest } = params;
706
+ return client.post("/reports/retention", {
707
+ websiteId,
708
+ parameters: {
709
+ startDate: startAt,
710
+ endDate: endAt,
711
+ timezone
712
+ },
713
+ filters: rest
714
+ });
715
+ },
716
+ /**
717
+ * Run a journey/flow report.
718
+ */
719
+ runJourneyReport(params) {
720
+ const { websiteId, startAt, endAt, steps = 5, startStep, endStep, ...rest } = params;
721
+ return client.post("/reports/journey", {
722
+ websiteId,
723
+ parameters: {
724
+ startDate: startAt,
725
+ endDate: endAt,
726
+ steps,
727
+ startStep,
728
+ endStep
729
+ },
730
+ filters: rest
731
+ });
732
+ },
733
+ /**
734
+ * Run a goals report.
735
+ */
736
+ runGoalReport(params) {
737
+ const { websiteId, startAt, endAt, type, value, ...rest } = params;
738
+ return client.post("/reports/goal", {
739
+ websiteId,
740
+ parameters: {
741
+ startDate: startAt,
742
+ endDate: endAt,
743
+ type,
744
+ value
745
+ },
746
+ filters: rest
747
+ });
748
+ },
749
+ /**
750
+ * Run an attribution report.
751
+ */
752
+ runAttributionReport(params) {
753
+ const { websiteId, startAt, endAt, model, type, step, currency, ...rest } = params;
754
+ return client.post("/reports/attribution", {
755
+ websiteId,
756
+ parameters: {
757
+ startDate: startAt,
758
+ endDate: endAt,
759
+ model,
760
+ type,
761
+ step,
762
+ currency
763
+ },
764
+ filters: rest
765
+ });
766
+ },
767
+ /**
768
+ * Run a revenue report.
769
+ */
770
+ runRevenueReport(params) {
771
+ const { websiteId, startAt, endAt, currency = "USD", ...rest } = params;
772
+ return client.post("/reports/revenue", {
773
+ websiteId,
774
+ parameters: {
775
+ startDate: startAt,
776
+ endDate: endAt,
777
+ currency
778
+ },
779
+ filters: rest
780
+ });
781
+ },
782
+ /**
783
+ * Run a UTM report.
784
+ */
785
+ runUTMReport(params) {
786
+ const { websiteId, startAt, endAt, ...rest } = params;
787
+ return client.post("/reports/utm", {
788
+ websiteId,
789
+ parameters: {
790
+ startDate: startAt,
791
+ endDate: endAt
792
+ },
793
+ filters: rest
794
+ });
795
+ },
796
+ /**
797
+ * Run a breakdown report.
798
+ * @param property - Field to break down by (path, referrer, browser, device, os, country, etc.)
799
+ */
800
+ runBreakdownReport(params) {
801
+ const { websiteId, startAt, endAt, property, ...rest } = params;
802
+ return client.post("/reports/breakdown", {
803
+ websiteId,
804
+ parameters: {
805
+ startDate: startAt,
806
+ endDate: endAt,
807
+ property
808
+ },
809
+ filters: rest
810
+ });
811
+ }
812
+ };
813
+ }
814
+
815
+ //#endregion
816
+ //#region src/endpoints/segments.ts
817
+ function createSegmentsEndpoints(client) {
818
+ return {
819
+ /**
820
+ * Get all segments for a website.
821
+ */
822
+ getSegments(websiteId) {
823
+ return client.get(`/websites/${websiteId}/segments`);
824
+ },
825
+ /**
826
+ * Create a new segment.
827
+ */
828
+ createSegment(websiteId, data) {
829
+ return client.post(`/websites/${websiteId}/segments`, data);
830
+ },
831
+ /**
832
+ * Get a segment by ID.
833
+ */
834
+ getSegment(websiteId, segmentId) {
835
+ return client.get(`/websites/${websiteId}/segments/${segmentId}`);
836
+ },
837
+ /**
838
+ * Update a segment.
839
+ */
840
+ updateSegment(websiteId, segmentId, data) {
841
+ return client.post(`/websites/${websiteId}/segments/${segmentId}`, data);
842
+ },
843
+ /**
844
+ * Delete a segment.
845
+ */
846
+ deleteSegment(websiteId, segmentId) {
847
+ return client.delete(`/websites/${websiteId}/segments/${segmentId}`);
848
+ }
849
+ };
850
+ }
851
+
852
+ //#endregion
853
+ //#region src/endpoints/sessions.ts
854
+ function createSessionsEndpoints(client) {
855
+ return {
856
+ /**
857
+ * Get website sessions.
858
+ */
859
+ getWebsiteSessions(websiteId, params) {
860
+ return client.get(`/websites/${websiteId}/sessions`, params);
861
+ },
862
+ /**
863
+ * Get session statistics.
864
+ */
865
+ getWebsiteSessionStats(websiteId, params) {
866
+ return client.get(`/websites/${websiteId}/sessions/stats`, params);
867
+ },
868
+ /**
869
+ * Get weekly session traffic.
870
+ */
871
+ getWeeklyTraffic(websiteId, params) {
872
+ return client.get(`/websites/${websiteId}/sessions/weekly`, params);
873
+ },
874
+ /**
875
+ * Get a specific session.
876
+ */
877
+ getSession(websiteId, sessionId) {
878
+ return client.get(`/websites/${websiteId}/sessions/${sessionId}`);
879
+ },
880
+ /**
881
+ * Get session activity (pageviews and events).
882
+ */
883
+ getSessionActivity(websiteId, sessionId, params) {
884
+ return client.get(`/websites/${websiteId}/sessions/${sessionId}/activity`, params);
885
+ },
886
+ /**
887
+ * Get session properties (custom data).
888
+ */
889
+ getSessionProperties(websiteId, sessionId) {
890
+ return client.get(`/websites/${websiteId}/sessions/${sessionId}/properties`);
891
+ }
892
+ };
893
+ }
894
+
895
+ //#endregion
896
+ //#region src/endpoints/users.ts
897
+ function createUsersEndpoints(client) {
898
+ return {
899
+ /**
900
+ * Get all users (admin only).
901
+ */
902
+ getUsers() {
903
+ return client.get("/users");
904
+ },
905
+ /**
906
+ * Create a new user (admin only).
907
+ */
908
+ createUser(data) {
909
+ return client.post("/users", data);
910
+ },
911
+ /**
912
+ * Get a user by ID.
913
+ */
914
+ getUser(userId) {
915
+ return client.get(`/users/${userId}`);
916
+ },
917
+ /**
918
+ * Update a user.
919
+ */
920
+ updateUser(userId, data) {
921
+ return client.post(`/users/${userId}`, data);
922
+ },
923
+ /**
924
+ * Delete a user (admin only).
925
+ */
926
+ deleteUser(userId) {
927
+ return client.delete(`/users/${userId}`);
928
+ },
929
+ /**
930
+ * Get websites belonging to a user.
931
+ */
932
+ getUserWebsites(userId) {
933
+ return client.get(`/users/${userId}/websites`);
934
+ },
935
+ /**
936
+ * Get user usage statistics.
937
+ */
938
+ getUserUsage(userId, params) {
939
+ return client.get(`/users/${userId}/usage`, params);
940
+ }
941
+ };
942
+ }
943
+
944
+ //#endregion
945
+ //#region src/endpoints/webhooks.ts
946
+ function createWebhooksEndpoints(client) {
947
+ return {
948
+ /**
949
+ * Handle Clerk webhook
950
+ */
951
+ clerk: (params) => client.post("/webhooks/clerk", params.data) };
952
+ }
953
+
954
+ //#endregion
955
+ //#region src/endpoints/websites.ts
956
+ function createWebsitesEndpoints(client) {
957
+ const toDateRangeQuery = (params) => ({
958
+ startDate: new Date(params.startAt).toISOString(),
959
+ endDate: new Date(params.endAt).toISOString()
960
+ });
961
+ const toDeploymentDays = (params) => {
962
+ const diffMs = Math.max(params.endAt - params.startAt, 0);
963
+ const days = Math.ceil(diffMs / 864e5);
964
+ return Math.min(Math.max(days, 1), 365);
965
+ };
966
+ const toSuccessResponse = (response) => ({
967
+ ...response,
968
+ data: response.data ? {
969
+ success: Boolean(response.data.accepted),
970
+ ...typeof response.data.count === "number" ? { count: response.data.count } : {}
971
+ } : void 0
972
+ });
973
+ return {
974
+ /**
975
+ * Get all websites.
976
+ */
977
+ getWebsites() {
978
+ return client.get("/websites");
979
+ },
980
+ /**
981
+ * Create a new website.
982
+ */
983
+ createWebsite(data) {
984
+ return client.post("/websites", data);
985
+ },
986
+ /**
987
+ * Get a website by ID.
988
+ */
989
+ getWebsite(websiteId) {
990
+ return client.get(`/websites/${websiteId}`);
991
+ },
992
+ /**
993
+ * Update a website.
994
+ */
995
+ updateWebsite(websiteId, data) {
996
+ return client.patch(`/websites/${websiteId}`, data);
997
+ },
998
+ /**
999
+ * Delete a website.
1000
+ */
1001
+ deleteWebsite(websiteId) {
1002
+ return client.delete(`/websites/${websiteId}`);
1003
+ },
1004
+ /**
1005
+ * Reset a website's data.
1006
+ */
1007
+ resetWebsite(websiteId) {
1008
+ return client.post(`/websites/${websiteId}/reset`);
1009
+ },
1010
+ /**
1011
+ * Transfer website ownership.
1012
+ */
1013
+ transferWebsite(websiteId, data) {
1014
+ return client.post(`/websites/${websiteId}/transfer`, data);
1015
+ },
1016
+ /**
1017
+ * Get website statistics.
1018
+ */
1019
+ getWebsiteStats(websiteId, params) {
1020
+ return client.get(`/websites/${websiteId}/stats`, toDateRangeQuery(params));
1021
+ },
1022
+ /**
1023
+ * Get website pageviews data.
1024
+ */
1025
+ getWebsitePageviews(websiteId, params) {
1026
+ return client.get(`/websites/${websiteId}/pageviews`, params);
1027
+ },
1028
+ /**
1029
+ * Get website metrics (URLs, referrers, browsers, etc.).
1030
+ */
1031
+ getWebsiteMetrics(websiteId, params) {
1032
+ return client.get(`/websites/${websiteId}/metrics`, params);
1033
+ },
1034
+ /**
1035
+ * Get expanded metrics (with additional details).
1036
+ */
1037
+ getWebsiteExpandedMetrics(websiteId, params) {
1038
+ return client.get(`/websites/${websiteId}/metrics/expanded`, params);
1039
+ },
1040
+ /**
1041
+ * Get website events.
1042
+ */
1043
+ getWebsiteEvents(websiteId, params) {
1044
+ return client.get(`/websites/${websiteId}/events`, params);
1045
+ },
1046
+ /**
1047
+ * Get events time series.
1048
+ */
1049
+ getWebsiteEventsSeries(websiteId, params) {
1050
+ return client.get(`/websites/${websiteId}/events/series`, params);
1051
+ },
1052
+ /**
1053
+ * Get active visitors count.
1054
+ */
1055
+ getWebsiteActive(websiteId) {
1056
+ return client.get(`/websites/${websiteId}/active`);
1057
+ },
1058
+ /**
1059
+ * Get website date range (first and last event dates).
1060
+ */
1061
+ getWebsiteDateRange(websiteId) {
1062
+ return client.get(`/websites/${websiteId}/daterange`);
1063
+ },
1064
+ /**
1065
+ * Get website values for a specific field.
1066
+ */
1067
+ getWebsiteValues(websiteId, params) {
1068
+ return client.get(`/websites/${websiteId}/values`, params);
1069
+ },
1070
+ /**
1071
+ * Get realtime data.
1072
+ */
1073
+ getRealtimeData(websiteId) {
1074
+ return client.get(`/realtime/${websiteId}`);
1075
+ },
1076
+ /**
1077
+ * Export website data.
1078
+ */
1079
+ exportWebsiteData(websiteId, params) {
1080
+ return client.get(`/websites/${websiteId}/export`, params);
1081
+ },
1082
+ /**
1083
+ * Get website ingest mode configuration.
1084
+ */
1085
+ getWebsiteMode(websiteId) {
1086
+ return client.get(`/websites/${websiteId}/mode`);
1087
+ },
1088
+ /**
1089
+ * Set website ingest mode (auto, node, or edge).
1090
+ */
1091
+ setWebsiteMode(websiteId, mode) {
1092
+ return client.post(`/websites/${websiteId}/mode`, { ingestMode: mode });
1093
+ },
1094
+ /**
1095
+ * Get routing health status.
1096
+ */
1097
+ getRoutingHealth() {
1098
+ return client.get("/health/routing");
1099
+ },
1100
+ /**
1101
+ * Get routing statistics.
1102
+ */
1103
+ getRoutingStats(params) {
1104
+ return client.get("/routing/stats", params);
1105
+ },
1106
+ /**
1107
+ * Get Web Vitals statistics for a website.
1108
+ * Note: Only available in entrolytics.
1109
+ */
1110
+ getWebsiteVitals(websiteId, params) {
1111
+ return client.get(API_ROUTES$1.vitalsOverview, {
1112
+ websiteId,
1113
+ ...toDateRangeQuery(params)
1114
+ });
1115
+ },
1116
+ /**
1117
+ * Get individual Web Vital events.
1118
+ * Note: Only available in entrolytics.
1119
+ */
1120
+ getWebsiteVitalEvents(websiteId, params) {
1121
+ return client.get(API_ROUTES$1.vitalsRecent, {
1122
+ websiteId,
1123
+ ...params.limit ? { limit: params.limit } : {}
1124
+ });
1125
+ },
1126
+ /**
1127
+ * Track a Web Vital metric (send to collection endpoint).
1128
+ * Note: Only available in entrolytics.
1129
+ */
1130
+ trackVital(websiteId, data) {
1131
+ return client.post(API_ROUTES$1.collectVitals, {
1132
+ websiteId,
1133
+ visitorId: data.visitorId,
1134
+ sessionId: data.sessionId,
1135
+ url: data.url,
1136
+ path: data.path,
1137
+ metricName: data.metric,
1138
+ metricValue: data.value,
1139
+ deviceType: data.deviceType,
1140
+ browser: data.browser
1141
+ }).then((response) => toSuccessResponse(response));
1142
+ },
1143
+ /**
1144
+ * Track multiple Web Vitals metrics in batch.
1145
+ * Note: Only available in entrolytics.
1146
+ */
1147
+ trackVitalsBatch(websiteId, vitals) {
1148
+ if (vitals.length === 0) return Promise.resolve({
1149
+ ok: false,
1150
+ status: 400,
1151
+ error: "At least one vital is required"
1152
+ });
1153
+ const [firstVital] = vitals;
1154
+ if (vitals.some((vital) => vital.visitorId !== firstVital?.visitorId || vital.sessionId !== firstVital?.sessionId)) return Promise.resolve({
1155
+ ok: false,
1156
+ status: 400,
1157
+ error: "All batched vitals must share the same visitorId and sessionId"
1158
+ });
1159
+ return client.post(API_ROUTES$1.collectVitalsBatch, {
1160
+ websiteId,
1161
+ visitorId: firstVital?.visitorId,
1162
+ sessionId: firstVital?.sessionId,
1163
+ vitals: vitals.map((vital) => ({
1164
+ url: vital.url,
1165
+ path: vital.path,
1166
+ metricName: vital.metric,
1167
+ metricValue: vital.value,
1168
+ deviceType: vital.deviceType,
1169
+ browser: vital.browser
1170
+ }))
1171
+ }).then((response) => toSuccessResponse(response));
1172
+ },
1173
+ /**
1174
+ * Get form analytics for a website.
1175
+ * Note: Only available in entrolytics.
1176
+ */
1177
+ getWebsiteForms(websiteId, params) {
1178
+ return client.get(API_ROUTES$1.formsConversions, {
1179
+ websiteId,
1180
+ ...toDateRangeQuery(params)
1181
+ });
1182
+ },
1183
+ /**
1184
+ * Get field-level analytics for a specific form.
1185
+ * Note: Only available in entrolytics.
1186
+ */
1187
+ getFormFields(websiteId, formId, params) {
1188
+ return client.get(API_ROUTES$1.formsFieldMetrics, {
1189
+ websiteId,
1190
+ formId,
1191
+ ...toDateRangeQuery(params)
1192
+ });
1193
+ },
1194
+ /**
1195
+ * Get individual form events.
1196
+ * Note: Only available in entrolytics.
1197
+ */
1198
+ getFormEvents(websiteId, params) {
1199
+ return client.get(API_ROUTES$1.formsRecent, {
1200
+ websiteId,
1201
+ ...params.limit ? { limit: params.limit } : {}
1202
+ });
1203
+ },
1204
+ /**
1205
+ * Track a form event (send to collection endpoint).
1206
+ * Note: Only available in entrolytics.
1207
+ */
1208
+ trackFormEvent(websiteId, data) {
1209
+ return client.post(API_ROUTES$1.collectForms, {
1210
+ websiteId,
1211
+ visitorId: data.visitorId,
1212
+ sessionId: data.sessionId,
1213
+ formId: data.formId,
1214
+ formName: data.formName,
1215
+ urlPath: data.urlPath,
1216
+ eventType: data.eventType,
1217
+ fieldName: data.fieldName,
1218
+ fieldType: data.fieldType,
1219
+ fieldIndex: data.fieldIndex,
1220
+ timeOnField: data.timeOnField,
1221
+ timeSinceStart: data.timeSinceStart,
1222
+ errorMessage: data.errorMessage,
1223
+ success: data.success
1224
+ }).then((response) => toSuccessResponse(response));
1225
+ },
1226
+ /**
1227
+ * Track multiple form events in batch.
1228
+ * Note: Only available in entrolytics.
1229
+ */
1230
+ trackFormEventsBatch(websiteId, events) {
1231
+ if (events.length === 0) return Promise.resolve({
1232
+ ok: false,
1233
+ status: 400,
1234
+ error: "At least one event is required"
1235
+ });
1236
+ const [firstEvent] = events;
1237
+ if (events.some((event) => event.visitorId !== firstEvent?.visitorId || event.sessionId !== firstEvent?.sessionId)) return Promise.resolve({
1238
+ ok: false,
1239
+ status: 400,
1240
+ error: "All batched form events must share the same visitorId and sessionId"
1241
+ });
1242
+ return client.post(API_ROUTES$1.collectFormsBatch, {
1243
+ websiteId,
1244
+ visitorId: firstEvent?.visitorId,
1245
+ sessionId: firstEvent?.sessionId,
1246
+ events: events.map((event) => ({
1247
+ formId: event.formId,
1248
+ formName: event.formName,
1249
+ urlPath: event.urlPath,
1250
+ eventType: event.eventType,
1251
+ fieldName: event.fieldName,
1252
+ fieldType: event.fieldType,
1253
+ fieldIndex: event.fieldIndex,
1254
+ timeOnField: event.timeOnField,
1255
+ timeSinceStart: event.timeSinceStart,
1256
+ errorMessage: event.errorMessage,
1257
+ success: event.success
1258
+ }))
1259
+ }).then((response) => toSuccessResponse(response));
1260
+ },
1261
+ /**
1262
+ * Get deployments for a website.
1263
+ * Note: Only available in entrolytics.
1264
+ */
1265
+ getWebsiteDeployments(websiteId, params) {
1266
+ return client.get(API_ROUTES$1.deploymentByWebsite(websiteId), {
1267
+ limit: params.limit,
1268
+ days: toDeploymentDays(params)
1269
+ });
1270
+ },
1271
+ /**
1272
+ * Get a specific deployment.
1273
+ * Note: Only available in entrolytics.
1274
+ */
1275
+ getDeployment(websiteId, deployId) {
1276
+ return client.get(API_ROUTES$1.deploymentByWebsite(websiteId), { limit: 100 }).then((response) => {
1277
+ if (!response.data) return {
1278
+ ...response,
1279
+ data: void 0
1280
+ };
1281
+ const deployment = response.data.find((item) => item.deployId === deployId);
1282
+ if (!deployment) return {
1283
+ ok: false,
1284
+ status: 404,
1285
+ error: `Deployment not found: ${deployId}`
1286
+ };
1287
+ return {
1288
+ ok: response.ok,
1289
+ status: response.status,
1290
+ data: deployment
1291
+ };
1292
+ });
1293
+ },
1294
+ /**
1295
+ * Compare two deployments.
1296
+ * Note: Only available in entrolytics.
1297
+ */
1298
+ compareDeployments(websiteId, limit = 10) {
1299
+ return client.get(API_ROUTES$1.deploymentCompare(websiteId), { limit });
1300
+ },
1301
+ /**
1302
+ * Set/register a deployment context.
1303
+ * Note: Only available in entrolytics.
1304
+ */
1305
+ setDeployment(websiteId, data) {
1306
+ return client.post(API_ROUTES$1.deployments, {
1307
+ websiteId,
1308
+ ...data,
1309
+ source: data.source ?? "custom"
1310
+ });
1311
+ }
1312
+ };
1313
+ }
1314
+
1315
+ //#endregion
1316
+ //#region src/runtime.ts
1317
+ /**
1318
+ * Detect the current JavaScript runtime environment
1319
+ *
1320
+ * @returns {Runtime} The detected runtime ('node', 'edge', or 'unknown')
1321
+ *
1322
+ * @example
1323
+ * ```ts
1324
+ * const runtime = detectRuntime();
1325
+ *
1326
+ * switch (runtime) {
1327
+ * case 'node':
1328
+ * console.log('Running in Node.js');
1329
+ * break;
1330
+ * case 'edge':
1331
+ * console.log('Running in Edge Runtime');
1332
+ * break;
1333
+ * default:
1334
+ * console.log('Unknown runtime');
1335
+ * }
1336
+ * ```
1337
+ */
1338
+ function detectRuntime() {
1339
+ const globalRef = globalThis;
1340
+ const isNode = typeof globalRef.process?.versions?.node === "string";
1341
+ const hasEdgeRuntime = typeof globalRef.EdgeRuntime !== "undefined";
1342
+ const hasDeno = typeof globalRef.Deno !== "undefined";
1343
+ if (hasEdgeRuntime || hasDeno || typeof WebAssembly !== "undefined" && typeof Response !== "undefined" && !isNode) return "edge";
1344
+ if (typeof process !== "undefined" && process.versions != null && process.versions.node != null) return "node";
1345
+ return "unknown";
1346
+ }
1347
+ /**
1348
+ * Check if code is running in Node.js runtime
1349
+ *
1350
+ * @returns {boolean} True if running in Node.js
1351
+ *
1352
+ * @example
1353
+ * ```ts
1354
+ * if (isNodeRuntime()) {
1355
+ * // Safe to use Node.js-only features
1356
+ * const fs = require('fs');
1357
+ * const data = fs.readFileSync('file.txt');
1358
+ * }
1359
+ * ```
1360
+ */
1361
+ function isNodeRuntime() {
1362
+ return detectRuntime() === "node";
1363
+ }
1364
+ /**
1365
+ * Check if code is running in Edge runtime
1366
+ *
1367
+ * @returns {boolean} True if running in Edge runtime (Vercel, Netlify, Cloudflare)
1368
+ *
1369
+ * @example
1370
+ * ```ts
1371
+ * if (isEdgeRuntime()) {
1372
+ * // Use only edge-compatible features
1373
+ * const response = await fetch('https://api.example.com');
1374
+ * }
1375
+ * ```
1376
+ */
1377
+ function isEdgeRuntime() {
1378
+ return detectRuntime() === "edge";
1379
+ }
1380
+ /**
1381
+ * Get runtime capabilities
1382
+ *
1383
+ * @returns Runtime capabilities object
1384
+ *
1385
+ * @example
1386
+ * ```ts
1387
+ * const capabilities = getRuntimeCapabilities();
1388
+ *
1389
+ * if (capabilities.supportsFileSystem) {
1390
+ * // Can use fs module
1391
+ * }
1392
+ *
1393
+ * if (capabilities.supportsWebCrypto) {
1394
+ * // Can use Web Crypto API
1395
+ * }
1396
+ * ```
1397
+ */
1398
+ function getRuntimeCapabilities() {
1399
+ const runtime = detectRuntime();
1400
+ return {
1401
+ runtime,
1402
+ isNode: runtime === "node",
1403
+ isEdge: runtime === "edge",
1404
+ supportsFileSystem: runtime === "node",
1405
+ supportsWebCrypto: typeof crypto !== "undefined" && typeof crypto.subtle !== "undefined",
1406
+ supportsFetch: typeof fetch !== "undefined",
1407
+ supportsStreams: typeof ReadableStream !== "undefined"
1408
+ };
1409
+ }
1410
+ /**
1411
+ * Assert that code is running in a specific runtime
1412
+ *
1413
+ * @param {Runtime} expected - The expected runtime
1414
+ * @throws {Error} If not running in the expected runtime
1415
+ *
1416
+ * @example
1417
+ * ```ts
1418
+ * // Ensure we're in edge runtime
1419
+ * assertRuntime('edge');
1420
+ *
1421
+ * // Now safe to use edge-only features
1422
+ * export const runtime = 'edge';
1423
+ * ```
1424
+ */
1425
+ function assertRuntime(expected) {
1426
+ const actual = detectRuntime();
1427
+ if (actual !== expected) throw new Error(`Expected ${expected} runtime, but detected ${actual}. This code requires ${expected} runtime to function correctly.`);
1428
+ }
1429
+
1430
+ //#endregion
1431
+ //#region src/edge-helpers.ts
1432
+ /**
1433
+ * Edge runtime helper utilities
1434
+ *
1435
+ * Provides edge-compatible environment variable access, fetch utilities,
1436
+ * and common patterns for edge deployments (Vercel, Netlify, Cloudflare).
1437
+ *
1438
+ * @module edge-helpers
1439
+ * @example
1440
+ * ```ts
1441
+ * import { getEdgeEnv, createEdgeFetch, getRegionInfo } from 'entro-api/edge-helpers';
1442
+ *
1443
+ * // Access environment variables safely
1444
+ * const apiKey = getEdgeEnv('API_KEY', 'default-key');
1445
+ *
1446
+ * // Create a fetch wrapper with retries
1447
+ * const edgeFetch = createEdgeFetch({ retries: 3 });
1448
+ * const response = await edgeFetch('https://api.example.com');
1449
+ *
1450
+ * // Get deployment region information
1451
+ * const region = getRegionInfo();
1452
+ * console.log(`Running in ${region.provider} region ${region.region}`);
1453
+ * ```
1454
+ */
1455
+ /**
1456
+ * Safely access environment variables in edge runtime
1457
+ *
1458
+ * @param {string} key - Environment variable name
1459
+ * @param {string} [defaultValue] - Optional default value if variable not found
1460
+ * @returns {string | undefined} The environment variable value or default
1461
+ *
1462
+ * @example
1463
+ * ```ts
1464
+ * // With default value
1465
+ * const apiKey = getEdgeEnv('API_KEY', 'fallback-key');
1466
+ *
1467
+ * // Without default (returns undefined if not found)
1468
+ * const optionalVar = getEdgeEnv('OPTIONAL_VAR');
1469
+ * ```
1470
+ */
1471
+ function getEdgeEnv(key, defaultValue) {
1472
+ const globals = globalThis;
1473
+ if (typeof process !== "undefined" && process.env) {
1474
+ const value = process.env[key];
1475
+ if (value !== void 0) return value;
1476
+ }
1477
+ if (globals.Deno?.env && typeof globals.Deno.env.get === "function") try {
1478
+ return globals.Deno.env.get(key) || defaultValue;
1479
+ } catch {}
1480
+ return defaultValue;
1481
+ }
1482
+ /**
1483
+ * Check if a required environment variable is set
1484
+ *
1485
+ * @param {string} key - Environment variable name
1486
+ * @throws {Error} If the required variable is not set
1487
+ *
1488
+ * @example
1489
+ * ```ts
1490
+ * // Throws if DATABASE_URL is not set
1491
+ * requireEdgeEnv('DATABASE_URL');
1492
+ * ```
1493
+ */
1494
+ function requireEdgeEnv(key) {
1495
+ const value = getEdgeEnv(key);
1496
+ if (!value) throw new Error(`Required environment variable ${key} is not set`);
1497
+ return value;
1498
+ }
1499
+ /**
1500
+ * Create an edge-compatible fetch wrapper with retries and timeout
1501
+ *
1502
+ * @param {EdgeFetchOptions} [defaultOptions] - Default options for all requests
1503
+ * @returns {Function} Enhanced fetch function
1504
+ *
1505
+ * @example
1506
+ * ```ts
1507
+ * const edgeFetch = createEdgeFetch({
1508
+ * retries: 3,
1509
+ * retryDelay: 1000,
1510
+ * timeout: 10000,
1511
+ * });
1512
+ *
1513
+ * // Fetch with automatic retries
1514
+ * const response = await edgeFetch('https://api.example.com/data');
1515
+ * ```
1516
+ */
1517
+ function createEdgeFetch(defaultOptions = {}) {
1518
+ const { retries = 3, retryDelay = 1e3, timeout = 3e4, ...fetchDefaults } = defaultOptions;
1519
+ return async function edgeFetch(input, options) {
1520
+ const finalRetries = options?.retries ?? retries;
1521
+ const finalDelay = options?.retryDelay ?? retryDelay;
1522
+ const finalTimeout = options?.timeout ?? timeout;
1523
+ const finalOptions = {
1524
+ ...fetchDefaults,
1525
+ ...options
1526
+ };
1527
+ let lastError;
1528
+ for (let attempt = 0; attempt <= finalRetries; attempt++) {
1529
+ try {
1530
+ const controller = new AbortController();
1531
+ const timeoutId = setTimeout(() => controller.abort(), finalTimeout);
1532
+ const response = await fetch(input, {
1533
+ ...finalOptions,
1534
+ signal: controller.signal
1535
+ });
1536
+ clearTimeout(timeoutId);
1537
+ if (response.ok || response.status >= 400 && response.status < 500) return response;
1538
+ lastError = /* @__PURE__ */ new Error(`HTTP ${response.status}: ${response.statusText}`);
1539
+ } catch (error) {
1540
+ lastError = error instanceof Error ? error : new Error(String(error));
1541
+ if (lastError.name === "AbortError") throw new Error(`Request timeout after ${finalTimeout}ms`);
1542
+ }
1543
+ if (attempt < finalRetries) {
1544
+ const delay = finalDelay * Math.pow(2, attempt);
1545
+ await new Promise((resolve) => setTimeout(resolve, delay));
1546
+ }
1547
+ }
1548
+ throw lastError || /* @__PURE__ */ new Error("Request failed");
1549
+ };
1550
+ }
1551
+ /**
1552
+ * Get information about the current edge deployment region
1553
+ *
1554
+ * @returns {RegionInfo} Information about the deployment region
1555
+ *
1556
+ * @example
1557
+ * ```ts
1558
+ * const region = getRegionInfo();
1559
+ *
1560
+ * if (region.provider === 'vercel') {
1561
+ * console.log(`Running in Vercel region: ${region.region}`);
1562
+ * }
1563
+ * ```
1564
+ */
1565
+ function getRegionInfo() {
1566
+ const globals = globalThis;
1567
+ if (getEdgeEnv("VERCEL")) return {
1568
+ provider: "vercel",
1569
+ region: getEdgeEnv("VERCEL_REGION"),
1570
+ isEdge: getEdgeEnv("VERCEL_EDGE_RUNTIME") === "1"
1571
+ };
1572
+ if (typeof globals.Deno !== "undefined" && getEdgeEnv("NETLIFY")) return {
1573
+ provider: "netlify",
1574
+ region: getEdgeEnv("NETLIFY_REGION"),
1575
+ isEdge: true
1576
+ };
1577
+ if (typeof globals.caches !== "undefined" && typeof WebAssembly !== "undefined") return {
1578
+ provider: "cloudflare",
1579
+ region: void 0,
1580
+ isEdge: true
1581
+ };
1582
+ return {
1583
+ provider: "unknown",
1584
+ isEdge: false
1585
+ };
1586
+ }
1587
+ /**
1588
+ * Extract geo information from edge request
1589
+ *
1590
+ * @param {Request} request - The incoming Request object
1591
+ * @returns {Object} Geo information extracted from headers
1592
+ *
1593
+ * @example
1594
+ * ```ts
1595
+ * export async function POST(request: Request) {
1596
+ * const geo = getGeoFromRequest(request);
1597
+ * console.log(`Request from: ${geo.country}, ${geo.city}`);
1598
+ * }
1599
+ * ```
1600
+ */
1601
+ function getGeoFromRequest(request) {
1602
+ const headers = request.headers;
1603
+ const vercelCountry = headers.get("x-vercel-ip-country");
1604
+ if (vercelCountry) return {
1605
+ country: vercelCountry,
1606
+ region: headers.get("x-vercel-ip-country-region"),
1607
+ city: headers.get("x-vercel-ip-city"),
1608
+ latitude: headers.get("x-vercel-ip-latitude"),
1609
+ longitude: headers.get("x-vercel-ip-longitude")
1610
+ };
1611
+ const cfCountry = headers.get("cf-ipcountry");
1612
+ if (cfCountry) return {
1613
+ country: cfCountry,
1614
+ region: headers.get("cf-region"),
1615
+ city: headers.get("cf-city"),
1616
+ latitude: headers.get("cf-latitude"),
1617
+ longitude: headers.get("cf-longitude")
1618
+ };
1619
+ return {
1620
+ country: void 0,
1621
+ region: void 0,
1622
+ city: void 0,
1623
+ latitude: void 0,
1624
+ longitude: void 0
1625
+ };
1626
+ }
1627
+ /**
1628
+ * Get client IP address from edge request
1629
+ *
1630
+ * @param {Request} request - The incoming Request object
1631
+ * @returns {string | undefined} The client IP address
1632
+ *
1633
+ * @example
1634
+ * ```ts
1635
+ * export async function POST(request: Request) {
1636
+ * const clientIp = getClientIp(request);
1637
+ * console.log(`Request from IP: ${clientIp}`);
1638
+ * }
1639
+ * ```
1640
+ */
1641
+ function getClientIp(request) {
1642
+ const headers = request.headers;
1643
+ return headers.get("x-forwarded-for")?.split(",")[0]?.trim() || headers.get("x-real-ip") || headers.get("cf-connecting-ip") || headers.get("x-vercel-forwarded-for") || void 0;
1644
+ }
1645
+
1646
+ //#endregion
1647
+ //#region src/index.ts
1648
+ /**
1649
+ * Create an Entrolytics API client.
1650
+ *
1651
+ * @example
1652
+ * ```ts
1653
+ * // Using environment variables
1654
+ * const client = getClient();
1655
+ *
1656
+ * // With explicit configuration
1657
+ * const client = getClient({
1658
+ * endpoint: 'https://analytics.example.com/api',
1659
+ * apiKey: 'your-api-key',
1660
+ * });
1661
+ *
1662
+ * // Make API calls
1663
+ * const { ok, data, error } = await client.getWebsites();
1664
+ * ```
1665
+ */
1666
+ function getClient(config) {
1667
+ const apiClient = new ApiClient(config);
1668
+ const admin = createAdminEndpoints(apiClient);
1669
+ const auth = createAuthEndpoints(apiClient);
1670
+ const billing = createBillingEndpoints(apiClient);
1671
+ const config_endpoints = createConfigEndpoints(apiClient);
1672
+ const me = createMeEndpoints(apiClient);
1673
+ const users = createUsersEndpoints(apiClient);
1674
+ const orgs = createOrgsEndpoints(apiClient);
1675
+ const websites = createWebsitesEndpoints(apiClient);
1676
+ const sessions = createSessionsEndpoints(apiClient);
1677
+ const events = createEventsEndpoints(apiClient);
1678
+ const reports = createReportsEndpoints(apiClient);
1679
+ const segments = createSegmentsEndpoints(apiClient);
1680
+ const links = createLinksEndpoints(apiClient);
1681
+ const pixels = createPixelsEndpoints(apiClient);
1682
+ const boards = createBoardsEndpoints(apiClient);
1683
+ const webhooks = createWebhooksEndpoints(apiClient);
1684
+ const integrations = createIntegrationsEndpoints(apiClient);
1685
+ return {
1686
+ auth,
1687
+ ...me,
1688
+ ...users,
1689
+ ...orgs,
1690
+ ...websites,
1691
+ ...sessions,
1692
+ ...events,
1693
+ ...reports,
1694
+ ...segments,
1695
+ ...links,
1696
+ ...pixels,
1697
+ ...boards,
1698
+ getConfig: config_endpoints.get,
1699
+ admin,
1700
+ webhooks,
1701
+ integrations,
1702
+ billing
1703
+ };
1704
+ }
1705
+
1706
+ //#endregion
1707
+ export { API_ENDPOINTS, API_ROUTES, ApiClient, BILLING_ERRORS, CLI_CONFIG, CLI_TOKEN_STATUS, DEFAULT_API_HOST, DEPLOYMENT_ENV_VARS, DEPLOYMENT_SOURCES, ENV_VAR_NAMES, ERROR_MESSAGES, EVENT_TYPES, FORM_EVENT_TYPES, FORM_FIELD_TYPES, FRAMEWORK_PACKAGES, FRAMEWORK_PATTERNS, HTTP_STATUS, NAVIGATION_TYPES, ONBOARDING_STEPS, PLANS, PLAN_FEATURES, RATE_LIMITS, SDK_EVENT_TYPES, SUCCESS_MESSAGES, USAGE_THRESHOLDS, USER_ROLES, VITAL_RATINGS, VITAL_THRESHOLDS, VITAL_TYPES, assertRuntime, createAdminEndpoints, createAuthEndpoints, createBillingEndpoints, createBoardsEndpoints, createConfigEndpoints, createEdgeFetch, createEventsEndpoints, createIntegrationsEndpoints, createLinksEndpoints, createMeEndpoints, createOrgsEndpoints, createPixelsEndpoints, createReportsEndpoints, createSegmentsEndpoints, createSessionsEndpoints, createUsersEndpoints, createWebhooksEndpoints, createWebsitesEndpoints, getClient as default, getClient, detectDeploymentContext, detectRuntime, getApiRoute, getClientIp, getEdgeEnv, getEnvVarNames, getFrameworkPackage, getGeoFromRequest, getPlan, getPlanLimit, getRegionInfo, getRuntimeCapabilities, getVitalRating, isEdgeRuntime, isNodeRuntime, isPlanFeatureEnabled, isUsageCritical, isUsageWarning, isValidFramework, requireEdgeEnv };
1708
+ //# sourceMappingURL=index.js.map