@nextlytics/core 0.2.0 → 0.2.1-canary.55

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 (70) hide show
  1. package/dist/anonymous-user.js +26 -2
  2. package/dist/backends/clickhouse.js +32 -14
  3. package/dist/backends/ga.js +26 -2
  4. package/dist/backends/gtm.js +26 -2
  5. package/dist/backends/lib/db.js +33 -2
  6. package/dist/backends/logging.js +26 -2
  7. package/dist/backends/neon.js +41 -20
  8. package/dist/backends/postgrest.js +33 -8
  9. package/dist/backends/posthog.js +26 -2
  10. package/dist/backends/segment.js +26 -2
  11. package/dist/client.js +41 -16
  12. package/dist/config-helpers.js +28 -2
  13. package/dist/handlers.js +35 -11
  14. package/dist/headers.js +26 -2
  15. package/dist/index.js +35 -6
  16. package/dist/middleware.js +47 -26
  17. package/dist/pages-router.js +28 -4
  18. package/dist/plugins/vercel-geo.js +26 -2
  19. package/dist/server-component-context.js +29 -3
  20. package/dist/server.js +60 -35
  21. package/dist/template.js +27 -2
  22. package/dist/types.js +16 -0
  23. package/dist/uitils.js +30 -4
  24. package/package.json +28 -101
  25. package/dist/anonymous-user.cjs +0 -118
  26. package/dist/anonymous-user.d.mts +0 -22
  27. package/dist/backends/clickhouse.cjs +0 -110
  28. package/dist/backends/clickhouse.d.mts +0 -58
  29. package/dist/backends/ga.cjs +0 -207
  30. package/dist/backends/ga.d.mts +0 -21
  31. package/dist/backends/gtm.cjs +0 -155
  32. package/dist/backends/gtm.d.mts +0 -11
  33. package/dist/backends/lib/db.cjs +0 -150
  34. package/dist/backends/lib/db.d.mts +0 -121
  35. package/dist/backends/logging.cjs +0 -45
  36. package/dist/backends/logging.d.mts +0 -7
  37. package/dist/backends/neon.cjs +0 -84
  38. package/dist/backends/neon.d.mts +0 -11
  39. package/dist/backends/postgrest.cjs +0 -98
  40. package/dist/backends/postgrest.d.mts +0 -46
  41. package/dist/backends/posthog.cjs +0 -120
  42. package/dist/backends/posthog.d.mts +0 -13
  43. package/dist/backends/segment.cjs +0 -112
  44. package/dist/backends/segment.d.mts +0 -43
  45. package/dist/client.cjs +0 -171
  46. package/dist/client.d.mts +0 -29
  47. package/dist/config-helpers.cjs +0 -71
  48. package/dist/config-helpers.d.mts +0 -16
  49. package/dist/handlers.cjs +0 -123
  50. package/dist/handlers.d.mts +0 -9
  51. package/dist/headers.cjs +0 -41
  52. package/dist/headers.d.mts +0 -3
  53. package/dist/index.cjs +0 -41
  54. package/dist/index.d.mts +0 -9
  55. package/dist/middleware.cjs +0 -204
  56. package/dist/middleware.d.mts +0 -10
  57. package/dist/pages-router.cjs +0 -45
  58. package/dist/pages-router.d.mts +0 -45
  59. package/dist/plugins/vercel-geo.cjs +0 -60
  60. package/dist/plugins/vercel-geo.d.mts +0 -25
  61. package/dist/server-component-context.cjs +0 -95
  62. package/dist/server-component-context.d.mts +0 -30
  63. package/dist/server.cjs +0 -236
  64. package/dist/server.d.mts +0 -13
  65. package/dist/template.cjs +0 -108
  66. package/dist/template.d.mts +0 -27
  67. package/dist/types.cjs +0 -16
  68. package/dist/types.d.mts +0 -216
  69. package/dist/uitils.cjs +0 -94
  70. package/dist/uitils.d.mts +0 -22
