lytx 0.3.0

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.
Files changed (213) hide show
  1. package/.env.example +37 -0
  2. package/README.md +486 -0
  3. package/alchemy.run.ts +155 -0
  4. package/cli/bootstrap-admin.ts +284 -0
  5. package/cli/deploy-staging.ts +692 -0
  6. package/cli/import-events.ts +628 -0
  7. package/cli/import-sites.ts +518 -0
  8. package/cli/index.ts +609 -0
  9. package/cli/init-db.ts +269 -0
  10. package/cli/migrate-to-durable-objects.ts +564 -0
  11. package/cli/migration-worker.ts +300 -0
  12. package/cli/performance-test.ts +588 -0
  13. package/cli/pg/client.ts +4 -0
  14. package/cli/pg/new-site.ts +153 -0
  15. package/cli/rollback-durable-objects.ts +622 -0
  16. package/cli/seed-data.ts +459 -0
  17. package/cli/setup.js +18 -0
  18. package/cli/setup.ts +463 -0
  19. package/cli/validate-migration.ts +200 -0
  20. package/cli/wrangler-migration.jsonc +28 -0
  21. package/db/adapter.ts +166 -0
  22. package/db/analytics_engine/client.ts +0 -0
  23. package/db/analytics_engine/sites.ts +0 -0
  24. package/db/client.ts +16 -0
  25. package/db/d1/client.ts +8 -0
  26. package/db/d1/drizzle.config.ts +35 -0
  27. package/db/d1/migrations/0000_true_maelstrom.sql +165 -0
  28. package/db/d1/migrations/0001_wonderful_bloodaxe.sql +12 -0
  29. package/db/d1/migrations/0002_late_frightful_four.sql +1 -0
  30. package/db/d1/migrations/0003_cuddly_obadiah_stane.sql +16 -0
  31. package/db/d1/migrations/0004_mute_stardust.sql +1 -0
  32. package/db/d1/migrations/0005_awesome_silvermane.sql +3 -0
  33. package/db/d1/migrations/0006_volatile_shriek.sql +2 -0
  34. package/db/d1/migrations/0007_superb_lila_cheney.sql +1 -0
  35. package/db/d1/migrations/0008_bitter_longshot.sql +17 -0
  36. package/db/d1/migrations/0009_wonderful_madame_masque.sql +28 -0
  37. package/db/d1/migrations/meta/0000_snapshot.json +1112 -0
  38. package/db/d1/migrations/meta/0001_snapshot.json +1187 -0
  39. package/db/d1/migrations/meta/0002_snapshot.json +1194 -0
  40. package/db/d1/migrations/meta/0003_snapshot.json +1296 -0
  41. package/db/d1/migrations/meta/0004_snapshot.json +1303 -0
  42. package/db/d1/migrations/meta/0005_snapshot.json +1325 -0
  43. package/db/d1/migrations/meta/0006_snapshot.json +1339 -0
  44. package/db/d1/migrations/meta/0007_snapshot.json +1347 -0
  45. package/db/d1/migrations/meta/0008_snapshot.json +1464 -0
  46. package/db/d1/migrations/meta/0009_snapshot.json +1648 -0
  47. package/db/d1/migrations/meta/_journal.json +76 -0
  48. package/db/d1/schema.ts +407 -0
  49. package/db/d1/sites.ts +374 -0
  50. package/db/d1/teamAiUsage.ts +101 -0
  51. package/db/d1/teams.ts +127 -0
  52. package/db/durable/drizzle.config.ts +8 -0
  53. package/db/durable/durableObjectClient.ts +480 -0
  54. package/db/durable/events.ts +100 -0
  55. package/db/durable/migrations/0000_fair_bucky.sql +38 -0
  56. package/db/durable/migrations/meta/0000_snapshot.json +278 -0
  57. package/db/durable/migrations/meta/_journal.json +13 -0
  58. package/db/durable/migrations/migrations.js +10 -0
  59. package/db/durable/schema.ts +5 -0
  60. package/db/durable/siteDurableObject.ts +1352 -0
  61. package/db/durable/types.ts +53 -0
  62. package/db/postgres/client.ts +13 -0
  63. package/db/postgres/drizzle.config.ts +12 -0
  64. package/db/postgres/migrations/0000_brainy_sprite.sql +116 -0
  65. package/db/postgres/migrations/meta/0000_snapshot.json +681 -0
  66. package/db/postgres/migrations/meta/_journal.json +13 -0
  67. package/db/postgres/schema.ts +145 -0
  68. package/db/postgres/sites.ts +118 -0
  69. package/db/tranformReports.ts +595 -0
  70. package/db/types.ts +55 -0
  71. package/endpoints/api_worker.tsx +1854 -0
  72. package/endpoints/site_do_worker.ts +11 -0
  73. package/index.d.ts +63 -0
  74. package/index.ts +83 -0
  75. package/lib/auth.ts +279 -0
  76. package/lib/geojson/world_countries.json +45307 -0
  77. package/lib/random_name.ts +41 -0
  78. package/lib/sendMail.ts +252 -0
  79. package/package.json +142 -0
  80. package/public/favicon.ico +0 -0
  81. package/public/images/android-chrome-192x192.png +0 -0
  82. package/public/images/android-chrome-512x512.png +0 -0
  83. package/public/images/apple-touch-icon.png +0 -0
  84. package/public/images/favicon-16x16.png +0 -0
  85. package/public/images/favicon-32x32.png +0 -0
  86. package/public/images/lytx_dark_dashboard.png +0 -0
  87. package/public/images/lytx_light_dashboard.png +0 -0
  88. package/public/images/safari-pinned-tab.svg +4 -0
  89. package/public/logo.png +0 -0
  90. package/public/site.webmanifest +26 -0
  91. package/public/sw.js +107 -0
  92. package/src/Document.tsx +86 -0
  93. package/src/api/ai_api.ts +1156 -0
  94. package/src/api/authMiddleware.ts +45 -0
  95. package/src/api/auth_api.ts +465 -0
  96. package/src/api/event_labels_api.ts +193 -0
  97. package/src/api/events_api.ts +210 -0
  98. package/src/api/queueWorker.ts +303 -0
  99. package/src/api/reports_api.ts +278 -0
  100. package/src/api/seed_api.ts +288 -0
  101. package/src/api/sites_api.ts +904 -0
  102. package/src/api/tag_api.ts +458 -0
  103. package/src/api/tag_api_v2.ts +289 -0
  104. package/src/api/team_api.ts +456 -0
  105. package/src/app/Dashboard.tsx +1339 -0
  106. package/src/app/Events.tsx +974 -0
  107. package/src/app/Explore.tsx +312 -0
  108. package/src/app/Layout.tsx +58 -0
  109. package/src/app/Settings.tsx +1302 -0
  110. package/src/app/components/DashboardCard.tsx +118 -0
  111. package/src/app/components/EditableCell.tsx +123 -0
  112. package/src/app/components/EventForm.tsx +93 -0
  113. package/src/app/components/MarketingFooter.tsx +49 -0
  114. package/src/app/components/MarketingNav.tsx +150 -0
  115. package/src/app/components/Nav.tsx +755 -0
  116. package/src/app/components/NewSiteSetup.tsx +298 -0
  117. package/src/app/components/SQLEditor.tsx +740 -0
  118. package/src/app/components/SiteSelector.tsx +126 -0
  119. package/src/app/components/SiteTag.tsx +42 -0
  120. package/src/app/components/SiteTagInstallCard.tsx +241 -0
  121. package/src/app/components/WorldMapCard.tsx +337 -0
  122. package/src/app/components/charts/ChartComponents.tsx +1481 -0
  123. package/src/app/components/charts/EventFunnel.tsx +45 -0
  124. package/src/app/components/charts/EventSummary.tsx +194 -0
  125. package/src/app/components/charts/SankeyFlows.tsx +72 -0
  126. package/src/app/components/marketing/CheckIcon.tsx +16 -0
  127. package/src/app/components/marketing/MarketingLayout.tsx +23 -0
  128. package/src/app/components/marketing/SectionHeading.tsx +35 -0
  129. package/src/app/components/reports/AskAiWorkspace.tsx +371 -0
  130. package/src/app/components/reports/CreateReportStarter.tsx +74 -0
  131. package/src/app/components/reports/DashboardRouteFiltersContext.tsx +14 -0
  132. package/src/app/components/reports/DashboardToolbar.tsx +154 -0
  133. package/src/app/components/reports/DashboardWorkspaceLayout.tsx +63 -0
  134. package/src/app/components/reports/DashboardWorkspaceShell.tsx +118 -0
  135. package/src/app/components/reports/ReportBuilderWorkspace.tsx +76 -0
  136. package/src/app/components/reports/custom/CustomReportBuilderPage.tsx +1667 -0
  137. package/src/app/components/reports/custom/ReportWidgetChart.tsx +297 -0
  138. package/src/app/components/reports/custom/buildWidgetSql.ts +151 -0
  139. package/src/app/components/reports/custom/chartPalettes.ts +18 -0
  140. package/src/app/components/reports/custom/types.ts +50 -0
  141. package/src/app/components/reports/reportBuilderMenuItems.ts +17 -0
  142. package/src/app/components/reports/useDashboardToolbarControls.tsx +235 -0
  143. package/src/app/components/ui/AlertBanner.tsx +101 -0
  144. package/src/app/components/ui/Button.tsx +55 -0
  145. package/src/app/components/ui/Card.tsx +80 -0
  146. package/src/app/components/ui/Input.tsx +72 -0
  147. package/src/app/components/ui/Link.tsx +23 -0
  148. package/src/app/components/ui/ReportBuilderMenu.tsx +246 -0
  149. package/src/app/components/ui/ThemeToggle.tsx +54 -0
  150. package/src/app/constants.ts +6 -0
  151. package/src/app/headers.ts +33 -0
  152. package/src/app/providers/AuthProvider.tsx +189 -0
  153. package/src/app/providers/ClientProviders.tsx +18 -0
  154. package/src/app/providers/QueryProvider.tsx +23 -0
  155. package/src/app/providers/ThemeProvider.tsx +88 -0
  156. package/src/app/utils/chartThemes.ts +146 -0
  157. package/src/app/utils/keybinds.ts +96 -0
  158. package/src/app/utils/media.tsx +24 -0
  159. package/src/client.tsx +114 -0
  160. package/src/config/createLytxAppConfig.ts +252 -0
  161. package/src/config/resourceNames.ts +88 -0
  162. package/src/db/index.ts +67 -0
  163. package/src/index.css +285 -0
  164. package/src/lib/featureFlags.ts +69 -0
  165. package/src/pages/GetStarted.tsx +290 -0
  166. package/src/pages/Home.tsx +268 -0
  167. package/src/pages/Login.tsx +283 -0
  168. package/src/pages/PrivacyPolicy.tsx +120 -0
  169. package/src/pages/Signup.tsx +267 -0
  170. package/src/pages/TermsOfService.tsx +126 -0
  171. package/src/pages/VerifyEmail.tsx +56 -0
  172. package/src/session/durableObject.ts +7 -0
  173. package/src/session/siteSchema.ts +86 -0
  174. package/src/session/types.ts +36 -0
  175. package/src/templates/README.md +80 -0
  176. package/src/templates/cleanFunctions.js +44 -0
  177. package/src/templates/embedFunctions.js +52 -0
  178. package/src/templates/lytx-shared.ts +662 -0
  179. package/src/templates/lytxpixel-core.ts +144 -0
  180. package/src/templates/lytxpixel.ts +267 -0
  181. package/src/templates/lytxpixelBrowser.js +634 -0
  182. package/src/templates/lytxpixelBrowser.mjs +634 -0
  183. package/src/templates/parseData.js +12 -0
  184. package/src/templates/script.ts +31 -0
  185. package/src/templates/template.tsx +50 -0
  186. package/src/templates/test.js +3 -0
  187. package/src/templates/trackWebEvents.ts +177 -0
  188. package/src/templates/vendors/clickcease.ts +8 -0
  189. package/src/templates/vendors/google.ts +174 -0
  190. package/src/templates/vendors/linkedin.ts +23 -0
  191. package/src/templates/vendors/meta.ts +56 -0
  192. package/src/templates/vendors/quantcast.ts +22 -0
  193. package/src/templates/vendors/simplfi.ts +7 -0
  194. package/src/types/app-context.ts +16 -0
  195. package/src/utilities/dashboardParams.ts +188 -0
  196. package/src/utilities/dashboardQueries.ts +537 -0
  197. package/src/utilities/dashboardTransforms.ts +167 -0
  198. package/src/utilities/dataValidation.ts +414 -0
  199. package/src/utilities/detector.ts +73 -0
  200. package/src/utilities/encrypt.ts +103 -0
  201. package/src/utilities/index.ts +13 -0
  202. package/src/utilities/parser.ts +117 -0
  203. package/src/utilities/performanceMonitoring.ts +570 -0
  204. package/src/utilities/route_interuptors.ts +24 -0
  205. package/src/worker.tsx +675 -0
  206. package/tsconfig.json +78 -0
  207. package/types/env.d.ts +16 -0
  208. package/types/rw.d.ts +7 -0
  209. package/types/shims.d.ts +53 -0
  210. package/types/vite.d.ts +19 -0
  211. package/vite/vite-plugin-pixel-bundle.ts +126 -0
  212. package/vite.config.ts +53 -0
  213. package/worker-configuration.d.ts +8401 -0
