@nextlytics/core 0.1.0-canary-1

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 (93) hide show
  1. package/dist/anonymous-user.cjs +118 -0
  2. package/dist/anonymous-user.d.mts +22 -0
  3. package/dist/anonymous-user.d.ts +22 -0
  4. package/dist/anonymous-user.js +94 -0
  5. package/dist/backends/clickhouse.cjs +110 -0
  6. package/dist/backends/clickhouse.d.mts +58 -0
  7. package/dist/backends/clickhouse.d.ts +58 -0
  8. package/dist/backends/clickhouse.js +92 -0
  9. package/dist/backends/ga.cjs +207 -0
  10. package/dist/backends/ga.d.mts +21 -0
  11. package/dist/backends/ga.d.ts +21 -0
  12. package/dist/backends/ga.js +183 -0
  13. package/dist/backends/gtm.cjs +155 -0
  14. package/dist/backends/gtm.d.mts +11 -0
  15. package/dist/backends/gtm.d.ts +11 -0
  16. package/dist/backends/gtm.js +131 -0
  17. package/dist/backends/lib/db.cjs +150 -0
  18. package/dist/backends/lib/db.d.mts +121 -0
  19. package/dist/backends/lib/db.d.ts +121 -0
  20. package/dist/backends/lib/db.js +119 -0
  21. package/dist/backends/logging.cjs +45 -0
  22. package/dist/backends/logging.d.mts +7 -0
  23. package/dist/backends/logging.d.ts +7 -0
  24. package/dist/backends/logging.js +21 -0
  25. package/dist/backends/neon.cjs +84 -0
  26. package/dist/backends/neon.d.mts +11 -0
  27. package/dist/backends/neon.d.ts +11 -0
  28. package/dist/backends/neon.js +66 -0
  29. package/dist/backends/postgrest.cjs +98 -0
  30. package/dist/backends/postgrest.d.mts +46 -0
  31. package/dist/backends/postgrest.d.ts +46 -0
  32. package/dist/backends/postgrest.js +73 -0
  33. package/dist/backends/posthog.cjs +120 -0
  34. package/dist/backends/posthog.d.mts +13 -0
  35. package/dist/backends/posthog.d.ts +13 -0
  36. package/dist/backends/posthog.js +96 -0
  37. package/dist/backends/segment.cjs +112 -0
  38. package/dist/backends/segment.d.mts +43 -0
  39. package/dist/backends/segment.d.ts +43 -0
  40. package/dist/backends/segment.js +88 -0
  41. package/dist/client.cjs +171 -0
  42. package/dist/client.d.mts +29 -0
  43. package/dist/client.d.ts +29 -0
  44. package/dist/client.js +146 -0
  45. package/dist/config-helpers.cjs +71 -0
  46. package/dist/config-helpers.d.mts +16 -0
  47. package/dist/config-helpers.d.ts +16 -0
  48. package/dist/config-helpers.js +45 -0
  49. package/dist/handlers.cjs +123 -0
  50. package/dist/handlers.d.mts +9 -0
  51. package/dist/handlers.d.ts +9 -0
  52. package/dist/handlers.js +99 -0
  53. package/dist/headers.cjs +41 -0
  54. package/dist/headers.d.mts +3 -0
  55. package/dist/headers.d.ts +3 -0
  56. package/dist/headers.js +17 -0
  57. package/dist/index.cjs +41 -0
  58. package/dist/index.d.mts +9 -0
  59. package/dist/index.d.ts +9 -0
  60. package/dist/index.js +12 -0
  61. package/dist/middleware.cjs +204 -0
  62. package/dist/middleware.d.mts +10 -0
  63. package/dist/middleware.d.ts +10 -0
  64. package/dist/middleware.js +183 -0
  65. package/dist/pages-router.cjs +45 -0
  66. package/dist/pages-router.d.mts +45 -0
  67. package/dist/pages-router.d.ts +45 -0
  68. package/dist/pages-router.js +21 -0
  69. package/dist/plugins/vercel-geo.cjs +60 -0
  70. package/dist/plugins/vercel-geo.d.mts +25 -0
  71. package/dist/plugins/vercel-geo.d.ts +25 -0
  72. package/dist/plugins/vercel-geo.js +36 -0
  73. package/dist/server-component-context.cjs +95 -0
  74. package/dist/server-component-context.d.mts +30 -0
  75. package/dist/server-component-context.d.ts +30 -0
  76. package/dist/server-component-context.js +69 -0
  77. package/dist/server.cjs +236 -0
  78. package/dist/server.d.mts +13 -0
  79. package/dist/server.d.ts +13 -0
  80. package/dist/server.js +213 -0
  81. package/dist/template.cjs +108 -0
  82. package/dist/template.d.mts +27 -0
  83. package/dist/template.d.ts +27 -0
  84. package/dist/template.js +83 -0
  85. package/dist/types.cjs +16 -0
  86. package/dist/types.d.mts +216 -0
  87. package/dist/types.d.ts +216 -0
  88. package/dist/types.js +0 -0
  89. package/dist/uitils.cjs +94 -0
  90. package/dist/uitils.d.mts +22 -0
  91. package/dist/uitils.d.ts +22 -0
  92. package/dist/uitils.js +68 -0
  93. package/package.json +162 -0
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var anonymous_user_exports = {};
20
+ __export(anonymous_user_exports, {
21
+ resolveAnonymousUser: () => resolveAnonymousUser
22
+ });
23
+ module.exports = __toCommonJS(anonymous_user_exports);
24
+ const BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
25
+ const ANON_ID_LENGTH = 10;
26
+ const DEFAULTS = {
27
+ gdprMode: true,
28
+ useCookies: false,
29
+ dailySalt: true,
30
+ cookieName: "__nextlytics_anon",
31
+ cookieMaxAge: 60 * 60 * 24 * 365 * 2
32
+ // 2 years
33
+ };
34
+ function isSecureRequest(headers) {
35
+ const proto = headers.get("x-forwarded-proto");
36
+ if (proto) return proto === "https";
37
+ return false;
38
+ }
39
+ function getDailySalt() {
40
+ const now = /* @__PURE__ */ new Date();
41
+ return `${now.getUTCFullYear()}-${now.getUTCMonth()}-${now.getUTCDate()}`;
42
+ }
43
+ function bytesToBase62(bytes, length) {
44
+ let result = "";
45
+ for (let i = 0; i < length; i++) {
46
+ const idx = (bytes[i * 2] * 256 + bytes[i * 2 + 1]) % 62;
47
+ result += BASE62_CHARS[idx];
48
+ }
49
+ return result;
50
+ }
51
+ async function hashToShortId(input) {
52
+ const encoder = new TextEncoder();
53
+ const data = encoder.encode(input);
54
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
55
+ return bytesToBase62(new Uint8Array(hashBuffer), ANON_ID_LENGTH);
56
+ }
57
+ async function generateGdprAnonId(serverContext, useDailySalt) {
58
+ const ip = serverContext.ip || "unknown";
59
+ const userAgent = serverContext.requestHeaders["user-agent"] || "unknown";
60
+ const host = serverContext.host || "unknown";
61
+ const parts = useDailySalt ? [getDailySalt(), ip, userAgent, host] : [ip, userAgent, host];
62
+ return hashToShortId(parts.join("|"));
63
+ }
64
+ function generateRandomAnonId() {
65
+ const bytes = new Uint8Array(ANON_ID_LENGTH * 2);
66
+ crypto.getRandomValues(bytes);
67
+ return bytesToBase62(bytes, ANON_ID_LENGTH);
68
+ }
69
+ async function resolveAnonymousUser(params) {
70
+ const { ctx, serverContext, config, response } = params;
71
+ const { headers, cookies } = ctx;
72
+ const gdprMode = config.anonymousUsers?.gdprMode ?? DEFAULTS.gdprMode;
73
+ const useCookies = config.anonymousUsers?.useCookies ?? DEFAULTS.useCookies;
74
+ const dailySalt = config.anonymousUsers?.dailySalt ?? DEFAULTS.dailySalt;
75
+ const cookieName = config.anonymousUsers?.cookieName ?? DEFAULTS.cookieName;
76
+ const cookieMaxAge = config.anonymousUsers?.cookieMaxAge ?? DEFAULTS.cookieMaxAge;
77
+ let anonId;
78
+ let shouldSetCookie = false;
79
+ if (useCookies) {
80
+ const existingCookie = cookies.get(cookieName);
81
+ if (existingCookie?.value) {
82
+ anonId = existingCookie.value;
83
+ } else {
84
+ anonId = gdprMode ? await generateGdprAnonId(serverContext, dailySalt) : generateRandomAnonId();
85
+ shouldSetCookie = true;
86
+ }
87
+ } else {
88
+ if (gdprMode) {
89
+ anonId = await generateGdprAnonId(serverContext, dailySalt);
90
+ } else {
91
+ anonId = generateRandomAnonId();
92
+ }
93
+ }
94
+ if (config.callbacks?.getAnonymousUserId) {
95
+ try {
96
+ const overrideResult = await config.callbacks.getAnonymousUserId({
97
+ ctx,
98
+ originalAnonymousUserId: anonId
99
+ });
100
+ anonId = overrideResult.anonId;
101
+ } catch {
102
+ }
103
+ }
104
+ if (shouldSetCookie && response) {
105
+ response.cookies.set(cookieName, anonId, {
106
+ maxAge: cookieMaxAge,
107
+ httpOnly: true,
108
+ secure: isSecureRequest(headers),
109
+ sameSite: "lax",
110
+ path: "/"
111
+ });
112
+ }
113
+ return { anonId };
114
+ }
115
+ // Annotate the CommonJS export names for ESM import in node:
116
+ 0 && (module.exports = {
117
+ resolveAnonymousUser
118
+ });
@@ -0,0 +1,22 @@
1
+ import { NextResponse } from 'next/server';
2
+ import { RequestContext, ServerEventContext, NextlyticsConfig, AnonymousUserResult } from './types.mjs';
3
+ import 'next/dist/server/web/spec-extension/cookies';
4
+
5
+ type ResolveAnonymousUserParams = {
6
+ ctx: RequestContext;
7
+ serverContext: ServerEventContext;
8
+ config: NextlyticsConfig;
9
+ /** Optional response for setting cookies. If not provided, cookies won't be set. */
10
+ response?: NextResponse | null;
11
+ };
12
+ /**
13
+ * Resolve anonymous user ID based on config.
14
+ *
15
+ * Modes:
16
+ * - gdprMode=true (default): Hash-based ID (Fathom-like)
17
+ * - gdprMode=false + useCookies=true: Persistent cookie-based ID
18
+ * - gdprMode=false + useCookies=false: Random ID per request
19
+ */
20
+ declare function resolveAnonymousUser(params: ResolveAnonymousUserParams): Promise<AnonymousUserResult>;
21
+
22
+ export { type ResolveAnonymousUserParams, resolveAnonymousUser };
@@ -0,0 +1,22 @@
1
+ import { NextResponse } from 'next/server';
2
+ import { RequestContext, ServerEventContext, NextlyticsConfig, AnonymousUserResult } from './types.js';
3
+ import 'next/dist/server/web/spec-extension/cookies';
4
+
5
+ type ResolveAnonymousUserParams = {
6
+ ctx: RequestContext;
7
+ serverContext: ServerEventContext;
8
+ config: NextlyticsConfig;
9
+ /** Optional response for setting cookies. If not provided, cookies won't be set. */
10
+ response?: NextResponse | null;
11
+ };
12
+ /**
13
+ * Resolve anonymous user ID based on config.
14
+ *
15
+ * Modes:
16
+ * - gdprMode=true (default): Hash-based ID (Fathom-like)
17
+ * - gdprMode=false + useCookies=true: Persistent cookie-based ID
18
+ * - gdprMode=false + useCookies=false: Random ID per request
19
+ */
20
+ declare function resolveAnonymousUser(params: ResolveAnonymousUserParams): Promise<AnonymousUserResult>;
21
+
22
+ export { type ResolveAnonymousUserParams, resolveAnonymousUser };
@@ -0,0 +1,94 @@
1
+ const BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2
+ const ANON_ID_LENGTH = 10;
3
+ const DEFAULTS = {
4
+ gdprMode: true,
5
+ useCookies: false,
6
+ dailySalt: true,
7
+ cookieName: "__nextlytics_anon",
8
+ cookieMaxAge: 60 * 60 * 24 * 365 * 2
9
+ // 2 years
10
+ };
11
+ function isSecureRequest(headers) {
12
+ const proto = headers.get("x-forwarded-proto");
13
+ if (proto) return proto === "https";
14
+ return false;
15
+ }
16
+ function getDailySalt() {
17
+ const now = /* @__PURE__ */ new Date();
18
+ return `${now.getUTCFullYear()}-${now.getUTCMonth()}-${now.getUTCDate()}`;
19
+ }
20
+ function bytesToBase62(bytes, length) {
21
+ let result = "";
22
+ for (let i = 0; i < length; i++) {
23
+ const idx = (bytes[i * 2] * 256 + bytes[i * 2 + 1]) % 62;
24
+ result += BASE62_CHARS[idx];
25
+ }
26
+ return result;
27
+ }
28
+ async function hashToShortId(input) {
29
+ const encoder = new TextEncoder();
30
+ const data = encoder.encode(input);
31
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
32
+ return bytesToBase62(new Uint8Array(hashBuffer), ANON_ID_LENGTH);
33
+ }
34
+ async function generateGdprAnonId(serverContext, useDailySalt) {
35
+ const ip = serverContext.ip || "unknown";
36
+ const userAgent = serverContext.requestHeaders["user-agent"] || "unknown";
37
+ const host = serverContext.host || "unknown";
38
+ const parts = useDailySalt ? [getDailySalt(), ip, userAgent, host] : [ip, userAgent, host];
39
+ return hashToShortId(parts.join("|"));
40
+ }
41
+ function generateRandomAnonId() {
42
+ const bytes = new Uint8Array(ANON_ID_LENGTH * 2);
43
+ crypto.getRandomValues(bytes);
44
+ return bytesToBase62(bytes, ANON_ID_LENGTH);
45
+ }
46
+ async function resolveAnonymousUser(params) {
47
+ const { ctx, serverContext, config, response } = params;
48
+ const { headers, cookies } = ctx;
49
+ const gdprMode = config.anonymousUsers?.gdprMode ?? DEFAULTS.gdprMode;
50
+ const useCookies = config.anonymousUsers?.useCookies ?? DEFAULTS.useCookies;
51
+ const dailySalt = config.anonymousUsers?.dailySalt ?? DEFAULTS.dailySalt;
52
+ const cookieName = config.anonymousUsers?.cookieName ?? DEFAULTS.cookieName;
53
+ const cookieMaxAge = config.anonymousUsers?.cookieMaxAge ?? DEFAULTS.cookieMaxAge;
54
+ let anonId;
55
+ let shouldSetCookie = false;
56
+ if (useCookies) {
57
+ const existingCookie = cookies.get(cookieName);
58
+ if (existingCookie?.value) {
59
+ anonId = existingCookie.value;
60
+ } else {
61
+ anonId = gdprMode ? await generateGdprAnonId(serverContext, dailySalt) : generateRandomAnonId();
62
+ shouldSetCookie = true;
63
+ }
64
+ } else {
65
+ if (gdprMode) {
66
+ anonId = await generateGdprAnonId(serverContext, dailySalt);
67
+ } else {
68
+ anonId = generateRandomAnonId();
69
+ }
70
+ }
71
+ if (config.callbacks?.getAnonymousUserId) {
72
+ try {
73
+ const overrideResult = await config.callbacks.getAnonymousUserId({
74
+ ctx,
75
+ originalAnonymousUserId: anonId
76
+ });
77
+ anonId = overrideResult.anonId;
78
+ } catch {
79
+ }
80
+ }
81
+ if (shouldSetCookie && response) {
82
+ response.cookies.set(cookieName, anonId, {
83
+ maxAge: cookieMaxAge,
84
+ httpOnly: true,
85
+ secure: isSecureRequest(headers),
86
+ sameSite: "lax",
87
+ path: "/"
88
+ });
89
+ }
90
+ return { anonId };
91
+ }
92
+ export {
93
+ resolveAnonymousUser
94
+ };
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var clickhouse_exports = {};
20
+ __export(clickhouse_exports, {
21
+ clickhouseBackend: () => clickhouseBackend
22
+ });
23
+ module.exports = __toCommonJS(clickhouse_exports);
24
+ var import_db = require("./lib/db");
25
+ function clickhouseBackend(config) {
26
+ const baseUrl = config.url.replace(/\/$/, "");
27
+ const database = config.database ?? "default";
28
+ const table = config.tableName ?? "analytics";
29
+ const asyncInsert = config.asyncInsert ?? true;
30
+ const acceptUpdates = config.acceptUpdates ?? false;
31
+ const updateLookbackMinutes = config.updateLookbackMinutes ?? 60;
32
+ const authHeader = "Basic " + btoa((config.username ?? "default") + ":" + (config.password ?? ""));
33
+ function printCreateTableStatement() {
34
+ console.error(`[Nextlytics ClickHouse] Table "${database}.${table}" does not exist. Run:
35
+ `);
36
+ console.error((0, import_db.generateChCreateTableSQL)(database, table));
37
+ }
38
+ async function query(sql) {
39
+ const params = new URLSearchParams({
40
+ database,
41
+ query: sql
42
+ });
43
+ const res = await fetch(`${baseUrl}/?${params}`, {
44
+ method: "GET",
45
+ headers: { Authorization: authHeader }
46
+ });
47
+ if (!res.ok) {
48
+ throw new Error(`ClickHouse query error ${res.status}: ${await res.text()}`);
49
+ }
50
+ const text = await res.text();
51
+ if (!text.trim()) return [];
52
+ return text.trim().split("\n").map((line) => JSON.parse(line));
53
+ }
54
+ async function insert(row) {
55
+ const params = new URLSearchParams({
56
+ database,
57
+ query: `INSERT INTO ${table} FORMAT JSONEachRow`,
58
+ date_time_input_format: "best_effort"
59
+ });
60
+ if (asyncInsert) {
61
+ params.set("async_insert", "1");
62
+ params.set("wait_for_async_insert", "0");
63
+ }
64
+ const res = await fetch(`${baseUrl}/?${params}`, {
65
+ method: "POST",
66
+ headers: {
67
+ "Content-Type": "application/json",
68
+ Authorization: authHeader
69
+ },
70
+ body: JSON.stringify(row)
71
+ });
72
+ if (!res.ok) {
73
+ const text = await res.text();
74
+ if ((0, import_db.isChTableNotFoundError)(text)) {
75
+ printCreateTableStatement();
76
+ }
77
+ throw new Error(`ClickHouse error ${res.status}: ${text}`);
78
+ }
79
+ }
80
+ return {
81
+ name: "clickhouse",
82
+ supportsUpdates: acceptUpdates,
83
+ async onEvent(event) {
84
+ const row = (0, import_db.eventToJsonRow)(event);
85
+ await insert(row);
86
+ },
87
+ async updateEvent(eventId, patch) {
88
+ if (!acceptUpdates || !patch.clientContext) return;
89
+ const cols = import_db.tableColumns.map((c) => c.name).join(", ");
90
+ const rows = await query(
91
+ `SELECT ${cols} FROM ${table} WHERE event_id = '${eventId}' AND timestamp > now() - INTERVAL ${updateLookbackMinutes} MINUTE FORMAT JSONEachRow`
92
+ );
93
+ if (rows.length === 0) return;
94
+ const existing = rows[0];
95
+ const clientCtx = (0, import_db.extractClientContext)(patch.clientContext);
96
+ const updated = {
97
+ ...existing,
98
+ referer: clientCtx.referer ?? existing.referer,
99
+ user_agent: clientCtx.user_agent ?? existing.user_agent,
100
+ locale: clientCtx.locale ?? existing.locale,
101
+ client_context: clientCtx.rest ?? existing.client_context
102
+ };
103
+ await insert(updated);
104
+ }
105
+ };
106
+ }
107
+ // Annotate the CommonJS export names for ESM import in node:
108
+ 0 && (module.exports = {
109
+ clickhouseBackend
110
+ });
@@ -0,0 +1,58 @@
1
+ import { NextlyticsBackend } from '../types.mjs';
2
+ import 'next/dist/server/web/spec-extension/cookies';
3
+ import 'next/server';
4
+
5
+ /**
6
+ * ClickHouse backend for Nextlytics
7
+ *
8
+ * Sends events to ClickHouse via HTTP API with async inserts.
9
+ *
10
+ * ## ClickHouse Cloud Usage
11
+ *
12
+ * ```typescript
13
+ * import { clickhouseBackend } from "@nextlytics/core/backends/clickhouse"
14
+ *
15
+ * const analytics = Nextlytics({
16
+ * backends: [
17
+ * clickhouseBackend({
18
+ * url: "https://xxx.clickhouse.cloud:8443",
19
+ * username: "default",
20
+ * password: process.env.CLICKHOUSE_PASSWORD!,
21
+ * })
22
+ * ]
23
+ * })
24
+ * ```
25
+ *
26
+ * ## Self-hosted ClickHouse
27
+ *
28
+ * ```typescript
29
+ * clickhouseBackend({
30
+ * url: "http://localhost:8123",
31
+ * username: "default",
32
+ * password: "",
33
+ * database: "analytics",
34
+ * })
35
+ * ```
36
+ */
37
+
38
+ type ClickHouseBackendConfig = {
39
+ /** ClickHouse HTTP API URL */
40
+ url: string;
41
+ /** Username (default: "default") */
42
+ username?: string;
43
+ /** Password */
44
+ password?: string;
45
+ /** Database name (default: "default") */
46
+ database?: string;
47
+ /** Table name (default: "analytics") */
48
+ tableName?: string;
49
+ /** Enable async inserts (default: true) */
50
+ asyncInsert?: boolean;
51
+ /** Enable updates via select+insert (uses ReplacingMergeTree deduplication) */
52
+ acceptUpdates?: boolean;
53
+ /** Lookback window in minutes for update SELECT queries (default: 60) */
54
+ updateLookbackMinutes?: number;
55
+ };
56
+ declare function clickhouseBackend(config: ClickHouseBackendConfig): NextlyticsBackend;
57
+
58
+ export { type ClickHouseBackendConfig, clickhouseBackend };
@@ -0,0 +1,58 @@
1
+ import { NextlyticsBackend } from '../types.js';
2
+ import 'next/dist/server/web/spec-extension/cookies';
3
+ import 'next/server';
4
+
5
+ /**
6
+ * ClickHouse backend for Nextlytics
7
+ *
8
+ * Sends events to ClickHouse via HTTP API with async inserts.
9
+ *
10
+ * ## ClickHouse Cloud Usage
11
+ *
12
+ * ```typescript
13
+ * import { clickhouseBackend } from "@nextlytics/core/backends/clickhouse"
14
+ *
15
+ * const analytics = Nextlytics({
16
+ * backends: [
17
+ * clickhouseBackend({
18
+ * url: "https://xxx.clickhouse.cloud:8443",
19
+ * username: "default",
20
+ * password: process.env.CLICKHOUSE_PASSWORD!,
21
+ * })
22
+ * ]
23
+ * })
24
+ * ```
25
+ *
26
+ * ## Self-hosted ClickHouse
27
+ *
28
+ * ```typescript
29
+ * clickhouseBackend({
30
+ * url: "http://localhost:8123",
31
+ * username: "default",
32
+ * password: "",
33
+ * database: "analytics",
34
+ * })
35
+ * ```
36
+ */
37
+
38
+ type ClickHouseBackendConfig = {
39
+ /** ClickHouse HTTP API URL */
40
+ url: string;
41
+ /** Username (default: "default") */
42
+ username?: string;
43
+ /** Password */
44
+ password?: string;
45
+ /** Database name (default: "default") */
46
+ database?: string;
47
+ /** Table name (default: "analytics") */
48
+ tableName?: string;
49
+ /** Enable async inserts (default: true) */
50
+ asyncInsert?: boolean;
51
+ /** Enable updates via select+insert (uses ReplacingMergeTree deduplication) */
52
+ acceptUpdates?: boolean;
53
+ /** Lookback window in minutes for update SELECT queries (default: 60) */
54
+ updateLookbackMinutes?: number;
55
+ };
56
+ declare function clickhouseBackend(config: ClickHouseBackendConfig): NextlyticsBackend;
57
+
58
+ export { type ClickHouseBackendConfig, clickhouseBackend };
@@ -0,0 +1,92 @@
1
+ import {
2
+ tableColumns,
3
+ eventToJsonRow,
4
+ generateChCreateTableSQL,
5
+ isChTableNotFoundError,
6
+ extractClientContext
7
+ } from "./lib/db";
8
+ function clickhouseBackend(config) {
9
+ const baseUrl = config.url.replace(/\/$/, "");
10
+ const database = config.database ?? "default";
11
+ const table = config.tableName ?? "analytics";
12
+ const asyncInsert = config.asyncInsert ?? true;
13
+ const acceptUpdates = config.acceptUpdates ?? false;
14
+ const updateLookbackMinutes = config.updateLookbackMinutes ?? 60;
15
+ const authHeader = "Basic " + btoa((config.username ?? "default") + ":" + (config.password ?? ""));
16
+ function printCreateTableStatement() {
17
+ console.error(`[Nextlytics ClickHouse] Table "${database}.${table}" does not exist. Run:
18
+ `);
19
+ console.error(generateChCreateTableSQL(database, table));
20
+ }
21
+ async function query(sql) {
22
+ const params = new URLSearchParams({
23
+ database,
24
+ query: sql
25
+ });
26
+ const res = await fetch(`${baseUrl}/?${params}`, {
27
+ method: "GET",
28
+ headers: { Authorization: authHeader }
29
+ });
30
+ if (!res.ok) {
31
+ throw new Error(`ClickHouse query error ${res.status}: ${await res.text()}`);
32
+ }
33
+ const text = await res.text();
34
+ if (!text.trim()) return [];
35
+ return text.trim().split("\n").map((line) => JSON.parse(line));
36
+ }
37
+ async function insert(row) {
38
+ const params = new URLSearchParams({
39
+ database,
40
+ query: `INSERT INTO ${table} FORMAT JSONEachRow`,
41
+ date_time_input_format: "best_effort"
42
+ });
43
+ if (asyncInsert) {
44
+ params.set("async_insert", "1");
45
+ params.set("wait_for_async_insert", "0");
46
+ }
47
+ const res = await fetch(`${baseUrl}/?${params}`, {
48
+ method: "POST",
49
+ headers: {
50
+ "Content-Type": "application/json",
51
+ Authorization: authHeader
52
+ },
53
+ body: JSON.stringify(row)
54
+ });
55
+ if (!res.ok) {
56
+ const text = await res.text();
57
+ if (isChTableNotFoundError(text)) {
58
+ printCreateTableStatement();
59
+ }
60
+ throw new Error(`ClickHouse error ${res.status}: ${text}`);
61
+ }
62
+ }
63
+ return {
64
+ name: "clickhouse",
65
+ supportsUpdates: acceptUpdates,
66
+ async onEvent(event) {
67
+ const row = eventToJsonRow(event);
68
+ await insert(row);
69
+ },
70
+ async updateEvent(eventId, patch) {
71
+ if (!acceptUpdates || !patch.clientContext) return;
72
+ const cols = tableColumns.map((c) => c.name).join(", ");
73
+ const rows = await query(
74
+ `SELECT ${cols} FROM ${table} WHERE event_id = '${eventId}' AND timestamp > now() - INTERVAL ${updateLookbackMinutes} MINUTE FORMAT JSONEachRow`
75
+ );
76
+ if (rows.length === 0) return;
77
+ const existing = rows[0];
78
+ const clientCtx = extractClientContext(patch.clientContext);
79
+ const updated = {
80
+ ...existing,
81
+ referer: clientCtx.referer ?? existing.referer,
82
+ user_agent: clientCtx.user_agent ?? existing.user_agent,
83
+ locale: clientCtx.locale ?? existing.locale,
84
+ client_context: clientCtx.rest ?? existing.client_context
85
+ };
86
+ await insert(updated);
87
+ }
88
+ };
89
+ }
90
+ export {
91
+ clickhouseBackend
92
+ };