@@ -1,207 +0,0 @@
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 ga_exports = {};
20
- __export(ga_exports, {
21
- googleAnalyticsBackend: () => googleAnalyticsBackend
22
- });
23
- module.exports = __toCommonJS(ga_exports);
24
- const GA_TEMPLATE_ID = "ga-gtag";
25
- function parseGaCookie(cookieValue) {
26
- const match = cookieValue.match(/^GA\d+\.\d+\.(.+)$/);
27
- return match ? match[1] : null;
28
- }
29
- function getClientId(event, gaCookieClientId, source) {
30
- if (source === "gaCookie" && gaCookieClientId) {
31
- return gaCookieClientId;
32
- }
33
- if (!event.anonymousUserId) {
34
- throw new Error("anonymousUserId is required for GA backend (no _ga cookie available)");
35
- }
36
- return event.anonymousUserId;
37
- }
38
- function toGA4EventName(type) {
39
- if (type === "pageView") return "page_view";
40
- if (type === "apiCall") return "api_call";
41
- return type.replace(/([A-Z])/g, "_$1").toLowerCase().replace(/^_/, "");
42
- }
43
- function buildEventParams(event) {
44
- const params = {
45
- // Required for engagement metrics
46
- engagement_time_msec: 1
47
- };
48
- const { serverContext } = event;
49
- if (serverContext) {
50
- params.page_location = `https://${serverContext.host}${serverContext.path}`;
51
- }
52
- const { clientContext } = event;
53
- if (clientContext) {
54
- if (clientContext.referer) {
55
- params.page_referrer = clientContext.referer;
56
- }
57
- if (clientContext.locale) {
58
- params.language = clientContext.locale;
59
- }
60
- if (clientContext.screen?.width && clientContext.screen?.height) {
61
- params.screen_resolution = `${clientContext.screen.width}x${clientContext.screen.height}`;
62
- }
63
- }
64
- if (event.properties) {
65
- Object.assign(params, event.properties);
66
- }
67
- return params;
68
- }
69
- function getUserAgent(event) {
70
- return event.clientContext?.userAgent ?? event.serverContext?.requestHeaders?.["user-agent"];
71
- }
72
- function getClientIp(event) {
73
- return event.serverContext?.ip;
74
- }
75
- async function sendToMeasurementProtocol(opts) {
76
- const endpoint = opts.debugMode ? "https://www.google-analytics.com/debug/mp/collect" : "https://www.google-analytics.com/mp/collect";
77
- const url = `${endpoint}?measurement_id=${opts.measurementId}&api_secret=${opts.apiSecret}`;
78
- const payload = {
79
- client_id: opts.clientId,
80
- events: [
81
- {
82
- name: opts.eventName,
83
- params: opts.eventParams
84
- }
85
- ]
86
- };
87
- if (opts.userId) {
88
- payload.user_id = opts.userId;
89
- }
90
- if (opts.userProperties && Object.keys(opts.userProperties).length > 0) {
91
- payload.user_properties = Object.fromEntries(
92
- Object.entries(opts.userProperties).map(([k, v]) => [k, { value: v }])
93
- );
94
- }
95
- const headers = {};
96
- if (opts.userAgent) {
97
- headers["User-Agent"] = opts.userAgent;
98
- }
99
- if (opts.clientIp) {
100
- headers["X-Forwarded-For"] = opts.clientIp;
101
- }
102
- try {
103
- const res = await fetch(url, {
104
- method: "POST",
105
- body: JSON.stringify(payload),
106
- headers: Object.keys(headers).length > 0 ? headers : void 0
107
- });
108
- if (!res.ok) {
109
- const body = await res.text().catch(() => "");
110
- console.warn(`[GA] Measurement Protocol error: ${res.status} ${res.statusText}`, body);
111
- }
112
- } catch (err) {
113
- console.warn("[GA] Measurement Protocol request failed:", err);
114
- }
115
- }
116
- function googleAnalyticsBackend(opts) {
117
- const { measurementId, debugMode, apiSecret, clientIdSource = "gaCookie" } = opts;
118
- return (ctx) => {
119
- const gaCookie = ctx.cookies.get("_ga");
120
- const gaCookieClientId = gaCookie ? parseGaCookie(gaCookie.value) : null;
121
- return {
122
- name: "google-analytics",
123
- returnsClientActions: true,
124
- supportsUpdates: false,
125
- getClientSideTemplates() {
126
- return {
127
- [GA_TEMPLATE_ID]: {
128
- items: [
129
- {
130
- async: "true",
131
- src: "https://www.googletagmanager.com/gtag/js?id={{measurementId}}",
132
- singleton: true
133
- },
134
- {
135
- body: [
136
- "window.dataLayer = window.dataLayer || [];",
137
- "function gtag(){dataLayer.push(arguments);}",
138
- "gtag('js', new Date());",
139
- "gtag('config', '{{measurementId}}', {{json(config)}});",
140
- "gtag('event', 'page_view');"
141
- ].join("\n")
142
- }
143
- ]
144
- }
145
- };
146
- },
147
- async onEvent(event) {
148
- const clientId = getClientId(event, gaCookieClientId, clientIdSource);
149
- const userId = event.userContext?.userId;
150
- const {
151
- email: _email,
152
- name: _name,
153
- phone: _phone,
154
- ...customTraits
155
- } = event.userContext?.traits ?? {};
156
- const userProperties = Object.keys(customTraits).length > 0 ? customTraits : void 0;
157
- if (event.type === "pageView") {
158
- const config = {
159
- send_page_view: false,
160
- client_id: clientId
161
- };
162
- if (debugMode) {
163
- config.debug_mode = true;
164
- }
165
- if (userId) {
166
- config.user_id = userId;
167
- }
168
- if (userProperties) {
169
- config.user_properties = userProperties;
170
- }
171
- return {
172
- items: [
173
- {
174
- type: "script-template",
175
- templateId: GA_TEMPLATE_ID,
176
- params: {
177
- measurementId,
178
- config
179
- }
180
- }
181
- ]
182
- };
183
- }
184
- if (apiSecret) {
185
- await sendToMeasurementProtocol({
186
- measurementId,
187
- apiSecret,
188
- clientId,
189
- userId,
190
- userProperties,
191
- eventName: toGA4EventName(event.type),
192
- eventParams: buildEventParams(event),
193
- userAgent: getUserAgent(event),
194
- clientIp: getClientIp(event),
195
- debugMode
196
- });
197
- }
198
- },
199
- updateEvent() {
200
- }
201
- };
202
- };
203
- }
204
- // Annotate the CommonJS export names for ESM import in node:
205
- 0 && (module.exports = {
206
- googleAnalyticsBackend
207
- });
@@ -1,21 +0,0 @@
1
- import { NextlyticsBackendFactory } from '../types.mjs';
2
- import 'next/dist/server/web/spec-extension/cookies';
3
- import 'next/server';
4
-
5
- type GoogleAnalyticsBackendOptions = {
6
- /** GA4 Measurement ID (e.g. "G-XXXXXXXXXX") */
7
- measurementId: string;
8
- /** Enable GA4 debug mode (shows events in DebugView) */
9
- debugMode?: boolean;
10
- /** API secret for Measurement Protocol (GA4 Admin → Data Streams → MP secrets) */
11
- apiSecret?: string;
12
- /**
13
- * Source for client_id.
14
- * - "gaCookie" (default): Use _ga cookie set by gtag.js, fall back to anonymousUserId
15
- * - "anonymousUserId": Always use Nextlytics anonymousUserId
16
- */
17
- clientIdSource?: "gaCookie" | "anonymousUserId";
18
- };
19
- declare function googleAnalyticsBackend(opts: GoogleAnalyticsBackendOptions): NextlyticsBackendFactory;
20
-
21
- export { type GoogleAnalyticsBackendOptions, googleAnalyticsBackend };
@@ -1,155 +0,0 @@
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 gtm_exports = {};
20
- __export(gtm_exports, {
21
- googleTagManagerBackend: () => googleTagManagerBackend
22
- });
23
- module.exports = __toCommonJS(gtm_exports);
24
- const GTM_INIT_TEMPLATE_ID = "gtm-init";
25
- const GTM_PAGEVIEW_TEMPLATE_ID = "gtm-pageview";
26
- const GTM_EVENT_TEMPLATE_ID = "gtm-event";
27
- function toSnakeCase(str) {
28
- return str.replace(/([A-Z])/g, "_$1").toLowerCase().replace(/^_/, "");
29
- }
30
- function googleTagManagerBackend(opts) {
31
- const { containerId } = opts;
32
- return {
33
- name: "google-tag-manager",
34
- returnsClientActions: true,
35
- supportsUpdates: false,
36
- getClientSideTemplates() {
37
- return {
38
- [GTM_INIT_TEMPLATE_ID]: {
39
- items: [
40
- {
41
- body: [
42
- "window.dataLayer = window.dataLayer || [];",
43
- "dataLayer.push({{json(initialData)}});",
44
- "if (!window.google_tag_manager || !window.google_tag_manager['{{containerId}}']) {",
45
- " (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':",
46
- " new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],",
47
- " j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=",
48
- " 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);",
49
- " })(window,document,'script','dataLayer','{{containerId}}');",
50
- "}"
51
- ].join("\n")
52
- }
53
- ]
54
- },
55
- [GTM_PAGEVIEW_TEMPLATE_ID]: {
56
- items: [
57
- {
58
- body: [
59
- "window.dataLayer = window.dataLayer || [];",
60
- "dataLayer.push({{json(pageData)}});"
61
- ].join("\n")
62
- }
63
- ]
64
- },
65
- [GTM_EVENT_TEMPLATE_ID]: {
66
- items: [
67
- {
68
- body: [
69
- "window.dataLayer = window.dataLayer || [];",
70
- "dataLayer.push({{json(eventData)}});"
71
- ].join("\n")
72
- }
73
- ]
74
- }
75
- };
76
- },
77
- async onEvent(event) {
78
- if (event.type !== "pageView") {
79
- const eventData = {
80
- event: toSnakeCase(event.type),
81
- eventId: event.eventId,
82
- ...event.properties
83
- };
84
- if (event.userContext?.userId) {
85
- eventData.userId = event.userContext.userId;
86
- }
87
- if (event.anonymousUserId) {
88
- eventData.anonymousUserId = event.anonymousUserId;
89
- }
90
- const traits2 = event.userContext?.traits;
91
- if (traits2 && Object.keys(traits2).length > 0) {
92
- eventData.userTraits = traits2;
93
- }
94
- return {
95
- items: [
96
- {
97
- type: "script-template",
98
- templateId: GTM_EVENT_TEMPLATE_ID,
99
- params: { eventData }
100
- }
101
- ]
102
- };
103
- }
104
- const initialData = {};
105
- if (event.userContext?.userId) {
106
- initialData.userId = event.userContext.userId;
107
- }
108
- if (event.anonymousUserId) {
109
- initialData.anonymousUserId = event.anonymousUserId;
110
- }
111
- const traits = event.userContext?.traits;
112
- if (traits && Object.keys(traits).length > 0) {
113
- initialData.userTraits = traits;
114
- }
115
- const pageData = {
116
- event: "page_view",
117
- eventId: event.eventId,
118
- page_path: event.serverContext.path,
119
- page_title: event.properties.title ?? void 0,
120
- page_location: `${event.serverContext.host}${event.serverContext.path}`
121
- };
122
- if (event.clientContext) {
123
- return {
124
- items: [
125
- {
126
- type: "script-template",
127
- templateId: GTM_PAGEVIEW_TEMPLATE_ID,
128
- params: { pageData }
129
- }
130
- ]
131
- };
132
- }
133
- return {
134
- items: [
135
- {
136
- type: "script-template",
137
- templateId: GTM_INIT_TEMPLATE_ID,
138
- params: { containerId, initialData }
139
- },
140
- {
141
- type: "script-template",
142
- templateId: GTM_PAGEVIEW_TEMPLATE_ID,
143
- params: { pageData }
144
- }
145
- ]
146
- };
147
- },
148
- updateEvent() {
149
- }
150
- };
151
- }
152
- // Annotate the CommonJS export names for ESM import in node:
153
- 0 && (module.exports = {
154
- googleTagManagerBackend
155
- });
@@ -1,11 +0,0 @@
1
- import { NextlyticsBackend } from '../types.mjs';
2
- import 'next/dist/server/web/spec-extension/cookies';
3
- import 'next/server';
4
-
5
- type GoogleTagManagerBackendOptions = {
6
- /** GTM Container ID (e.g. "GTM-XXXXXXX") */
7
- containerId: string;
8
- };
9
- declare function googleTagManagerBackend(opts: GoogleTagManagerBackendOptions): NextlyticsBackend;
10
-
11
- export { type GoogleTagManagerBackendOptions, googleTagManagerBackend };
@@ -1,150 +0,0 @@
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 db_exports = {};
20
- __export(db_exports, {
21
- eventToJsonRow: () => eventToJsonRow,
22
- eventToRow: () => eventToRow,
23
- extractClientContext: () => extractClientContext,
24
- generateChCreateTableSQL: () => generateChCreateTableSQL,
25
- generatePgCreateTableSQL: () => generatePgCreateTableSQL,
26
- isChTableNotFoundError: () => isChTableNotFoundError,
27
- isPgTableNotFoundError: () => isPgTableNotFoundError,
28
- tableColumns: () => tableColumns
29
- });
30
- module.exports = __toCommonJS(db_exports);
31
- const tableColumns = [
32
- { name: "event_id", pgType: "TEXT PRIMARY KEY", chType: "String" },
33
- { name: "parent_event_id", pgType: "TEXT", chType: "Nullable(String)" },
34
- { name: "timestamp", pgType: "TIMESTAMPTZ", chType: "DateTime64(3)" },
35
- { name: "type", pgType: "TEXT", chType: "LowCardinality(String)" },
36
- { name: "anonymous_user_id", pgType: "TEXT", chType: "Nullable(String)" },
37
- { name: "user_id", pgType: "TEXT", chType: "Nullable(String)" },
38
- { name: "user_email", pgType: "TEXT", chType: "Nullable(String)" },
39
- { name: "user_name", pgType: "TEXT", chType: "Nullable(String)" },
40
- { name: "host", pgType: "TEXT", chType: "LowCardinality(String)" },
41
- { name: "method", pgType: "TEXT", chType: "LowCardinality(String)" },
42
- { name: "path", pgType: "TEXT", chType: "String" },
43
- { name: "ip", pgType: "INET", chType: "Nullable(IPv6)" },
44
- { name: "referer", pgType: "TEXT", chType: "Nullable(String)" },
45
- { name: "user_agent", pgType: "TEXT", chType: "Nullable(String)" },
46
- { name: "locale", pgType: "TEXT", chType: "LowCardinality(Nullable(String))" },
47
- { name: "server_context", pgType: "JSONB", chType: "JSON" },
48
- { name: "client_context", pgType: "JSONB", chType: "JSON" },
49
- { name: "user_traits", pgType: "JSONB", chType: "JSON" },
50
- { name: "properties", pgType: "JSONB", chType: "JSON" }
51
- ];
52
- function extractClientContext(ctx, serverCtx) {
53
- const serverReferer = serverCtx?.requestHeaders?.["referer"];
54
- const serverUserAgent = serverCtx?.requestHeaders?.["user-agent"];
55
- const serverLocale = serverCtx?.requestHeaders?.["accept-language"]?.split(",")[0];
56
- if (!ctx) {
57
- return {
58
- referer: serverReferer,
59
- user_agent: serverUserAgent,
60
- locale: serverLocale,
61
- rest: null
62
- };
63
- }
64
- const { referer, userAgent, locale, ...rest } = ctx;
65
- return {
66
- referer: referer ?? serverReferer,
67
- user_agent: userAgent ?? serverUserAgent,
68
- locale: locale ?? serverLocale,
69
- rest: Object.keys(rest).length > 0 ? rest : null
70
- };
71
- }
72
- function extractCommonFields(event) {
73
- const { host, method, path, ip, ...serverContextRest } = event.serverContext;
74
- const clientCtx = extractClientContext(event.clientContext, event.serverContext);
75
- const userTraitsRest = event.userContext?.traits ? (() => {
76
- const { email: _email, name: _name, ...rest } = event.userContext.traits;
77
- return Object.keys(rest).length > 0 ? rest : null;
78
- })() : null;
79
- return {
80
- event_id: event.eventId,
81
- parent_event_id: event.parentEventId ?? null,
82
- timestamp: event.collectedAt,
83
- type: event.type,
84
- anonymous_user_id: event.anonymousUserId ?? null,
85
- user_id: event.userContext?.userId ?? null,
86
- user_email: event.userContext?.traits?.email ?? null,
87
- user_name: event.userContext?.traits?.name ?? null,
88
- host,
89
- method,
90
- path,
91
- ip: ip || null,
92
- referer: clientCtx.referer ?? null,
93
- user_agent: clientCtx.user_agent ?? null,
94
- locale: clientCtx.locale ?? null,
95
- serverContextRest,
96
- clientContextRest: clientCtx.rest,
97
- userTraitsRest,
98
- properties: event.properties
99
- };
100
- }
101
- function eventToRow(event) {
102
- const { serverContextRest, clientContextRest, userTraitsRest, properties, ...common } = extractCommonFields(event);
103
- return {
104
- ...common,
105
- server_context: JSON.stringify(serverContextRest),
106
- client_context: clientContextRest ? JSON.stringify(clientContextRest) : null,
107
- user_traits: userTraitsRest ? JSON.stringify(userTraitsRest) : null,
108
- properties: JSON.stringify(properties)
109
- };
110
- }
111
- function eventToJsonRow(event) {
112
- const { serverContextRest, clientContextRest, userTraitsRest, ...common } = extractCommonFields(event);
113
- return {
114
- ...common,
115
- server_context: serverContextRest,
116
- client_context: clientContextRest ?? {},
117
- user_traits: userTraitsRest ?? {}
118
- };
119
- }
120
- function generatePgCreateTableSQL(tableName) {
121
- const pk = tableColumns[0];
122
- const alters = tableColumns.slice(1).map((col) => `ALTER TABLE ${tableName} ADD COLUMN IF NOT EXISTS ${col.name} ${col.pgType};`).join("\n");
123
- return `CREATE TABLE IF NOT EXISTS ${tableName} (${pk.name} ${pk.pgType});
124
- ${alters}`;
125
- }
126
- function isPgTableNotFoundError(err) {
127
- return err instanceof Error && err.message.includes("does not exist");
128
- }
129
- function generateChCreateTableSQL(database, tableName) {
130
- const fullTable = `${database}.${tableName}`;
131
- const createCols = tableColumns.filter((c) => c.name === "event_id" || c.name === "timestamp").map((c) => `${c.name} ${c.chType}`).join(", ");
132
- const create = `CREATE TABLE IF NOT EXISTS ${fullTable} (${createCols}) ENGINE = ReplacingMergeTree() PARTITION BY toYYYYMM(timestamp) ORDER BY event_id;`;
133
- const alters = tableColumns.filter((c) => c.name !== "event_id" && c.name !== "timestamp").map((c) => `ALTER TABLE ${fullTable} ADD COLUMN IF NOT EXISTS ${c.name} ${c.chType};`).join("\n");
134
- return `${create}
135
- ${alters}`;
136
- }
137
- function isChTableNotFoundError(text) {
138
- return text.includes("UNKNOWN_TABLE") || text.includes("doesn't exist");
139
- }
140
- // Annotate the CommonJS export names for ESM import in node:
141
- 0 && (module.exports = {
142
- eventToJsonRow,
143
- eventToRow,
144
- extractClientContext,
145
- generateChCreateTableSQL,
146
- generatePgCreateTableSQL,
147
- isChTableNotFoundError,
148
- isPgTableNotFoundError,
149
- tableColumns
150
- });
@@ -1,121 +0,0 @@
1
- import { NextlyticsEvent, ClientContext, ServerEventContext } from '../../types.mjs';
2
- import 'next/dist/server/web/spec-extension/cookies';
3
- import 'next/server';
4
-
5
- declare const tableColumns: readonly [{
6
- readonly name: "event_id";
7
- readonly pgType: "TEXT PRIMARY KEY";
8
- readonly chType: "String";
9
- }, {
10
- readonly name: "parent_event_id";
11
- readonly pgType: "TEXT";
12
- readonly chType: "Nullable(String)";
13
- }, {
14
- readonly name: "timestamp";
15
- readonly pgType: "TIMESTAMPTZ";
16
- readonly chType: "DateTime64(3)";
17
- }, {
18
- readonly name: "type";
19
- readonly pgType: "TEXT";
20
- readonly chType: "LowCardinality(String)";
21
- }, {
22
- readonly name: "anonymous_user_id";
23
- readonly pgType: "TEXT";
24
- readonly chType: "Nullable(String)";
25
- }, {
26
- readonly name: "user_id";
27
- readonly pgType: "TEXT";
28
- readonly chType: "Nullable(String)";
29
- }, {
30
- readonly name: "user_email";
31
- readonly pgType: "TEXT";
32
- readonly chType: "Nullable(String)";
33
- }, {
34
- readonly name: "user_name";
35
- readonly pgType: "TEXT";
36
- readonly chType: "Nullable(String)";
37
- }, {
38
- readonly name: "host";
39
- readonly pgType: "TEXT";
40
- readonly chType: "LowCardinality(String)";
41
- }, {
42
- readonly name: "method";
43
- readonly pgType: "TEXT";
44
- readonly chType: "LowCardinality(String)";
45
- }, {
46
- readonly name: "path";
47
- readonly pgType: "TEXT";
48
- readonly chType: "String";
49
- }, {
50
- readonly name: "ip";
51
- readonly pgType: "INET";
52
- readonly chType: "Nullable(IPv6)";
53
- }, {
54
- readonly name: "referer";
55
- readonly pgType: "TEXT";
56
- readonly chType: "Nullable(String)";
57
- }, {
58
- readonly name: "user_agent";
59
- readonly pgType: "TEXT";
60
- readonly chType: "Nullable(String)";
61
- }, {
62
- readonly name: "locale";
63
- readonly pgType: "TEXT";
64
- readonly chType: "LowCardinality(Nullable(String))";
65
- }, {
66
- readonly name: "server_context";
67
- readonly pgType: "JSONB";
68
- readonly chType: "JSON";
69
- }, {
70
- readonly name: "client_context";
71
- readonly pgType: "JSONB";
72
- readonly chType: "JSON";
73
- }, {
74
- readonly name: "user_traits";
75
- readonly pgType: "JSONB";
76
- readonly chType: "JSON";
77
- }, {
78
- readonly name: "properties";
79
- readonly pgType: "JSONB";
80
- readonly chType: "JSON";
81
- }];
82
- type ColumnName = (typeof tableColumns)[number]["name"];
83
- type ClientContextColumns = {
84
- referer: string | undefined;
85
- user_agent: string | undefined;
86
- locale: string | undefined;
87
- rest: Record<string, unknown> | null;
88
- };
89
- declare function extractClientContext(ctx: ClientContext | undefined, serverCtx?: ServerEventContext): ClientContextColumns;
90
- /** For PostgreSQL - JSON fields as strings */
91
- declare function eventToRow(event: NextlyticsEvent): Record<ColumnName, unknown>;
92
- /** For ClickHouse/PostgREST - JSON fields as objects */
93
- declare function eventToJsonRow(event: NextlyticsEvent): Record<ColumnName, unknown>;
94
- declare function generatePgCreateTableSQL(tableName: string): string;
95
- declare function isPgTableNotFoundError(err: unknown): boolean;
96
- declare function generateChCreateTableSQL(database: string, tableName: string): string;
97
- declare function isChTableNotFoundError(text: string): boolean;
98
- /** Row type returned from analytics table queries */
99
- interface AnalyticsEventRow {
100
- event_id: string;
101
- parent_event_id: string | null;
102
- timestamp: string;
103
- type: string;
104
- anonymous_user_id: string | null;
105
- user_id: string | null;
106
- user_email: string | null;
107
- user_name: string | null;
108
- host: string;
109
- method: string;
110
- path: string;
111
- ip: string | null;
112
- referer: string | null;
113
- user_agent: string | null;
114
- locale: string | null;
115
- server_context: Record<string, unknown>;
116
- client_context: Record<string, unknown>;
117
- user_traits: Record<string, unknown>;
118
- properties: Record<string, unknown>;
119
- }
120
-
121
- export { type AnalyticsEventRow, type ClientContextColumns, type ColumnName, eventToJsonRow, eventToRow, extractClientContext, generateChCreateTableSQL, generatePgCreateTableSQL, isChTableNotFoundError, isPgTableNotFoundError, tableColumns };