@pageflock/analytics 0.1.0 → 0.1.2

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/README.md CHANGED
@@ -10,7 +10,7 @@ The script tag still works on its own (see [`@pageflock/tracker`](https://www.np
10
10
  npm install @pageflock/analytics
11
11
  ```
12
12
 
13
- You need a site ID from the Pageflock dashboard and the URL of your ingest Worker's collect endpoint, `https://YOUR-PAGEFLOCK-INGEST/api/e`.
13
+ You need a site ID from the Pageflock dashboard. Events go to Pageflock's hosted ingest, `https://e.pageflock.com/api/e`, unless you set `endpoint` (see [Self-hosting](#self-hosting)).
14
14
 
15
15
  ## Next.js
16
16
 
@@ -28,10 +28,7 @@ export default function RootLayout({
28
28
  <html lang="en">
29
29
  <body>
30
30
  {children}
31
- <Analytics
32
- site="SITE_ID"
33
- endpoint="https://YOUR-PAGEFLOCK-INGEST/api/e"
34
- />
31
+ <Analytics site="SITE_ID" />
35
32
  </body>
36
33
  </html>
37
34
  );
@@ -48,7 +45,7 @@ import { Analytics } from "@pageflock/analytics/react";
48
45
  export const App = () => (
49
46
  <>
50
47
  <Routes />
51
- <Analytics site="SITE_ID" endpoint="https://YOUR-PAGEFLOCK-INGEST/api/e" />
48
+ <Analytics site="SITE_ID" />
52
49
  </>
53
50
  );
54
51
  ```
@@ -65,7 +62,7 @@ import { Analytics } from "@pageflock/analytics/vue";
65
62
  </script>
66
63
 
67
64
  <template>
68
- <Analytics site="SITE_ID" endpoint="https://YOUR-PAGEFLOCK-INGEST/api/e" />
65
+ <Analytics site="SITE_ID" />
69
66
  <RouterView />
70
67
  </template>
71
68
  ```
@@ -79,7 +76,7 @@ import { Analytics } from "@pageflock/analytics/vue";
79
76
  import { inject } from "@pageflock/analytics";
80
77
  import { dev } from "$app/environment";
81
78
 
82
- inject({ site: "SITE_ID", endpoint: "https://YOUR-PAGEFLOCK-INGEST/api/e", debug: dev });
79
+ inject({ site: "SITE_ID", debug: dev });
83
80
 
84
81
  let { children } = $props();
85
82
  </script>
@@ -95,7 +92,7 @@ Astro bundles `<script>` tags, so add this to your base layout:
95
92
  <script>
96
93
  import { inject } from "@pageflock/analytics";
97
94
 
98
- inject({ site: "SITE_ID", endpoint: "https://YOUR-PAGEFLOCK-INGEST/api/e" });
95
+ inject({ site: "SITE_ID" });
99
96
  </script>
100
97
  ```
101
98
 
@@ -104,7 +101,7 @@ Astro bundles `<script>` tags, so add this to your base layout:
104
101
  ```ts
105
102
  import { inject } from "@pageflock/analytics";
106
103
 
107
- inject({ site: "SITE_ID", endpoint: "https://YOUR-PAGEFLOCK-INGEST/api/e" });
104
+ inject({ site: "SITE_ID" });
108
105
  ```
109
106
 
110
107
  ## Custom events
@@ -126,22 +123,51 @@ No-code events work too: `<button data-track="Signup" data-track-plan="pro">`.
126
123
  | Option | Type | Default | What it does |
127
124
  | --- | --- | --- | --- |
128
125
  | `site` | `string` | required | The site ID from the Pageflock dashboard. |
129
- | `endpoint` | `string` | required | The collect endpoint, `https://YOUR-PAGEFLOCK-INGEST/api/e`. |
126
+ | `endpoint` | `string` | `https://e.pageflock.com/api/e` | The collect endpoint. Only set it when you self-host. |
130
127
  | `autoEvents` | `boolean` | `false` | Also track outbound link clicks, file downloads and 404 pages, like `s.auto.js`. |
131
128
  | `hashRouting` | `boolean` | `false` | Count `#hash` changes as page views, for hash-routed apps. |
132
129
  | `beforeSend` | `(event: AnalyticsEvent) => AnalyticsEvent \| null` | none | Change an event before it is sent, or return `null` to drop it. |
130
+ | `mask` | `string[]` | none | Route patterns, such as `/projects/[id]`, reported in place of the paths they match. See [Masking URLs](#masking-urls). |
133
131
  | `debug` | `boolean` | `false` | Log every event to the console, including on localhost. |
134
132
 
135
- `site`, `endpoint`, `autoEvents` and `hashRouting` are read when tracking starts. `beforeSend` and `debug` can change on later renders.
133
+ `site`, `endpoint`, `autoEvents` and `hashRouting` are read when tracking starts. `beforeSend`, `mask` and `debug` can change on later renders.
134
+
135
+ ### Masking URLs
136
+
137
+ Paths often carry data that belongs to your users: a project's name, an order number, an invite token. Pass the routes that hold it as `mask`, and each page view and event on a matching path is reported as the route pattern instead, so `/projects/acme-launch/settings` arrives as `/projects/[id]/settings`, and so does the `path` of a 404 event. The real path never leaves the browser, and the dashboard groups every project under one row.
138
+
139
+ ```tsx
140
+ <Analytics
141
+ site="SITE_ID"
142
+ mask={["/projects/[id]", "/projects/[id]/settings", "/docs/[...slug]"]}
143
+ />
144
+ ```
145
+
146
+ Patterns use file-router syntax: `[name]` matches one segment, `[...name]` one or more, and `[[...name]]` zero or more. When several match, the most specific wins, so `/projects/new` beats `/projects/[id]`. Paths that match no pattern are sent as they are. The query string is kept, since Pageflock only stores UTM tags and the parameters you allow from it.
147
+
148
+ `beforeSend` runs first and sees the real URL, so it can still drop pages by their path. List only the dynamic routes; static paths have nothing to hide.
149
+
150
+ ### Self-hosting
151
+
152
+ Running your own Pageflock? Point `endpoint` at your ingest Worker's collect endpoint:
153
+
154
+ ```tsx
155
+ <Analytics site="SITE_ID" endpoint="https://YOUR-PAGEFLOCK-INGEST/api/e" />
156
+ ```
157
+
158
+ The install screen in your own dashboard fills this in for you.
159
+
160
+ ### Content Security Policy
161
+
162
+ If your site sets a Content Security Policy, allow the endpoint in `connect-src`, for example `connect-src 'self' https://e.pageflock.com`. The package is bundled into your code, so `script-src` needs nothing new.
136
163
 
137
164
  ### beforeSend
138
165
 
139
- Every event, page views included, passes through `beforeSend` as `{ name, url, props }`. Page views are named `pageview`, and time on page is sent as `engagement`.
166
+ Every event, page views included, passes through `beforeSend` as `{ name, url, props }`. Page views are named `pageview`, and time on page and scroll depth are sent as `engagement`.
140
167
 
141
168
  ```tsx
142
169
  <Analytics
143
170
  site="SITE_ID"
144
- endpoint="https://YOUR-PAGEFLOCK-INGEST/api/e"
145
171
  beforeSend={(event) => {
146
172
  if (new URL(event.url).pathname.startsWith("/admin")) {
147
173
  return null;
@@ -158,7 +184,3 @@ Every event, page views included, passes through `beforeSend` as `{ name, url, p
158
184
  Like the script, the package sends nothing on `localhost`, from `file:` pages or in automated browsers, and it waits until a prerendered page is shown. Turn on `debug` to see what would be sent. It uses no cookies, no `localStorage` or `sessionStorage`, and no fingerprinting APIs.
159
185
 
160
186
  Each entry bundles the tracker core, so the package has no runtime dependencies. React and Vue are optional peer dependencies.
161
-
162
- ## Licence
163
-
164
- MIT, unlike the rest of the Pageflock repository, so it can ship in any site.
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  inject
3
- } from "./chunk-7JF7P3VW.js";
3
+ } from "./chunk-UXUNZ35R.js";
4
4
 
5
5
  // src/react.ts
6
6
  import { useEffect } from "react";
@@ -38,6 +38,13 @@ var createTracker = (options) => {
38
38
  let lastUrl;
39
39
  let visibleSince = Date.now();
40
40
  let engaged = 0;
41
+ let depth = 0;
42
+ const measureDepth = () => {
43
+ depth = Math.max(
44
+ depth,
45
+ (scrollY + innerHeight) / document.documentElement.scrollHeight
46
+ );
47
+ };
41
48
  const send = (eventName, eventProps, extra) => {
42
49
  let name = eventName;
43
50
  let url = lastUrl ?? location.href;
@@ -70,10 +77,12 @@ var createTracker = (options) => {
70
77
  engaged += Date.now() - visibleSince;
71
78
  }
72
79
  visibleSince = Date.now();
80
+ measureDepth();
73
81
  if (lastUrl && engaged > 0) {
74
- send("engagement", void 0, { e: engaged });
82
+ send("engagement", void 0, { e: engaged, d: depth });
75
83
  }
76
84
  engaged = 0;
85
+ depth = 0;
77
86
  };
78
87
  const pageview = () => {
79
88
  const url = hashRouting ? location.href : location.href.split("#")[0];
@@ -103,6 +112,7 @@ var createTracker = (options) => {
103
112
  }
104
113
  });
105
114
  addEventListener("pagehide", flushEngagement);
115
+ addEventListener("scroll", measureDepth, { passive: true });
106
116
  document.addEventListener("click", (event) => {
107
117
  const element = event.target?.closest?.(
108
118
  "[data-track]"
@@ -114,8 +124,13 @@ var createTracker = (options) => {
114
124
  });
115
125
  return { track: (name, props) => send(name, props), pageview };
116
126
  };
117
- var init = ({ autoEvents, ...options }) => {
118
- const tracker = createTracker(options);
127
+ var DEFAULT_ENDPOINT = "https://e.pageflock.com/api/e";
128
+ var init = ({
129
+ autoEvents,
130
+ endpoint = DEFAULT_ENDPOINT,
131
+ ...options
132
+ }) => {
133
+ const tracker = createTracker({ ...options, endpoint });
119
134
  tracker.pageview();
120
135
  if (autoEvents) {
121
136
  installAutoEvents(tracker);
@@ -123,6 +138,89 @@ var init = ({ autoEvents, ...options }) => {
123
138
  return tracker;
124
139
  };
125
140
 
141
+ // src/mask.ts
142
+ var OPTIONAL_REST = /^\[\[\.\.\..+\]\]$/u;
143
+ var REST = /^\[\.\.\..+\]$/u;
144
+ var DYNAMIC = /^\[.+\]$/u;
145
+ var split = (path) => path.split("/").filter(Boolean);
146
+ var parseSegment = (segment) => {
147
+ if (OPTIONAL_REST.test(segment)) {
148
+ return { kind: "rest", optional: true };
149
+ }
150
+ if (REST.test(segment)) {
151
+ return { kind: "rest", optional: false };
152
+ }
153
+ if (DYNAMIC.test(segment)) {
154
+ return { kind: "dynamic" };
155
+ }
156
+ return { kind: "static", value: segment };
157
+ };
158
+ var parse = (pattern) => ({
159
+ pattern,
160
+ segments: split(pattern).map(parseSegment)
161
+ });
162
+ var decode = (part) => {
163
+ try {
164
+ return decodeURIComponent(part);
165
+ } catch {
166
+ return part;
167
+ }
168
+ };
169
+ var matches = (segments, parts, at = 0, index = 0) => {
170
+ const segment = segments[at];
171
+ if (!segment) {
172
+ return index === parts.length;
173
+ }
174
+ if (segment.kind === "rest") {
175
+ return segment.optional || index < parts.length;
176
+ }
177
+ const part = parts[index];
178
+ if (part === void 0) {
179
+ return false;
180
+ }
181
+ if (segment.kind === "static" && segment.value !== decode(part)) {
182
+ return false;
183
+ }
184
+ return matches(segments, parts, at + 1, index + 1);
185
+ };
186
+ var RANK = { static: 0, dynamic: 1, rest: 2 };
187
+ var bySpecificity = (a, b) => {
188
+ const length = Math.max(a.segments.length, b.segments.length);
189
+ for (let index = 0; index < length; index += 1) {
190
+ const left = a.segments[index];
191
+ const right = b.segments[index];
192
+ if (!(left && right)) {
193
+ return left ? -1 : 1;
194
+ }
195
+ const difference = RANK[left.kind] - RANK[right.kind];
196
+ if (difference !== 0) {
197
+ return difference;
198
+ }
199
+ }
200
+ return 0;
201
+ };
202
+ var createMasker = (patterns) => {
203
+ const masks = patterns.map(parse).sort(bySpecificity);
204
+ return (href) => {
205
+ if (masks.length === 0) {
206
+ return href;
207
+ }
208
+ let url;
209
+ try {
210
+ url = new URL(href);
211
+ } catch {
212
+ return href;
213
+ }
214
+ const parts = split(url.pathname);
215
+ const mask = masks.find(({ segments }) => matches(segments, parts));
216
+ if (!mask) {
217
+ return href;
218
+ }
219
+ url.pathname = mask.pattern;
220
+ return url.href;
221
+ };
222
+ };
223
+
126
224
  // src/index.ts
127
225
  var LOG_PREFIX = "[pageflock]";
128
226
  var pageflockGlobal = () => globalThis;
@@ -131,8 +229,32 @@ var current;
131
229
  var log = (message, event) => {
132
230
  console.info(`${LOG_PREFIX} ${message}`, event);
133
231
  };
232
+ var masker;
233
+ var currentMasker = () => {
234
+ const patterns = current?.mask ?? [];
235
+ const key = patterns.join("\n");
236
+ if (masker?.key !== key) {
237
+ masker = { key, apply: createMasker(patterns) };
238
+ }
239
+ return masker.apply;
240
+ };
241
+ var applyMask = (event) => {
242
+ if (!event) {
243
+ return event;
244
+ }
245
+ const mask = currentMasker();
246
+ const url = mask(event.url);
247
+ const path = event.props?.path;
248
+ if (event.name === "404" && typeof path === "string") {
249
+ const masked = new URL(mask(new URL(path, url).href)).pathname;
250
+ return { ...event, url, props: { ...event.props, path: masked } };
251
+ }
252
+ return { ...event, url };
253
+ };
134
254
  var beforeSend = (event) => {
135
- const result = current?.beforeSend ? current.beforeSend(event) : event;
255
+ const result = applyMask(
256
+ current?.beforeSend ? current.beforeSend(event) : event
257
+ );
136
258
  if (current?.debug) {
137
259
  log(result ? event.name : `${event.name} (dropped)`, result ?? event);
138
260
  }
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  inject,
3
3
  track
4
- } from "./chunks/chunk-7JF7P3VW.js";
4
+ } from "./chunks/chunk-UXUNZ35R.js";
5
5
  export {
6
6
  inject,
7
7
  track
package/dist/next.js CHANGED
@@ -1,10 +1,10 @@
1
1
  "use client";
2
2
  import {
3
3
  Analytics
4
- } from "./chunks/chunk-4ZAVKYVM.js";
4
+ } from "./chunks/chunk-5NKMGFKF.js";
5
5
  import {
6
6
  track
7
- } from "./chunks/chunk-7JF7P3VW.js";
7
+ } from "./chunks/chunk-UXUNZ35R.js";
8
8
  export {
9
9
  Analytics,
10
10
  track
package/dist/react.js CHANGED
@@ -1,10 +1,10 @@
1
1
  "use client";
2
2
  import {
3
3
  Analytics
4
- } from "./chunks/chunk-4ZAVKYVM.js";
4
+ } from "./chunks/chunk-5NKMGFKF.js";
5
5
  import {
6
6
  track
7
- } from "./chunks/chunk-7JF7P3VW.js";
7
+ } from "./chunks/chunk-UXUNZ35R.js";
8
8
  export {
9
9
  Analytics,
10
10
  track
@@ -9,8 +9,12 @@ export interface AnalyticsEvent {
9
9
  export interface AnalyticsOptions {
10
10
  /** The site ID from the Pageflock dashboard. */
11
11
  site: string;
12
- /** Full URL of the collect endpoint, for example https://pageflock.example.com/api/e. */
13
- endpoint: string;
12
+ /**
13
+ * Full URL of the collect endpoint. Leave it out to send to Pageflock's
14
+ * hosted ingest (https://e.pageflock.com/api/e); set it when you self-host,
15
+ * for example https://pageflock.example.com/api/e.
16
+ */
17
+ endpoint?: string;
14
18
  /** Also track outbound link clicks, file downloads and 404 pages. */
15
19
  autoEvents?: boolean;
16
20
  /** Count changes of `location.hash` as page views. */
@@ -20,12 +24,19 @@ export interface AnalyticsOptions {
20
24
  * return null to drop it. Use it to strip tokens from URLs or skip pages.
21
25
  */
22
26
  beforeSend?: (event: AnalyticsEvent) => AnalyticsEvent | null;
27
+ /**
28
+ * Route patterns, such as `/projects/[id]` or `/docs/[...slug]`, reported
29
+ * in place of the paths they match, so ids, slugs and names in URLs never
30
+ * leave the browser. The most specific match wins.
31
+ * Applied to every event after `beforeSend`.
32
+ */
33
+ mask?: readonly string[];
23
34
  /** Log every event to the console, including on localhost where nothing is sent. */
24
35
  debug?: boolean;
25
36
  }
26
37
  /**
27
38
  * Starts tracking and records the first page view. Safe to call more than
28
- * once: later calls only update `beforeSend` and `debug`. Does nothing on the
39
+ * once: later calls only update `beforeSend`, `mask` and `debug`. Does nothing on the
29
40
  * server, or when the Pageflock script tag is already on the page.
30
41
  */
31
42
  export declare const inject: (options: AnalyticsOptions) => void;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * URL masks: route patterns such as `/projects/[id]` that stand in for the
3
+ * real path, so ids, slugs and names in URLs never leave the browser.
4
+ *
5
+ * Segments in a pattern are a literal (`settings`), one dynamic segment
6
+ * (`[id]`), one or more (`[...path]`) or zero or more (`[[...path]]`), the
7
+ * same syntax as file-based routers.
8
+ */
9
+ /**
10
+ * Builds a function that turns a full URL into the URL to report: the first
11
+ * matching pattern replaces the path, and the query and fragment are kept.
12
+ * A URL that matches no pattern is returned unchanged.
13
+ */
14
+ export declare const createMasker: (patterns: readonly string[]) => (href: string) => string;
@@ -3,7 +3,7 @@
3
3
  * layout (`app/layout.tsx`) or `pages/_app.tsx`:
4
4
  *
5
5
  * import { Analytics } from "@pageflock/analytics/next";
6
- * <Analytics site="SITE_ID" endpoint="https://pageflock.example.com/api/e" />
6
+ * <Analytics site="SITE_ID" />
7
7
  *
8
8
  * Client navigations go through `history.pushState`, which the tracker
9
9
  * already follows, so no router hooks are needed.
@@ -8,27 +8,23 @@ export declare const Analytics: import("vue").DefineComponent<import("vue").Extr
8
8
  type: StringConstructor;
9
9
  required: true;
10
10
  };
11
- endpoint: {
12
- type: StringConstructor;
13
- required: true;
14
- };
11
+ endpoint: StringConstructor;
15
12
  autoEvents: BooleanConstructor;
16
13
  hashRouting: BooleanConstructor;
17
14
  debug: BooleanConstructor;
18
15
  beforeSend: PropType<AnalyticsOptions["beforeSend"]>;
16
+ mask: PropType<AnalyticsOptions["mask"]>;
19
17
  }>, () => null, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<import("vue").ExtractPropTypes<{
20
18
  site: {
21
19
  type: StringConstructor;
22
20
  required: true;
23
21
  };
24
- endpoint: {
25
- type: StringConstructor;
26
- required: true;
27
- };
22
+ endpoint: StringConstructor;
28
23
  autoEvents: BooleanConstructor;
29
24
  hashRouting: BooleanConstructor;
30
25
  debug: BooleanConstructor;
31
26
  beforeSend: PropType<AnalyticsOptions["beforeSend"]>;
27
+ mask: PropType<AnalyticsOptions["mask"]>;
32
28
  }>> & Readonly<{}>, {
33
29
  autoEvents: boolean;
34
30
  hashRouting: boolean;
package/dist/vue.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  inject,
3
3
  track
4
- } from "./chunks/chunk-7JF7P3VW.js";
4
+ } from "./chunks/chunk-UXUNZ35R.js";
5
5
 
6
6
  // src/vue.ts
7
7
  import { defineComponent, onMounted } from "vue";
@@ -9,11 +9,12 @@ var Analytics = defineComponent({
9
9
  name: "PageflockAnalytics",
10
10
  props: {
11
11
  site: { type: String, required: true },
12
- endpoint: { type: String, required: true },
12
+ endpoint: String,
13
13
  autoEvents: Boolean,
14
14
  hashRouting: Boolean,
15
15
  debug: Boolean,
16
- beforeSend: Function
16
+ beforeSend: Function,
17
+ mask: Array
17
18
  },
18
19
  setup(props) {
19
20
  onMounted(() => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pageflock/analytics",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Pageflock analytics for React, Next.js, Vue and any bundled site: cookieless, under 2 KB.",
5
5
  "keywords": [
6
6
  "analytics",
@@ -59,7 +59,7 @@
59
59
  "typescript": "7.0.2",
60
60
  "vitest": "5.1.0",
61
61
  "vue": "3.5.45",
62
- "@pageflock/tracker": "0.1.0"
62
+ "@pageflock/tracker": "0.1.2"
63
63
  },
64
64
  "peerDependencies": {
65
65
  "react": ">=18",