@casoon/trackr 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/README.md ADDED
@@ -0,0 +1,142 @@
1
+ # @casoon/trackr
2
+
3
+ Privacy-first, GDPR-native analytics for static sites. No cookies, no persistent IDs, self-hosted.
4
+
5
+ ## Features
6
+
7
+ - **Privacy by Default** - No cookies, no localStorage, no fingerprinting
8
+ - **Lightweight** - Client script < 1KB gzipped
9
+ - **Self-Hosted** - Your data stays on your infrastructure
10
+ - **Astro-First** - Designed for Astro, works with any static site
11
+ - **Flexible Storage** - Postgres or external API (Plausible, Umami)
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pnpm add @casoon/trackr
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ ### 1. Add the client script
22
+
23
+ ```astro
24
+ ---
25
+ // src/components/Analytics.astro
26
+ ---
27
+ <script>
28
+ import { init } from "@casoon/trackr/client";
29
+ init({ endpoint: "/api/track" });
30
+ </script>
31
+ ```
32
+
33
+ Include in your layout:
34
+
35
+ ```astro
36
+ ---
37
+ import Analytics from "../components/Analytics.astro";
38
+ ---
39
+ <html>
40
+ <body>
41
+ <slot />
42
+ <Analytics />
43
+ </body>
44
+ </html>
45
+ ```
46
+
47
+ ### 2. Create the API endpoint
48
+
49
+ ```typescript
50
+ // src/pages/api/track.ts
51
+ import type { APIRoute } from "astro";
52
+ import { createHandler } from "@casoon/trackr/server";
53
+ import { postgres } from "@casoon/trackr/storage/postgres";
54
+
55
+ const handler = createHandler({
56
+ storage: postgres(import.meta.env.DATABASE_URL),
57
+ privacy: {
58
+ anonymizeIp: true,
59
+ stripPii: true
60
+ },
61
+ botFilter: true
62
+ });
63
+
64
+ export const POST: APIRoute = async ({ request }) => {
65
+ return handler(request);
66
+ };
67
+ ```
68
+
69
+ ### 3. Set up the database
70
+
71
+ ```sql
72
+ CREATE TABLE trackr_events (
73
+ id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
74
+ ts TIMESTAMPTZ NOT NULL DEFAULT NOW(),
75
+ type TEXT NOT NULL,
76
+ name TEXT,
77
+ url TEXT NOT NULL,
78
+ referrer_domain TEXT,
79
+ country TEXT,
80
+ device TEXT,
81
+ browser TEXT,
82
+ session_id TEXT,
83
+ props JSONB DEFAULT '{}'
84
+ );
85
+
86
+ CREATE INDEX idx_trackr_ts ON trackr_events (ts);
87
+ CREATE INDEX idx_trackr_url ON trackr_events (url);
88
+ ```
89
+
90
+ ## Custom Events
91
+
92
+ ```typescript
93
+ import { track } from "@casoon/trackr/client";
94
+
95
+ // Track button click
96
+ document.querySelector("#signup").addEventListener("click", () => {
97
+ track("signup_click", { plan: "pro" });
98
+ });
99
+ ```
100
+
101
+ ## Storage Adapters
102
+
103
+ ### Postgres
104
+
105
+ ```typescript
106
+ import { postgres } from "@casoon/trackr/storage/postgres";
107
+
108
+ const storage = postgres(process.env.DATABASE_URL);
109
+ ```
110
+
111
+ ### External API
112
+
113
+ Forward events to Plausible, Umami, or any other service:
114
+
115
+ ```typescript
116
+ import { api } from "@casoon/trackr/storage/api";
117
+
118
+ const storage = api({
119
+ url: "https://plausible.io/api/event",
120
+ headers: { "Authorization": "Bearer ..." },
121
+ transform: (event) => ({
122
+ name: event.type === "pageview" ? "pageview" : event.name,
123
+ url: event.url,
124
+ domain: "your-domain.com"
125
+ })
126
+ });
127
+ ```
128
+
129
+ ## Privacy Features
130
+
131
+ - **IP Anonymization** - Last octet removed before any processing
132
+ - **PII Filtering** - Email, phone, tokens stripped from URLs
133
+ - **No Cookies** - Session ID derived from anonymized IP + UA + date
134
+ - **Bot Filtering** - Common bots and crawlers excluded
135
+
136
+ ## License
137
+
138
+ LGPL-3.0-or-later
139
+
140
+ ## Author
141
+
142
+ Joern Seidel <joern@casoon.de>
@@ -0,0 +1,38 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined") return require.apply(this, arguments);
11
+ throw Error('Dynamic require of "' + x + '" is not supported');
12
+ });
13
+ var __commonJS = (cb, mod) => function __require2() {
14
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
+ // If the importer is in node compatibility mode or this is not an ESM
26
+ // file that has been converted to a CommonJS file using a Babel-
27
+ // compatible transform (i.e. "__esModule" has not been set), then set
28
+ // "default" to the CommonJS "module.exports" for node compatibility.
29
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
+ mod
31
+ ));
32
+
33
+ export {
34
+ __require,
35
+ __commonJS,
36
+ __toESM
37
+ };
38
+ //# sourceMappingURL=chunk-7D4SUZUM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,58 @@
1
+ // src/client/index.ts
2
+ var config = null;
3
+ function init(options) {
4
+ config = options;
5
+ trackPageview();
6
+ if (typeof window !== "undefined") {
7
+ window.addEventListener("popstate", trackPageview);
8
+ }
9
+ }
10
+ function track(name, props) {
11
+ if (!config) {
12
+ console.warn("[trackr] Not initialized. Call init() first.");
13
+ return;
14
+ }
15
+ sendEvent({
16
+ type: "event",
17
+ name,
18
+ url: getPath(),
19
+ props,
20
+ ts: Date.now()
21
+ });
22
+ }
23
+ function trackPageview() {
24
+ if (!config) return;
25
+ sendEvent({
26
+ type: "pageview",
27
+ url: getPath(),
28
+ referrer: document.referrer ? new URL(document.referrer).hostname : void 0,
29
+ ts: Date.now()
30
+ });
31
+ }
32
+ function getPath() {
33
+ return window.location.pathname;
34
+ }
35
+ function sendEvent(event) {
36
+ if (!config) return;
37
+ const body = JSON.stringify(event);
38
+ if (navigator.sendBeacon) {
39
+ navigator.sendBeacon(config.endpoint, body);
40
+ } else {
41
+ fetch(config.endpoint, {
42
+ method: "POST",
43
+ body,
44
+ keepalive: true,
45
+ headers: { "Content-Type": "application/json" }
46
+ }).catch(() => {
47
+ });
48
+ }
49
+ if (config.debug) {
50
+ console.log("[trackr]", event);
51
+ }
52
+ }
53
+
54
+ export {
55
+ init,
56
+ track
57
+ };
58
+ //# sourceMappingURL=chunk-ABUPERUQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client/index.ts"],"sourcesContent":["import type { TrackrConfig } from \"../types.js\";\n\nlet config: TrackrConfig | null = null;\n\nexport function init(options: TrackrConfig): void {\n config = options;\n trackPageview();\n \n if (typeof window !== \"undefined\") {\n window.addEventListener(\"popstate\", trackPageview);\n }\n}\n\nexport function track(name: string, props?: Record<string, string | number | boolean>): void {\n if (!config) {\n console.warn(\"[trackr] Not initialized. Call init() first.\");\n return;\n }\n \n sendEvent({\n type: \"event\",\n name,\n url: getPath(),\n props,\n ts: Date.now()\n });\n}\n\nfunction trackPageview(): void {\n if (!config) return;\n \n sendEvent({\n type: \"pageview\",\n url: getPath(),\n referrer: document.referrer ? new URL(document.referrer).hostname : undefined,\n ts: Date.now()\n });\n}\n\nfunction getPath(): string {\n return window.location.pathname;\n}\n\nfunction sendEvent(event: Record<string, unknown>): void {\n if (!config) return;\n \n const body = JSON.stringify(event);\n \n if (navigator.sendBeacon) {\n navigator.sendBeacon(config.endpoint, body);\n } else {\n fetch(config.endpoint, {\n method: \"POST\",\n body,\n keepalive: true,\n headers: { \"Content-Type\": \"application/json\" }\n }).catch(() => {});\n }\n \n if (config.debug) {\n console.log(\"[trackr]\", event);\n }\n}\n"],"mappings":";AAEA,IAAI,SAA8B;AAE3B,SAAS,KAAK,SAA6B;AAChD,WAAS;AACT,gBAAc;AAEd,MAAI,OAAO,WAAW,aAAa;AACjC,WAAO,iBAAiB,YAAY,aAAa;AAAA,EACnD;AACF;AAEO,SAAS,MAAM,MAAc,OAAyD;AAC3F,MAAI,CAAC,QAAQ;AACX,YAAQ,KAAK,8CAA8C;AAC3D;AAAA,EACF;AAEA,YAAU;AAAA,IACR,MAAM;AAAA,IACN;AAAA,IACA,KAAK,QAAQ;AAAA,IACb;AAAA,IACA,IAAI,KAAK,IAAI;AAAA,EACf,CAAC;AACH;AAEA,SAAS,gBAAsB;AAC7B,MAAI,CAAC,OAAQ;AAEb,YAAU;AAAA,IACR,MAAM;AAAA,IACN,KAAK,QAAQ;AAAA,IACb,UAAU,SAAS,WAAW,IAAI,IAAI,SAAS,QAAQ,EAAE,WAAW;AAAA,IACpE,IAAI,KAAK,IAAI;AAAA,EACf,CAAC;AACH;AAEA,SAAS,UAAkB;AACzB,SAAO,OAAO,SAAS;AACzB;AAEA,SAAS,UAAU,OAAsC;AACvD,MAAI,CAAC,OAAQ;AAEb,QAAM,OAAO,KAAK,UAAU,KAAK;AAEjC,MAAI,UAAU,YAAY;AACxB,cAAU,WAAW,OAAO,UAAU,IAAI;AAAA,EAC5C,OAAO;AACL,UAAM,OAAO,UAAU;AAAA,MACrB,QAAQ;AAAA,MACR;AAAA,MACA,WAAW;AAAA,MACX,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,IAChD,CAAC,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAAA,EACnB;AAEA,MAAI,OAAO,OAAO;AAChB,YAAQ,IAAI,YAAY,KAAK;AAAA,EAC/B;AACF;","names":[]}
@@ -0,0 +1,153 @@
1
+ // src/server/bot.ts
2
+ var BOT_PATTERNS = [
3
+ /bot/i,
4
+ /crawler/i,
5
+ /spider/i,
6
+ /crawling/i,
7
+ /headless/i,
8
+ /phantom/i,
9
+ /selenium/i,
10
+ /google/i,
11
+ /bing/i,
12
+ /yahoo/i,
13
+ /baidu/i,
14
+ /facebook/i,
15
+ /twitter/i,
16
+ /linkedin/i,
17
+ /slack/i,
18
+ /discord/i,
19
+ /telegram/i,
20
+ /preview/i,
21
+ /curl/i,
22
+ /wget/i,
23
+ /monitoring/i,
24
+ /uptime/i,
25
+ /pingdom/i
26
+ ];
27
+ function isBot(request) {
28
+ const ua = request.headers.get("user-agent") || "";
29
+ if (BOT_PATTERNS.some((p) => p.test(ua))) return true;
30
+ if (!request.headers.get("accept-language")) return true;
31
+ if (ua.length < 20) return true;
32
+ return false;
33
+ }
34
+
35
+ // src/server/privacy.ts
36
+ var PII_PARAMS = ["email", "mail", "phone", "name", "token", "key", "password", "secret"];
37
+ function anonymizeIp(ip) {
38
+ if (ip.includes(".")) {
39
+ return ip.split(".").slice(0, 3).join(".") + ".0";
40
+ }
41
+ return ip.split(":").slice(0, 4).join(":") + "::";
42
+ }
43
+ function stripPii(url) {
44
+ try {
45
+ const u = new URL(url, "http://localhost");
46
+ PII_PARAMS.forEach((p) => u.searchParams.delete(p));
47
+ return u.pathname + (u.search || "");
48
+ } catch {
49
+ return url;
50
+ }
51
+ }
52
+ function createSessionId(ip, ua, date) {
53
+ const input = anonymizeIp(ip) + "|" + ua + "|" + date;
54
+ return simpleHash(input).slice(0, 16);
55
+ }
56
+ function simpleHash(str) {
57
+ let hash = 0;
58
+ for (let i = 0; i < str.length; i++) {
59
+ const char = str.charCodeAt(i);
60
+ hash = (hash << 5) - hash + char;
61
+ hash = hash & hash;
62
+ }
63
+ return Math.abs(hash).toString(36);
64
+ }
65
+ function applyPrivacy(event, config) {
66
+ const result = { ...event };
67
+ if (config.stripPii && result.url) {
68
+ result.url = stripPii(result.url);
69
+ }
70
+ if (config.stripQueryParams && result.url) {
71
+ try {
72
+ const u = new URL(result.url, "http://localhost");
73
+ config.stripQueryParams.forEach((p) => {
74
+ if (p.endsWith("*")) {
75
+ const prefix = p.slice(0, -1);
76
+ [...u.searchParams.keys()].filter((k) => k.startsWith(prefix)).forEach((k) => u.searchParams.delete(k));
77
+ } else {
78
+ u.searchParams.delete(p);
79
+ }
80
+ });
81
+ result.url = u.pathname + (u.search || "");
82
+ } catch {
83
+ }
84
+ }
85
+ return result;
86
+ }
87
+
88
+ // src/server/index.ts
89
+ function createHandler(config) {
90
+ return async (request) => {
91
+ if (request.method !== "POST") {
92
+ return new Response("Method not allowed", { status: 405 });
93
+ }
94
+ if (config.botFilter && isBot(request)) {
95
+ return new Response("OK");
96
+ }
97
+ try {
98
+ const body = await request.json();
99
+ if (!isValidEvent(body)) {
100
+ return new Response("Invalid event", { status: 400 });
101
+ }
102
+ let event = {
103
+ type: body.type,
104
+ name: body.name,
105
+ url: body.url,
106
+ referrer: body.referrer,
107
+ props: body.props,
108
+ ts: body.ts
109
+ };
110
+ if (config.privacy) {
111
+ event = applyPrivacy(event, config.privacy);
112
+ }
113
+ const ip = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || request.headers.get("x-real-ip") || "0.0.0.0";
114
+ const ua = request.headers.get("user-agent") || "";
115
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
116
+ if (config.privacy?.anonymizeIp !== false) {
117
+ event.sessionId = createSessionId(ip, ua, today);
118
+ }
119
+ event.device = detectDevice(ua);
120
+ event.browser = detectBrowser(ua);
121
+ await config.storage.save(event);
122
+ return new Response("OK");
123
+ } catch {
124
+ return new Response("Error", { status: 500 });
125
+ }
126
+ };
127
+ }
128
+ function isValidEvent(e) {
129
+ if (typeof e !== "object" || e === null) return false;
130
+ const obj = e;
131
+ return typeof obj.type === "string" && typeof obj.url === "string" && typeof obj.ts === "number";
132
+ }
133
+ function detectDevice(ua) {
134
+ if (/tablet|ipad/i.test(ua)) return "tablet";
135
+ if (/mobile|android|iphone/i.test(ua)) return "mobile";
136
+ return "desktop";
137
+ }
138
+ function detectBrowser(ua) {
139
+ if (/firefox/i.test(ua)) return "Firefox";
140
+ if (/edg/i.test(ua)) return "Edge";
141
+ if (/chrome/i.test(ua)) return "Chrome";
142
+ if (/safari/i.test(ua)) return "Safari";
143
+ return "Other";
144
+ }
145
+
146
+ export {
147
+ isBot,
148
+ anonymizeIp,
149
+ stripPii,
150
+ applyPrivacy,
151
+ createHandler
152
+ };
153
+ //# sourceMappingURL=chunk-L3N32JO4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server/bot.ts","../src/server/privacy.ts","../src/server/index.ts"],"sourcesContent":["const BOT_PATTERNS = [\n /bot/i, /crawler/i, /spider/i, /crawling/i,\n /headless/i, /phantom/i, /selenium/i,\n /google/i, /bing/i, /yahoo/i, /baidu/i,\n /facebook/i, /twitter/i, /linkedin/i,\n /slack/i, /discord/i, /telegram/i,\n /preview/i, /curl/i, /wget/i,\n /monitoring/i, /uptime/i, /pingdom/i\n];\n\nexport function isBot(request: Request): boolean {\n const ua = request.headers.get(\"user-agent\") || \"\";\n \n if (BOT_PATTERNS.some(p => p.test(ua))) return true;\n if (!request.headers.get(\"accept-language\")) return true;\n if (ua.length < 20) return true;\n \n return false;\n}\n","import type { PrivacyConfig, TrackrEvent } from \"../types.js\";\n\nconst PII_PARAMS = [\"email\", \"mail\", \"phone\", \"name\", \"token\", \"key\", \"password\", \"secret\"];\n\nexport function anonymizeIp(ip: string): string {\n if (ip.includes(\".\")) {\n return ip.split(\".\").slice(0, 3).join(\".\") + \".0\";\n }\n return ip.split(\":\").slice(0, 4).join(\":\") + \"::\";\n}\n\nexport function stripPii(url: string): string {\n try {\n const u = new URL(url, \"http://localhost\");\n PII_PARAMS.forEach(p => u.searchParams.delete(p));\n return u.pathname + (u.search || \"\");\n } catch {\n return url;\n }\n}\n\nexport function createSessionId(ip: string, ua: string, date: string): string {\n const input = anonymizeIp(ip) + \"|\" + ua + \"|\" + date;\n return simpleHash(input).slice(0, 16);\n}\n\nfunction simpleHash(str: string): string {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash;\n }\n return Math.abs(hash).toString(36);\n}\n\nexport function applyPrivacy(\n event: TrackrEvent,\n config: PrivacyConfig\n): TrackrEvent {\n const result = { ...event };\n\n if (config.stripPii && result.url) {\n result.url = stripPii(result.url);\n }\n\n if (config.stripQueryParams && result.url) {\n try {\n const u = new URL(result.url, \"http://localhost\");\n config.stripQueryParams.forEach(p => {\n if (p.endsWith(\"*\")) {\n const prefix = p.slice(0, -1);\n [...u.searchParams.keys()]\n .filter(k => k.startsWith(prefix))\n .forEach(k => u.searchParams.delete(k));\n } else {\n u.searchParams.delete(p);\n }\n });\n result.url = u.pathname + (u.search || \"\");\n } catch {}\n }\n\n return result;\n}\n","import type { HandlerConfig, TrackrEvent } from \"../types.js\";\nimport { isBot } from \"./bot.js\";\nimport { applyPrivacy, createSessionId } from \"./privacy.js\";\n\ninterface RawEvent {\n type: string;\n url: string;\n ts: number;\n name?: string;\n referrer?: string;\n props?: Record<string, string | number | boolean>;\n}\n\nexport function createHandler(config: HandlerConfig): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n if (request.method !== \"POST\") {\n return new Response(\"Method not allowed\", { status: 405 });\n }\n\n if (config.botFilter && isBot(request)) {\n return new Response(\"OK\");\n }\n\n try {\n const body = await request.json() as unknown;\n\n if (!isValidEvent(body)) {\n return new Response(\"Invalid event\", { status: 400 });\n }\n\n let event: TrackrEvent = {\n type: body.type as \"pageview\" | \"event\",\n name: body.name,\n url: body.url,\n referrer: body.referrer,\n props: body.props,\n ts: body.ts\n };\n\n if (config.privacy) {\n event = applyPrivacy(event, config.privacy);\n }\n\n const ip = request.headers.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim()\n || request.headers.get(\"x-real-ip\")\n || \"0.0.0.0\";\n const ua = request.headers.get(\"user-agent\") || \"\";\n const today = new Date().toISOString().split(\"T\")[0];\n\n if (config.privacy?.anonymizeIp !== false) {\n event.sessionId = createSessionId(ip, ua, today);\n }\n\n event.device = detectDevice(ua);\n event.browser = detectBrowser(ua);\n\n await config.storage.save(event);\n\n return new Response(\"OK\");\n } catch {\n return new Response(\"Error\", { status: 500 });\n }\n };\n}\n\nfunction isValidEvent(e: unknown): e is RawEvent {\n if (typeof e !== \"object\" || e === null) return false;\n const obj = e as Record<string, unknown>;\n return typeof obj.type === \"string\" && typeof obj.url === \"string\" && typeof obj.ts === \"number\";\n}\n\nfunction detectDevice(ua: string): \"desktop\" | \"mobile\" | \"tablet\" {\n if (/tablet|ipad/i.test(ua)) return \"tablet\";\n if (/mobile|android|iphone/i.test(ua)) return \"mobile\";\n return \"desktop\";\n}\n\nfunction detectBrowser(ua: string): string {\n if (/firefox/i.test(ua)) return \"Firefox\";\n if (/edg/i.test(ua)) return \"Edge\";\n if (/chrome/i.test(ua)) return \"Chrome\";\n if (/safari/i.test(ua)) return \"Safari\";\n return \"Other\";\n}\n\nexport { isBot } from \"./bot.js\";\nexport { anonymizeIp, stripPii, applyPrivacy } from \"./privacy.js\";\n"],"mappings":";AAAA,IAAM,eAAe;AAAA,EACnB;AAAA,EAAQ;AAAA,EAAY;AAAA,EAAW;AAAA,EAC/B;AAAA,EAAa;AAAA,EAAY;AAAA,EACzB;AAAA,EAAW;AAAA,EAAS;AAAA,EAAU;AAAA,EAC9B;AAAA,EAAa;AAAA,EAAY;AAAA,EACzB;AAAA,EAAU;AAAA,EAAY;AAAA,EACtB;AAAA,EAAY;AAAA,EAAS;AAAA,EACrB;AAAA,EAAe;AAAA,EAAW;AAC5B;AAEO,SAAS,MAAM,SAA2B;AAC/C,QAAM,KAAK,QAAQ,QAAQ,IAAI,YAAY,KAAK;AAEhD,MAAI,aAAa,KAAK,OAAK,EAAE,KAAK,EAAE,CAAC,EAAG,QAAO;AAC/C,MAAI,CAAC,QAAQ,QAAQ,IAAI,iBAAiB,EAAG,QAAO;AACpD,MAAI,GAAG,SAAS,G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AAM,SAAQ,oBAAI,KAAK,GAAE,YAAY,EAAE,MAAM,GAAG,EAAE,CAAC;AAEnD,UAAI,OAAO,SAAS,gBAAgB,OAAO;AACzC,cAAM,YAAY,gBAAgB,IAAI,IAAI,KAAK;AAAA,MACjD;AAEA,YAAM,SAAS,aAAa,EAAE;AAC9B,YAAM,UAAU,cAAc,EAAE;AAEhC,YAAM,OAAO,QAAQ,KAAK,KAAK;AAE/B,aAAO,IAAI,SAAS,IAAI;AAAA,IAC1B,QAAQ;AACN,aAAO,IAAI,SAAS,SAAS,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC9C;AAAA,EACF;AACF;AAEA,SAAS,aAAa,GAA2B;AAC/C,MAAI,OAAO,MAAM,YAAY,MAAM,KAAM,QAAO;AAChD,QAAM,MAAM;AACZ,SAAO,OAAO,IAAI,SAAS,YAAY,OAAO,IAAI,QAAQ,YAAY,OAAO,IAAI,OAAO;AAC1F;AAEA,SAAS,aAAa,IAA6C;AACjE,MAAI,eAAe,KAAK,EAAE,EAAG,QAAO;AACpC,MAAI,yBAAyB,KAAK,EAAE,EAAG,QAAO;AAC9C,SAAO;AACT;AAEA,SAAS,cAAc,IAAoB;AACzC,MAAI,WAAW,KAAK,EAAE,EAAG,QAAO;AAChC,MAAI,OAAO,KAAK,EAAE,EAAG,QAAO;AAC5B,MAAI,UAAU,KAAK,EAAE,EAAG,QAAO;AAC/B,MAAI,UAAU,KAAK,EAAE,EAAG,QAAO;AAC/B,SAAO;AACT;","names":[]}
@@ -0,0 +1,6 @@
1
+ import { a as TrackrConfig } from '../types-EaeYBDKE.js';
2
+
3
+ declare function init(options: TrackrConfig): void;
4
+ declare function track(name: string, props?: Record<string, string | number | boolean>): void;
5
+
6
+ export { init, track };
@@ -0,0 +1,10 @@
1
+ import {
2
+ init,
3
+ track
4
+ } from "../chunk-ABUPERUQ.js";
5
+ import "../chunk-7D4SUZUM.js";
6
+ export {
7
+ init,
8
+ track
9
+ };
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}