@@ -0,0 +1,11 @@
1
+ import { SiteDurableObject as SiteDurableObjectImpl } from "../db/durable/siteDurableObject";
2
+
3
+ // Re-declare the class in this module so workerd/miniflare can resolve it
4
+ // as a concrete durable object export on this worker script.
5
+ export class SiteDurableObject extends SiteDurableObjectImpl {}
6
+
7
+ export default {
8
+ async fetch(): Promise<Response> {
9
+ return new Response("site durable object host");
10
+ },
11
+ } satisfies ExportedHandler;
package/index.d.ts ADDED
@@ -0,0 +1,63 @@
1
+ import type { CreateLytxAppConfig } from "./src/config/createLytxAppConfig";
2
+
3
+ export { Signup } from "./src/pages/Signup";
4
+ export { Login } from "./src/pages/Login";
5
+ export { VerifyEmail } from "./src/pages/VerifyEmail";
6
+
7
+ export { DashboardPage } from "./src/app/Dashboard";
8
+ export type { DashboardPageProps } from "./src/app/Dashboard";
9
+ export { EventsPage } from "./src/app/Events";
10
+ export { ExplorePage } from "./src/app/Explore";
11
+ export { SettingsPage } from "./src/app/Settings";
12
+ export { AppLayout } from "./src/app/Layout";
13
+
14
+ export { NewSiteSetup } from "./src/app/components/NewSiteSetup";
15
+ export { DashboardWorkspaceLayout } from "./src/app/components/reports/DashboardWorkspaceLayout";
16
+ export { ReportBuilderWorkspace } from "./src/app/components/reports/ReportBuilderWorkspace";
17
+ export { CustomReportBuilderPage } from "./src/app/components/reports/custom/CustomReportBuilderPage";
18
+
19
+ export { Document } from "./src/Document";
20
+
21
+ export { eventsApi } from "./src/api/events_api";
22
+ export { seedApi } from "./src/api/seed_api";
23
+ export { team_dashboard_endpoints } from "./src/api/team_api";
24
+ export {
25
+ world_countries,
26
+ getCurrentVisitorsRoute,
27
+ getDashboardDataRoute,
28
+ siteEventsSqlRoute,
29
+ siteEventsSchemaRoute,
30
+ } from "./src/api/sites_api";
31
+ export { aiChatRoute, aiConfigRoute, aiTagSuggestRoute } from "./src/api/ai_api";
32
+ export { resendVerificationEmailRoute, userApiRoutes } from "./src/api/auth_api";
33
+ export { eventLabelsApi } from "./src/api/event_labels_api";
34
+ export { reportsApi } from "./src/api/reports_api";
35
+ export { legacyContainerRoute, newSiteSetup } from "./src/api/tag_api";
36
+ export { lytxTag, trackWebEvent } from "./src/api/tag_api_v2";
37
+ export { handleQueueMessage } from "./src/api/queueWorker";
38
+
39
+ export { authMiddleware, sessionMiddleware } from "./src/api/authMiddleware";
40
+
41
+ export { auth } from "./lib/auth";
42
+ export type { AuthUserSession } from "./lib/auth";
43
+
44
+ export { checkIfTeamSetupSites, onlyAllowGetPost } from "./src/utilities/route_interuptors";
45
+
46
+ export { SyncDurableObject } from "./src/session/durableObject";
47
+ export { SiteDurableObject } from "./db/durable/siteDurableObject";
48
+
49
+ export type {
50
+ CreateLytxAppConfig,
51
+ LytxDbAdapter,
52
+ LytxEventStore,
53
+ LytxDbConfig,
54
+ } from "./src/config/createLytxAppConfig";
55
+ export function createLytxApp(
56
+ config?: CreateLytxAppConfig,
57
+ ): ReturnType<typeof import("./src/worker").createLytxApp>;
58
+ export { DEFAULT_LYTX_RESOURCE_NAMES, resolveLytxResourceNames } from "./src/config/resourceNames";
59
+ export type { LytxResourceNames, LytxResourceNamingOptions, LytxResourceStagePosition } from "./src/config/resourceNames";
60
+
61
+ export type { AppContext } from "./src/worker";
62
+ export type { DBAdapter, UserRole } from "./db/types";
63
+ export type { SitesContext, TeamContext } from "./db/d1/sites";
package/index.ts ADDED
@@ -0,0 +1,83 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Lytx Kit – Core Library
3
+ // ---------------------------------------------------------------------------
4
+ // Re-exports every building block from the analytics platform so consumers
5
+ // can import only what they need and compose their own worker / app.
6
+ //
7
+ // import { DashboardPage, eventsApi, authMiddleware } from "lytx";
8
+ //
9
+ // The package does not export one static fetch/queue handler singleton.
10
+ // Consumers can either call `createLytxApp(...)` or wire up their own
11
+ // `defineApp` using whichever routes, pages, and middleware they choose.
12
+ // ---------------------------------------------------------------------------
13
+
14
+ // ── Pages (public / unauthenticated) ────────────────────────────────────────
15
+ export { Signup } from "./src/pages/Signup";
16
+ export { Login } from "./src/pages/Login";
17
+ export { VerifyEmail } from "./src/pages/VerifyEmail";
18
+
19
+ // ── App pages (authenticated) ───────────────────────────────────────────────
20
+ export { DashboardPage } from "./src/app/Dashboard";
21
+ export type { DashboardPageProps } from "./src/app/Dashboard";
22
+ export { EventsPage } from "./src/app/Events";
23
+ export { ExplorePage } from "./src/app/Explore";
24
+ export { SettingsPage } from "./src/app/Settings";
25
+ export { AppLayout } from "./src/app/Layout";
26
+
27
+ // ── App components ──────────────────────────────────────────────────────────
28
+ export { NewSiteSetup } from "./src/app/components/NewSiteSetup";
29
+ export { DashboardWorkspaceLayout } from "./src/app/components/reports/DashboardWorkspaceLayout";
30
+ export { ReportBuilderWorkspace } from "./src/app/components/reports/ReportBuilderWorkspace";
31
+ export { CustomReportBuilderPage } from "./src/app/components/reports/custom/CustomReportBuilderPage";
32
+
33
+ // ── Document / shell ────────────────────────────────────────────────────────
34
+ export { Document } from "./src/Document";
35
+
36
+ // ── API route groups ────────────────────────────────────────────────────────
37
+ export { eventsApi } from "./src/api/events_api";
38
+ export { seedApi } from "./src/api/seed_api";
39
+ export { team_dashboard_endpoints } from "./src/api/team_api";
40
+ export {
41
+ world_countries,
42
+ getCurrentVisitorsRoute,
43
+ getDashboardDataRoute,
44
+ siteEventsSqlRoute,
45
+ siteEventsSchemaRoute,
46
+ } from "./src/api/sites_api";
47
+ export { aiChatRoute, aiConfigRoute, aiTagSuggestRoute } from "./src/api/ai_api";
48
+ export { resendVerificationEmailRoute, userApiRoutes } from "./src/api/auth_api";
49
+ export { eventLabelsApi } from "./src/api/event_labels_api";
50
+ export { reportsApi } from "./src/api/reports_api";
51
+ export { legacyContainerRoute, newSiteSetup } from "./src/api/tag_api";
52
+ export { lytxTag, trackWebEvent } from "./src/api/tag_api_v2";
53
+ export { handleQueueMessage } from "./src/api/queueWorker";
54
+
55
+ // ── Middleware ───────────────────────────────────────────────────────────────
56
+ export { authMiddleware, sessionMiddleware } from "./src/api/authMiddleware";
57
+
58
+ // ── Auth ────────────────────────────────────────────────────────────────────
59
+ export { auth } from "./lib/auth";
60
+ export type { AuthUserSession } from "./lib/auth";
61
+
62
+ // ── Route utilities ─────────────────────────────────────────────────────────
63
+ export { checkIfTeamSetupSites, onlyAllowGetPost } from "./src/utilities/route_interuptors";
64
+
65
+ // ── Durable Objects ─────────────────────────────────────────────────────────
66
+ export { SyncDurableObject } from "./src/session/durableObject";
67
+ export { SiteDurableObject } from "./db/durable/siteDurableObject";
68
+
69
+ // ── App factory ─────────────────────────────────────────────────────────────
70
+ export { createLytxApp } from "./src/worker";
71
+ export type {
72
+ CreateLytxAppConfig,
73
+ LytxDbAdapter,
74
+ LytxEventStore,
75
+ LytxDbConfig,
76
+ } from "./src/config/createLytxAppConfig";
77
+ export { DEFAULT_LYTX_RESOURCE_NAMES, resolveLytxResourceNames } from "./src/config/resourceNames";
78
+ export type { LytxResourceNames, LytxResourceNamingOptions, LytxResourceStagePosition } from "./src/config/resourceNames";
79
+
80
+ // ── Types ───────────────────────────────────────────────────────────────────
81
+ export type { AppContext } from "./src/worker";
82
+ export type { DBAdapter, UserRole } from "./db/types";
83
+ export type { SitesContext, TeamContext } from "./db/d1/sites";
package/lib/auth.ts ADDED
@@ -0,0 +1,279 @@
1
+ import { betterAuth } from "better-auth";
2
+ import { drizzleAdapter } from "better-auth/adapters/drizzle";
3
+ import { customSession } from "better-auth/plugins";
4
+ import { env } from "cloudflare:workers";
5
+ import { IS_DEV } from "rwsdk/constants";
6
+
7
+ import { d1_client } from "@db/d1/client";
8
+ import type { DBAdapter } from "@db/d1/schema";
9
+ import * as schema from "@db/d1/schema";
10
+ import { createNewAccount, getSitesForUser } from "@db/d1/sites";
11
+ import type { SitesContext } from "@db/d1/sites";
12
+ import { sendVerificationEmail } from "@lib/sendMail";
13
+
14
+ type SocialProviderToggles = {
15
+ google?: boolean;
16
+ github?: boolean;
17
+ };
18
+
19
+ export type AuthRuntimeConfig = {
20
+ emailPasswordEnabled?: boolean;
21
+ requireEmailVerification?: boolean;
22
+ socialProviders?: SocialProviderToggles;
23
+ };
24
+
25
+ type TeamSummary = {
26
+ id: number;
27
+ name: string;
28
+ external_id: number;
29
+ };
30
+
31
+ type CoreSession = {
32
+ session: {
33
+ id: string;
34
+ createdAt: Date;
35
+ updatedAt: Date;
36
+ userId: string;
37
+ expiresAt: Date;
38
+ token: string;
39
+ ipAddress?: string | null;
40
+ userAgent?: string | null;
41
+ };
42
+ user: {
43
+ id: string;
44
+ name: string;
45
+ email: string;
46
+ emailVerified: boolean;
47
+ image?: string | null;
48
+ createdAt: Date;
49
+ updatedAt: Date;
50
+ };
51
+ };
52
+
53
+ export type AuthUserSession = CoreSession & {
54
+ initial_site_setup: boolean;
55
+ email_verified: boolean;
56
+ team: TeamSummary;
57
+ all_teams: TeamSummary[];
58
+ role: "admin" | "editor" | "viewer";
59
+ db_adapter: DBAdapter;
60
+ userSites: SitesContext | undefined;
61
+ timezone: string | null;
62
+ last_site_id: number | null;
63
+ last_team_id: number | null;
64
+ };
65
+
66
+ export type AuthProviderAvailability = {
67
+ google: boolean;
68
+ github: boolean;
69
+ };
70
+
71
+ let auth_runtime_config: AuthRuntimeConfig = {
72
+ emailPasswordEnabled: true,
73
+ requireEmailVerification: true,
74
+ socialProviders: {},
75
+ };
76
+
77
+ let auth_instance: ReturnType<typeof betterAuth> | null = null;
78
+
79
+ const hasGoogleCredentials = () => Boolean(env.GOOGLE_CLIENT_ID?.trim() && env.GOOGLE_CLIENT_SECRET?.trim());
80
+ const hasGithubCredentials = () => Boolean(env.GITHUB_CLIENT_ID?.trim() && env.GITHUB_CLIENT_SECRET?.trim());
81
+
82
+ export function setAuthRuntimeConfig(config: AuthRuntimeConfig = {}) {
83
+ auth_runtime_config = {
84
+ ...auth_runtime_config,
85
+ ...config,
86
+ socialProviders: {
87
+ ...auth_runtime_config.socialProviders,
88
+ ...config.socialProviders,
89
+ },
90
+ };
91
+
92
+ auth_instance = null;
93
+ }
94
+
95
+ export function getAuthProviderAvailability(): AuthProviderAvailability {
96
+ const google_enabled = auth_runtime_config.socialProviders?.google ?? hasGoogleCredentials();
97
+ const github_enabled = auth_runtime_config.socialProviders?.github ?? hasGithubCredentials();
98
+
99
+ return {
100
+ google: google_enabled,
101
+ github: github_enabled,
102
+ };
103
+ }
104
+
105
+ function getTrustedOrigins() {
106
+ if (!IS_DEV) return [env.BETTER_AUTH_URL];
107
+ return [
108
+ "http://localhost:5173",
109
+ "http://127.0.0.1:5173",
110
+ "http://localhost:6124",
111
+ "http://localhost:6123",
112
+ "http://*.ts.net:*",
113
+ "https://*.ts.net:*",
114
+ env.BETTER_AUTH_URL,
115
+ ];
116
+ }
117
+
118
+ function buildSocialProviders() {
119
+ const providers: Record<string, { clientId: string; clientSecret: string }> = {};
120
+ const availability = getAuthProviderAvailability();
121
+
122
+ if (availability.google) {
123
+ const clientId = env.GOOGLE_CLIENT_ID?.trim();
124
+ const clientSecret = env.GOOGLE_CLIENT_SECRET?.trim();
125
+ if (!clientId || !clientSecret) {
126
+ throw new Error("Google sign-in is enabled but GOOGLE_CLIENT_ID/GOOGLE_CLIENT_SECRET are missing");
127
+ }
128
+ providers.google = { clientId, clientSecret };
129
+ }
130
+
131
+ if (availability.github) {
132
+ const clientId = env.GITHUB_CLIENT_ID?.trim();
133
+ const clientSecret = env.GITHUB_CLIENT_SECRET?.trim();
134
+ if (!clientId || !clientSecret) {
135
+ throw new Error("GitHub sign-in is enabled but GITHUB_CLIENT_ID/GITHUB_CLIENT_SECRET are missing");
136
+ }
137
+ providers.github = { clientId, clientSecret };
138
+ }
139
+
140
+ return providers;
141
+ }
142
+
143
+ function createAuthInstance() {
144
+ return betterAuth({
145
+ trustedOrigins: getTrustedOrigins(),
146
+ plugins: [
147
+ customSession(async ({ user, session }) => {
148
+ const user_with_state = user as typeof user & {
149
+ last_team_id?: number | null;
150
+ timezone?: string | null;
151
+ last_site_id?: number | null;
152
+ };
153
+
154
+ let initial_site_setup = false;
155
+ const lastTeamId = user_with_state.last_team_id ?? null;
156
+ const userSites = await getSitesForUser(user.id, lastTeamId);
157
+
158
+ let currentTeamId = 0;
159
+ let currentTeamName = "";
160
+ let db_adapter: DBAdapter = "sqlite";
161
+ let teamExternalId = 0;
162
+ let userRole = "viewer";
163
+ if (userSites) {
164
+ if (userSites.teamHasSites) {
165
+ initial_site_setup = true;
166
+ }
167
+ currentTeamId = userSites.team.id;
168
+
169
+ if (userSites.team.name) currentTeamName = userSites.team.name;
170
+ if (userSites.team.db_adapter) db_adapter = userSites.team.db_adapter;
171
+ if (userSites.team.external_id) teamExternalId = userSites.team.external_id;
172
+ if (userSites.team.role) userRole = userSites.team.role;
173
+ }
174
+
175
+ const teams = [{ id: currentTeamId, name: currentTeamName, external_id: teamExternalId }];
176
+ if (userSites?.all_teams) {
177
+ const mappedTeams = userSites.all_teams.map((team) => ({
178
+ id: team.team_id,
179
+ name: team.name!,
180
+ external_id: team.external_id!,
181
+ }));
182
+ teams.push(...mappedTeams);
183
+ }
184
+
185
+ return {
186
+ initial_site_setup,
187
+ email_verified: user.emailVerified,
188
+ team: { id: currentTeamId, name: currentTeamName, external_id: teamExternalId },
189
+ all_teams: teams,
190
+ role: userRole,
191
+ db_adapter,
192
+ userSites: userSites?.sitesList,
193
+ timezone: user_with_state.timezone ?? null,
194
+ last_site_id: user_with_state.last_site_id ?? null,
195
+ last_team_id: currentTeamId || lastTeamId,
196
+ user,
197
+ session,
198
+ };
199
+ }),
200
+ ],
201
+ database: drizzleAdapter(d1_client, { provider: "sqlite", schema }),
202
+ secret: env.BETTER_AUTH_SECRET,
203
+ emailAndPassword: {
204
+ enabled: auth_runtime_config.emailPasswordEnabled ?? true,
205
+ requireEmailVerification: auth_runtime_config.requireEmailVerification ?? true,
206
+ },
207
+ rateLimit: {
208
+ storage: "secondary-storage",
209
+ },
210
+ secondaryStorage: {
211
+ get: async (key) => {
212
+ const value = await env.lytx_sessions.get(key);
213
+ return value ? value : null;
214
+ },
215
+ set: async (key, value, ttl) => {
216
+ if (ttl) await env.lytx_sessions.put(key, value, { expirationTtl: ttl });
217
+ else await env.lytx_sessions.put(key, value);
218
+ },
219
+ delete: async (key) => {
220
+ await env.lytx_sessions.delete(key);
221
+ },
222
+ },
223
+ onAPIError: {
224
+ onError(error) {
225
+ if (error instanceof Error) {
226
+ console.error("Better Auth API error:", {
227
+ name: error.name,
228
+ message: error.message,
229
+ stack: IS_DEV ? error.stack : undefined,
230
+ });
231
+ return;
232
+ }
233
+
234
+ console.error("Better Auth API error:", error);
235
+ },
236
+ },
237
+ user: {},
238
+ emailVerification: {
239
+ sendOnSignUp: true,
240
+ sendVerificationEmail: async ({ user, url }, _request) => {
241
+ if (IS_DEV) console.log("🔥🔥🔥 sendVerificationEmail", user, url);
242
+ await sendVerificationEmail(user.email, url);
243
+ },
244
+ },
245
+ databaseHooks: {
246
+ user: {
247
+ create: {
248
+ after: async (user) => {
249
+ await createNewAccount(user);
250
+ },
251
+ },
252
+ },
253
+ },
254
+ socialProviders: buildSocialProviders(),
255
+ });
256
+ }
257
+
258
+ export function getAuth() {
259
+ if (!auth_instance) {
260
+ auth_instance = createAuthInstance();
261
+ }
262
+ return auth_instance;
263
+ }
264
+
265
+ export type AuthInstance = ReturnType<typeof getAuth>;
266
+
267
+ export const auth: AuthInstance = new Proxy({} as AuthInstance, {
268
+ get(_target, property, receiver) {
269
+ return Reflect.get(getAuth(), property, receiver);
270
+ },
271
+ });
272
+
273
+ export function asAuthUserSession(value: unknown): AuthUserSession | null {
274
+ if (!value || typeof value !== "object") return null;
275
+ const candidate = value as Partial<AuthUserSession>;
276
+ if (!candidate.user || !candidate.session) return null;
277
+ if (!candidate.team || !candidate.role || !candidate.db_adapter) return null;
278
+ return candidate as AuthUserSession;
279
+ }