@tbdhdev/beacon-sdk 0.0.0-stage → 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.
@@ -0,0 +1,300 @@
1
+ // src/core.ts
2
+ const IGNORE_KEY = "beacon.ignore";
3
+ const DOWNLOAD_RE = /\.(pdf|zip|gz|tgz|rar|7z|dmg|pkg|exe|msi|deb|rpm|apk|csv|xlsx?|docx?|pptx?|txt|mp3|mp4|mov|avi|wav|iso|epub)$/i;
4
+ const CAMPAIGN_PARAM_RE = /^(utm_\w+|gclid|fbclid|msclkid)$/i;
5
+ function pageKey(url) {
6
+ const params = new URLSearchParams(url.search);
7
+ for (const name of [...params.keys()]) if (CAMPAIGN_PARAM_RE.test(name)) params.delete(name);
8
+ return `${url.pathname}?${params}`;
9
+ }
10
+ /** Starts tracking in the browser. Call once per page load: it patches history and adds listeners. */
11
+ function createBeacon(config) {
12
+ const d = document;
13
+ const loc = location;
14
+ const website = config.websiteId;
15
+ const endpoint = new URL(config.endpoint ?? "/x/e", loc.href).href;
16
+ let ignored = false;
17
+ try {
18
+ const flag = /beacon-ignore=(true|false)/.exec(loc.hash)?.[1];
19
+ if (flag === "true") localStorage.setItem(IGNORE_KEY, "1");
20
+ else if (flag === "false") localStorage.removeItem(IGNORE_KEY);
21
+ ignored = localStorage.getItem(IGNORE_KEY) === "1";
22
+ } catch {}
23
+ if (ignored) {
24
+ const noop = () => void 0;
25
+ return {
26
+ track: noop,
27
+ identify: noop,
28
+ page: noop
29
+ };
30
+ }
31
+ let distinctId;
32
+ let lastPage;
33
+ let lastPath;
34
+ let lastUrl;
35
+ let landingUrl;
36
+ let referrer = d.referrer;
37
+ let lastTitle = "";
38
+ let views = 0;
39
+ const currentUrl = () => {
40
+ if (!config.hashRouting) return loc.href;
41
+ const route = /^#!?\//.test(loc.hash) ? loc.hash.replace(/^#!?[/\\]+/, "") : "";
42
+ const base = loc.pathname.replace(/\/index\.html?$/, "/").replace(/\/?$/, "/");
43
+ const url = new URL(loc.origin + base + route);
44
+ const own = new URLSearchParams(url.search);
45
+ for (const [name, value] of new URLSearchParams(loc.search)) if (!own.has(name)) url.searchParams.append(name, value);
46
+ return url.href;
47
+ };
48
+ const send = (type, extra = {}) => {
49
+ const body = JSON.stringify({
50
+ website,
51
+ type,
52
+ url: currentUrl(),
53
+ title: d.title,
54
+ screen: `${screen.width}x${screen.height}`,
55
+ language: navigator.language,
56
+ id: distinctId,
57
+ ...extra
58
+ });
59
+ const transmit = () => {
60
+ if (typeof fetch === "function") fetch(endpoint, {
61
+ method: "POST",
62
+ body,
63
+ keepalive: true,
64
+ credentials: "omit"
65
+ }).catch(() => void 0);
66
+ else navigator.sendBeacon?.(endpoint, body);
67
+ };
68
+ if (d.prerendering) d.addEventListener("prerenderingchange", transmit, { once: true });
69
+ else transmit();
70
+ };
71
+ const page = (path) => {
72
+ const url = new URL(path ?? currentUrl(), loc.href);
73
+ const key = pageKey(url);
74
+ if (key === lastPage) return;
75
+ const view = ++views;
76
+ lastPage = key;
77
+ lastPath = url.pathname;
78
+ lastUrl = url.href;
79
+ landingUrl ?? (landingUrl = url.href);
80
+ const extra = {
81
+ url: url.href,
82
+ referrer
83
+ };
84
+ const route = () => new URL(currentUrl()).pathname;
85
+ const at = route();
86
+ const sendPageview = () => {
87
+ if (view !== views || route() !== at) {
88
+ send("pageview", {
89
+ ...extra,
90
+ title: ""
91
+ });
92
+ return;
93
+ }
94
+ lastTitle = d.title;
95
+ send("pageview", extra);
96
+ };
97
+ referrer = "";
98
+ if (d.title || !lastTitle) sendPageview();
99
+ else onTitle(sendPageview);
100
+ };
101
+ const api = {
102
+ track: (name, props) => send("event", {
103
+ name,
104
+ props
105
+ }),
106
+ identify: (id, traits) => {
107
+ distinctId = id;
108
+ send("identify", {
109
+ name: "identify",
110
+ props: traits
111
+ });
112
+ },
113
+ page
114
+ };
115
+ if (config.autoPageviews ?? true) {
116
+ page();
117
+ const later = () => setTimeout(() => page(), 0);
118
+ const replaced = (href) => {
119
+ const url = new URL(href);
120
+ if (url.pathname !== lastPath) {
121
+ page(href);
122
+ return;
123
+ }
124
+ lastPage = pageKey(url);
125
+ lastUrl = href;
126
+ };
127
+ let calls = 0;
128
+ for (const method of ["pushState", "replaceState"]) {
129
+ const original = history[method].bind(history);
130
+ history[method] = (...args) => {
131
+ original(...args);
132
+ const href = currentUrl();
133
+ const call = ++calls;
134
+ setTimeout(() => {
135
+ if (method === "pushState") page();
136
+ else if (call === calls) replaced(href);
137
+ }, 0);
138
+ };
139
+ }
140
+ addEventListener("popstate", later);
141
+ if (config.hashRouting) addEventListener("hashchange", later);
142
+ }
143
+ addEventListener("pageshow", (event) => {
144
+ if (event.persisted && lastUrl) {
145
+ const url = lastUrl;
146
+ lastPage = landingUrl = void 0;
147
+ page(url);
148
+ }
149
+ });
150
+ const onClick = (event) => {
151
+ if (event.type === "auxclick" && event.button !== 1) return;
152
+ const elements = event.composedPath().filter((node) => node instanceof Element);
153
+ const tagged = event.type === "click" ? elements.find((el) => el.getAttribute("data-beacon-event")) : void 0;
154
+ if (tagged) {
155
+ const props = Object.fromEntries(Array.from(tagged.attributes).filter(({ name }) => name.startsWith("data-beacon-prop-")).map(({ name, value }) => [name.slice(17), value]));
156
+ api.track(tagged.getAttribute("data-beacon-event") ?? "", props);
157
+ }
158
+ const link = elements.find((el) => el instanceof HTMLAnchorElement);
159
+ if (!link?.href || !/^https?:$/.test(link.protocol)) return;
160
+ const isDownload = DOWNLOAD_RE.test(link.pathname) || link.hasAttribute("download") && link.host === loc.host;
161
+ if (config.downloads && isDownload) send("download", {
162
+ name: "download",
163
+ props: { url: link.href }
164
+ });
165
+ else if (config.outbound && link.host !== loc.host) send("outbound", {
166
+ name: "outbound",
167
+ props: { url: link.href }
168
+ });
169
+ };
170
+ d.addEventListener("click", onClick, true);
171
+ d.addEventListener("auxclick", onClick, true);
172
+ if (config.webVitals) observeVitals((vitals, load) => send("vitals", {
173
+ url: landingUrl ?? currentUrl(),
174
+ props: vitals,
175
+ load
176
+ }));
177
+ return api;
178
+ }
179
+ function onTitle(callback) {
180
+ const done = () => {
181
+ observer.disconnect();
182
+ clearTimeout(timer);
183
+ callback();
184
+ };
185
+ const observer = new MutationObserver(() => {
186
+ if (document.title) done();
187
+ });
188
+ const timer = setTimeout(done, 1e3);
189
+ observer.observe(document.documentElement, {
190
+ childList: true,
191
+ subtree: true,
192
+ characterData: true
193
+ });
194
+ }
195
+ function observeVitals(report) {
196
+ const newLoad = () => Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(8)), (byte) => byte.toString(16).padStart(2, "0")).join("");
197
+ let load = newLoad();
198
+ let vitals = {};
199
+ let sent = {};
200
+ const flushes = [];
201
+ const observe = (type, callback, extra = {}) => {
202
+ try {
203
+ const observer = new PerformanceObserver((list) => callback(list.getEntries()));
204
+ observer.observe({
205
+ type,
206
+ buffered: true,
207
+ ...extra
208
+ });
209
+ flushes.push(() => callback(observer.takeRecords()));
210
+ } catch {}
211
+ };
212
+ const navigation = performance.getEntriesByType("navigation")[0];
213
+ const activation = () => navigation?.activationStart ?? 0;
214
+ const prerendering = document.prerendering;
215
+ let firstHidden = prerendering ? 1e400 : performance.getEntriesByType("visibility-state").find((entry) => entry.name === "hidden" && entry.startTime >= activation())?.startTime ?? (document.visibilityState === "hidden" ? 0 : 1e400);
216
+ let lcpStart;
217
+ observe("largest-contentful-paint", (entries) => {
218
+ for (const entry of entries) if (entry.startTime < firstHidden) lcpStart = entry.startTime;
219
+ });
220
+ const shifts = globalThis.PerformanceObserver?.supportedEntryTypes?.includes("layout-shift");
221
+ if (shifts) vitals.CLS = 0;
222
+ let windowValue = 0;
223
+ let windowStart = 0;
224
+ let previous = 0;
225
+ observe("layout-shift", (entries) => {
226
+ for (const entry of entries) {
227
+ if (entry.hadRecentInput) continue;
228
+ const sameWindow = windowValue > 0 && entry.startTime - previous < 1e3 && entry.startTime - windowStart < 5e3;
229
+ windowValue = sameWindow ? windowValue + entry.value : entry.value;
230
+ windowStart = sameWindow ? windowStart : entry.startTime;
231
+ previous = entry.startTime;
232
+ vitals.CLS = Math.max(vitals.CLS ?? 0, windowValue);
233
+ }
234
+ });
235
+ observe("event", (entries) => {
236
+ for (const entry of entries) if (entry.interactionId) vitals.INP = Math.max(vitals.INP ?? 0, entry.duration);
237
+ }, { durationThreshold: 40 });
238
+ observe("first-input", (entries) => {
239
+ for (const entry of entries) vitals.INP = Math.max(vitals.INP ?? 0, entry.duration);
240
+ });
241
+ const ttfb = () => {
242
+ if (navigation && navigation.responseStart > 0 && navigation.responseStart <= performance.now()) vitals.TTFB = Math.max(navigation.responseStart - activation(), 0);
243
+ };
244
+ if (prerendering) document.addEventListener("prerenderingchange", ttfb, { once: true });
245
+ else ttfb();
246
+ addEventListener("pageshow", (event) => {
247
+ if (event.persisted) {
248
+ load = newLoad();
249
+ vitals = shifts ? { CLS: 0 } : {};
250
+ sent = {};
251
+ windowValue = 0;
252
+ lcpStart = void 0;
253
+ }
254
+ });
255
+ const onHide = (event) => {
256
+ if (event.type !== "pagehide" && document.visibilityState !== "hidden") return;
257
+ firstHidden = Math.min(firstHidden, performance.now());
258
+ for (const flush of flushes) flush();
259
+ if (lcpStart !== void 0) vitals.LCP = Math.max(lcpStart - activation(), 0);
260
+ const changed = Object.fromEntries(Object.entries(vitals).filter(([name, value]) => sent[name] !== value));
261
+ if (Object.keys(changed).length > 0) {
262
+ Object.assign(sent, changed);
263
+ report(changed, load);
264
+ }
265
+ };
266
+ addEventListener("visibilitychange", onHide);
267
+ addEventListener("pagehide", onHide);
268
+ }
269
+ // src/index.ts
270
+ let beacon;
271
+ const queue = [];
272
+ const isBrowser = () => typeof window !== "undefined" && typeof document !== "undefined";
273
+ function call(method, args) {
274
+ if (beacon) try {
275
+ beacon[method](...args);
276
+ } catch {}
277
+ else if (isBrowser() && queue.length < 100) queue.push([method, args]);
278
+ }
279
+ /** Starts Beacon. Safe to call during SSR (no-op) and more than once (later calls are ignored). */
280
+ function init(config) {
281
+ if (beacon || !isBrowser() || !config.websiteId) return;
282
+ try {
283
+ beacon = createBeacon(config);
284
+ } catch {
285
+ return;
286
+ }
287
+ for (const [method, args] of queue.splice(0)) call(method, args);
288
+ }
289
+ function track(name, props) {
290
+ call("track", [name, props]);
291
+ }
292
+ function identify(id, traits) {
293
+ call("identify", [id, traits]);
294
+ }
295
+ function page(url) {
296
+ call("page", [url]);
297
+ }
298
+ export { track as i, init as n, page as r, identify as t };
299
+
300
+ //# sourceMappingURL=src-DaAShSXp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-DaAShSXp.js","names":[],"sources":["../src/core.ts","../src/index.ts"],"sourcesContent":["// Beacon browser core, shared by `@tbdhdev/beacon-sdk` and the zero-install script. Cookieless: never\n// writes storage except the operator's own opt-out flag, set with `#beacon-ignore=true`.\nexport type BeaconProps = Record<string, string | number | boolean>;\n\nexport interface BeaconApi {\n /** Track a custom event, e.g. `track(\"signup_clicked\", { plan: \"pro\" })`. */\n track: (name: string, props?: BeaconProps) => void;\n /** Opt-in identification for your own logged-in apps. Kept in memory only. */\n identify: (id: string, traits?: BeaconProps) => void;\n /** Record a pageview for `url` (default: the current location). Repeats of the last page are ignored. */\n page: (url?: string) => void;\n}\n\nexport interface BeaconConfig {\n /** Website id from the Beacon dashboard. */\n websiteId: string;\n /**\n * Event endpoint: your ingest origin + prefix + event path (Settings → Tracking), e.g.\n * `https://beacon.example.com/x/e`. Relative URLs resolve against the page. Default `/x/e`.\n */\n endpoint?: string;\n /**\n * Record the first pageview and history navigations (pushState, replaceState to another path,\n * back/forward). Set `false` to call `page()` from your router instead. Default `true`.\n */\n autoPageviews?: boolean;\n /**\n * The app routes in the URL hash (`/#/pricing`, e.g. Vue's `createWebHashHistory` or React\n * Router's `HashRouter`): record the hash route as the page path. Default `false`.\n */\n hashRouting?: boolean;\n /** Track clicks on links to other hosts. */\n outbound?: boolean;\n /** Track clicks on file downloads (pdf, zip, csv, ...). */\n downloads?: boolean;\n /** Send LCP, CLS, INP and TTFB when the page is hidden. */\n webVitals?: boolean;\n}\n\ninterface LayoutShift extends PerformanceEntry {\n value: number;\n hadRecentInput: boolean;\n}\n\ninterface EventTiming extends PerformanceEntry {\n interactionId?: number;\n}\n\nconst IGNORE_KEY = \"beacon.ignore\";\nconst DOWNLOAD_RE =\n /\\.(pdf|zip|gz|tgz|rar|7z|dmg|pkg|exe|msi|deb|rpm|apk|csv|xlsx?|docx?|pptx?|txt|mp3|mp4|mov|avi|wav|iso|epub)$/i;\n// Campaign and click-id params that sites strip after landing; removing them is not a new page.\nconst CAMPAIGN_PARAM_RE = /^(utm_\\w+|gclid|fbclid|msclkid)$/i;\n\n// Identifies a page for deduplication: path and query, minus campaign params.\nfunction pageKey(url: URL) {\n const params = new URLSearchParams(url.search);\n\n for (const name of [...params.keys()]) {\n if (CAMPAIGN_PARAM_RE.test(name)) {\n params.delete(name);\n }\n }\n\n return `${url.pathname}?${params}`;\n}\n\n/** Starts tracking in the browser. Call once per page load: it patches history and adds listeners. */\nexport function createBeacon(config: BeaconConfig): BeaconApi {\n const d = document;\n const loc = location;\n const website = config.websiteId;\n const endpoint = new URL(config.endpoint ?? \"/x/e\", loc.href).href;\n let ignored = false;\n\n try {\n const flag = /beacon-ignore=(true|false)/.exec(loc.hash)?.[1];\n\n if (flag === \"true\") {\n localStorage.setItem(IGNORE_KEY, \"1\");\n } else if (flag === \"false\") {\n localStorage.removeItem(IGNORE_KEY);\n }\n\n ignored = localStorage.getItem(IGNORE_KEY) === \"1\";\n } catch {\n // Storage blocked: tracking stays enabled.\n }\n\n // Opted out: no history patches, listeners or observers either.\n if (ignored) {\n const noop = () => undefined;\n\n return { track: noop, identify: noop, page: noop };\n }\n\n let distinctId: string | undefined;\n // The last pageview: its dedupe key, path (for replaceState) and URL (for back/forward restores).\n let lastPage: string | undefined;\n let lastPath: string | undefined;\n let lastUrl: string | undefined;\n // The first pageview's URL, which web vitals (a page-load measurement) are filed under.\n let landingUrl: string | undefined;\n let referrer = d.referrer;\n let lastTitle = \"\";\n // Counts pageviews, so one still waiting for its title can tell a newer page has started.\n let views = 0;\n\n // With hash routing, `/app#/pricing?plan=pro` and `/app/index.html#/pricing?plan=pro` are the\n // page `/app/pricing?plan=pro`, and `/app`, `/app#/` and `/app/#section` are its root `/app/`.\n const currentUrl = () => {\n if (!config.hashRouting) {\n return loc.href;\n }\n\n // Leading slashes (and backslashes, which URLs read as slashes) are not part of the route.\n const route = /^#!?\\//.test(loc.hash)\n ? loc.hash.replace(/^#!?[/\\\\]+/, \"\")\n : \"\";\n const base = loc.pathname\n .replace(/\\/index\\.html?$/, \"/\")\n .replace(/\\/?$/, \"/\");\n // An absolute URL, so neither `#/\\evil.com` nor a `//evil.com/` path can change the host.\n const url = new URL(loc.origin + base + route);\n const own = new URLSearchParams(url.search);\n\n // The real query (where UTM tags usually are) still applies; the route's own params win.\n for (const [name, value] of new URLSearchParams(loc.search)) {\n if (!own.has(name)) {\n url.searchParams.append(name, value);\n }\n }\n\n return url.href;\n };\n\n const send = (type: string, extra: Record<string, unknown> = {}) => {\n const body = JSON.stringify({\n website,\n type,\n url: currentUrl(),\n title: d.title,\n screen: `${screen.width}x${screen.height}`,\n language: navigator.language,\n id: distinctId,\n ...extra,\n });\n // A cors-mode fetch always sends the page's real Origin, which ingest checks; sendBeacon sends\n // \"Origin: null\" under no-referrer/same-origin referrer policies, so it is only a fallback.\n const transmit = () => {\n if (typeof fetch === \"function\") {\n fetch(endpoint, {\n method: \"POST\",\n body,\n keepalive: true,\n credentials: \"omit\",\n }).catch(() => undefined);\n } else {\n navigator.sendBeacon?.(endpoint, body);\n }\n };\n\n // A prerendered page may never be shown: hold its events until the visitor opens it.\n if ((d as Document & { prerendering?: boolean }).prerendering) {\n d.addEventListener(\"prerenderingchange\", transmit, { once: true });\n } else {\n transmit();\n }\n };\n\n const page = (path?: string) => {\n const url = new URL(path ?? currentUrl(), loc.href);\n const key = pageKey(url);\n\n if (key === lastPage) {\n return;\n }\n\n const view = ++views;\n\n lastPage = key;\n lastPath = url.pathname;\n lastUrl = url.href;\n landingUrl ??= url.href;\n\n const extra = { url: url.href, referrer };\n const route = () => new URL(currentUrl()).pathname;\n const at = route();\n const sendPageview = () => {\n // Waited for a title, but a newer page came first (another page() call, or the location\n // moved on before its own page() call): the title now is that page's.\n if (view !== views || route() !== at) {\n send(\"pageview\", { ...extra, title: \"\" });\n\n return;\n }\n\n lastTitle = d.title;\n send(\"pageview\", extra);\n };\n\n referrer = \"\";\n\n // Next.js empties <title> on client navigation and streams the new one in a moment later.\n if (d.title || !lastTitle) {\n sendPageview();\n } else {\n onTitle(sendPageview);\n }\n };\n\n const api: BeaconApi = {\n track: (name, props) => send(\"event\", { name, props }),\n identify: (id, traits) => {\n distinctId = id;\n send(\"identify\", { name: \"identify\", props: traits });\n },\n page,\n };\n\n if (config.autoPageviews ?? true) {\n page();\n\n // Deferred so the app can render the new page (and its <title>) first.\n const later = () => setTimeout(() => page(), 0);\n // replaceState on the same path (stripping UTM tags, syncing filters) updates the URL, not the page.\n const replaced = (href: string) => {\n const url = new URL(href);\n\n if (url.pathname !== lastPath) {\n page(href);\n\n return;\n }\n\n lastPage = pageKey(url);\n lastUrl = href;\n };\n\n // Counts history calls, so a replaceState can tell another one came after it.\n let calls = 0;\n\n for (const method of [\"pushState\", \"replaceState\"] as const) {\n const original = history[method].bind(history);\n\n history[method] = (...args: Parameters<History[\"pushState\"]>) => {\n original(...args);\n // Judge a replaceState by the URL it set: Vue Router's push() replaces the current entry\n // and then pushes the new one in the same tick, so location has moved on by the timeout.\n const href = currentUrl();\n const call = ++calls;\n\n setTimeout(() => {\n if (method === \"pushState\") {\n page();\n } else if (call === calls) {\n // A replaceState followed by another history call (a redirect chain) was never shown.\n replaced(href);\n }\n }, 0);\n };\n }\n\n addEventListener(\"popstate\", later);\n\n if (config.hashRouting) {\n addEventListener(\"hashchange\", later);\n }\n }\n\n // Back/forward cache restores show the page again without reloading it, and no router runs.\n addEventListener(\"pageshow\", (event) => {\n if (event.persisted && lastUrl) {\n const url = lastUrl;\n\n // A new page load, which its web vitals are filed under.\n lastPage = landingUrl = undefined;\n page(url);\n }\n });\n\n // Left clicks, and middle clicks (auxclick) that open a link in a new tab.\n const onClick = (event: MouseEvent) => {\n if (event.type === \"auxclick\" && event.button !== 1) {\n return;\n }\n\n // composedPath() reaches into open shadow roots, where event.target stops at the host.\n const elements = event\n .composedPath()\n .filter((node): node is Element => node instanceof Element);\n const tagged =\n event.type === \"click\"\n ? elements.find((el) => el.getAttribute(\"data-beacon-event\"))\n : undefined;\n\n if (tagged) {\n // fromEntries keeps a prop named `__proto__` as a prop.\n const props: BeaconProps = Object.fromEntries(\n Array.from(tagged.attributes)\n .filter(({ name }) => name.startsWith(\"data-beacon-prop-\"))\n .map(({ name, value }) => [name.slice(17), value]),\n );\n\n api.track(tagged.getAttribute(\"data-beacon-event\") ?? \"\", props);\n }\n\n const link = elements.find(\n (el): el is HTMLAnchorElement => el instanceof HTMLAnchorElement,\n );\n\n if (!link?.href || !/^https?:$/.test(link.protocol)) {\n return;\n }\n\n // Browsers ignore `download` on cross-origin links and navigate instead.\n const isDownload =\n DOWNLOAD_RE.test(link.pathname) ||\n (link.hasAttribute(\"download\") && link.host === loc.host);\n\n if (config.downloads && isDownload) {\n send(\"download\", { name: \"download\", props: { url: link.href } });\n } else if (config.outbound && link.host !== loc.host) {\n send(\"outbound\", { name: \"outbound\", props: { url: link.href } });\n }\n };\n\n d.addEventListener(\"click\", onClick, true);\n d.addEventListener(\"auxclick\", onClick, true);\n\n if (config.webVitals) {\n // Vitals describe the page load, so they belong to the first page recorded (after any redirect\n // the router made before its first page() call), not the route open when the tab is hidden.\n observeVitals((vitals, load) =>\n send(\"vitals\", { url: landingUrl ?? currentUrl(), props: vitals, load }),\n );\n }\n\n return api;\n}\n\n// Calls back once document.title is set, or after 1s.\nfunction onTitle(callback: () => void) {\n const done = () => {\n observer.disconnect();\n clearTimeout(timer);\n callback();\n };\n\n const observer = new MutationObserver(() => {\n if (document.title) {\n done();\n }\n });\n const timer = setTimeout(done, 1000);\n\n observer.observe(document.documentElement, {\n childList: true,\n subtree: true,\n characterData: true,\n });\n}\n\nfunction observeVitals(\n report: (vitals: Record<string, number>, load: string) => void,\n) {\n // Every report from one page load carries the same id, so the dashboard counts it once.\n const newLoad = () =>\n Array.from(crypto.getRandomValues(new Uint8Array(8)), (byte) =>\n byte.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n let load = newLoad();\n let vitals: Record<string, number> = {};\n // What the last report sent, per metric.\n let sent: Record<string, number> = {};\n // Entries the browser has queued but not yet delivered, pulled in just before reporting.\n const flushes: (() => void)[] = [];\n const observe = (\n type: string,\n callback: (entries: PerformanceEntry[]) => void,\n extra: Record<string, unknown> = {},\n ) => {\n try {\n const observer = new PerformanceObserver((list) =>\n callback(list.getEntries()),\n );\n\n observer.observe({ type, buffered: true, ...extra });\n flushes.push(() => callback(observer.takeRecords()));\n } catch {\n // Entry type unsupported in this browser.\n }\n };\n\n const navigation = performance.getEntriesByType(\"navigation\")[0] as\n | (PerformanceNavigationTiming & { activationStart?: number })\n | undefined;\n // A prerendered page loads before the visitor opens it: LCP and TTFB count from activation,\n // whose time the entry only has once the page is shown.\n const activation = () => navigation?.activationStart ?? 0;\n const prerendering = (document as Document & { prerendering?: boolean })\n .prerendering;\n\n // LCP only counts paints before the page was first hidden (as in the web-vitals library): a page\n // opened in a background tab, or one the visitor comes back to, would report the wait as LCP.\n // The browser's visibility history (Chromium) also covers a hide before Beacon started, e.g. before\n // hydration. A prerendered page is hidden until it is shown, which is not the visitor leaving.\n let firstHidden = prerendering\n ? Infinity\n : (performance\n .getEntriesByType(\"visibility-state\")\n .find(\n (entry) => entry.name === \"hidden\" && entry.startTime >= activation(),\n )?.startTime ?? (document.visibilityState === \"hidden\" ? 0 : Infinity));\n\n // Kept raw: a paint while prerendering comes before activationStart is known, so the report\n // subtracts it instead.\n let lcpStart: number | undefined;\n\n observe(\"largest-contentful-paint\", (entries) => {\n for (const entry of entries) {\n if (entry.startTime < firstHidden) {\n lcpStart = entry.startTime;\n }\n }\n });\n\n // A page that never shifts has a CLS of 0, which must be reported too, but only where layout\n // shifts can be observed at all (not in Safari or Firefox).\n const shifts =\n globalThis.PerformanceObserver?.supportedEntryTypes?.includes(\n \"layout-shift\",\n );\n\n if (shifts) {\n vitals.CLS = 0;\n }\n\n // CLS: largest session window (shifts < 1s apart, window < 5s).\n let windowValue = 0;\n let windowStart = 0;\n let previous = 0;\n\n observe(\"layout-shift\", (entries) => {\n for (const entry of entries as LayoutShift[]) {\n if (entry.hadRecentInput) {\n continue;\n }\n\n const sameWindow =\n windowValue > 0 &&\n entry.startTime - previous < 1000 &&\n entry.startTime - windowStart < 5000;\n\n windowValue = sameWindow ? windowValue + entry.value : entry.value;\n windowStart = sameWindow ? windowStart : entry.startTime;\n previous = entry.startTime;\n vitals.CLS = Math.max(vitals.CLS ?? 0, windowValue);\n }\n });\n\n // shortcut: INP is the slowest interaction, not the p98; matches web-vitals below ~50 interactions per page.\n // getWebVitals keeps each page load's largest value, so a p98 (which can drop) needs that query changed too.\n observe(\n \"event\",\n (entries) => {\n for (const entry of entries as EventTiming[]) {\n if (entry.interactionId) {\n vitals.INP = Math.max(vitals.INP ?? 0, entry.duration);\n }\n }\n },\n { durationThreshold: 40 },\n );\n // \"event\" entries start at 40ms, so a page whose interactions are all fast would report no INP.\n // The first input is always reported, whatever its duration (as the web-vitals library does).\n observe(\"first-input\", (entries) => {\n for (const entry of entries) {\n vitals.INP = Math.max(vitals.INP ?? 0, entry.duration);\n }\n });\n\n // 0 (or a time still to come) when the browser has no real value, e.g. for some cached loads.\n const ttfb = () => {\n if (\n navigation &&\n navigation.responseStart > 0 &&\n navigation.responseStart <= performance.now()\n ) {\n vitals.TTFB = Math.max(navigation.responseStart - activation(), 0);\n }\n };\n\n if (prerendering) {\n document.addEventListener(\"prerenderingchange\", ttfb, { once: true });\n } else {\n ttfb();\n }\n\n // A back/forward cache restore is a new page load without a network load or first paint: it\n // gets its own id, and CLS and INP start over.\n addEventListener(\"pageshow\", (event) => {\n if (event.persisted) {\n load = newLoad();\n vitals = shifts ? { CLS: 0 } : {};\n sent = {};\n windowValue = 0;\n lcpStart = undefined;\n }\n });\n\n // CLS and INP keep growing while the page stays open, so each hide reports what changed since the\n // last report. The visitor may never come back, so waiting for a final value would lose it.\n // visibilitychange bubbles up from document; pagehide covers browsers that skip it on unload.\n const onHide = (event: Event) => {\n if (event.type !== \"pagehide\" && document.visibilityState !== \"hidden\") {\n return;\n }\n\n firstHidden = Math.min(firstHidden, performance.now());\n\n for (const flush of flushes) {\n flush();\n }\n\n if (lcpStart !== undefined) {\n vitals.LCP = Math.max(lcpStart - activation(), 0);\n }\n\n const changed = Object.fromEntries(\n Object.entries(vitals).filter(([name, value]) => sent[name] !== value),\n );\n\n if (Object.keys(changed).length > 0) {\n Object.assign(sent, changed);\n report(changed, load);\n }\n };\n\n addEventListener(\"visibilitychange\", onHide);\n addEventListener(\"pagehide\", onHide);\n}\n","import {\n type BeaconApi,\n type BeaconConfig,\n type BeaconProps,\n createBeacon,\n} from \"./core.js\";\n\nexport type { BeaconApi, BeaconConfig, BeaconProps };\n\nlet beacon: BeaconApi | undefined;\n// Calls made before init() (e.g. a child component's effect) run right after it. Capped, for an\n// app that never calls init() (e.g. no consent).\nconst queue: [keyof BeaconApi, unknown[]][] = [];\nconst isBrowser = () =>\n typeof window !== \"undefined\" && typeof document !== \"undefined\";\n\nfunction call(method: keyof BeaconApi, args: unknown[]) {\n if (beacon) {\n try {\n (beacon[method] as (...a: unknown[]) => void)(...args);\n } catch {\n // Bad input from the app (an unparsable URL, props JSON can't encode): never break the page.\n }\n } else if (isBrowser() && queue.length < 100) {\n queue.push([method, args]);\n }\n}\n\n/** Starts Beacon. Safe to call during SSR (no-op) and more than once (later calls are ignored). */\nexport function init(config: BeaconConfig): void {\n // Without a website id every event would be refused, e.g. when its env var is missing.\n if (beacon || !isBrowser() || !config.websiteId) {\n return;\n }\n\n try {\n beacon = createBeacon(config);\n } catch {\n // A malformed endpoint: tracking stays off rather than breaking the page.\n return;\n }\n\n for (const [method, args] of queue.splice(0)) {\n call(method, args);\n }\n}\n\nexport function track(name: string, props?: BeaconProps): void {\n call(\"track\", [name, props]);\n}\n\nexport function identify(id: string, traits?: BeaconProps): void {\n call(\"identify\", [id, traits]);\n}\n\nexport function page(url?: string): void {\n call(\"page\", [url]);\n}\n"],"mappings":";AAgDA,MAAM,aAAa;AACnB,MAAM,cACJ;AAEF,MAAM,oBAAoB;AAG1B,SAAS,QAAQ,KAAU;CACzB,MAAM,SAAS,IAAI,gBAAgB,IAAI,MAAM;CAE7C,KAAK,MAAM,QAAQ,CAAC,GAAG,OAAO,KAAK,CAAC,GAClC,IAAI,kBAAkB,KAAK,IAAI,GAC7B,OAAO,OAAO,IAAI;CAItB,OAAO,GAAG,IAAI,SAAS,GAAG;AAC5B;;AAGA,SAAgB,aAAa,QAAiC;CAC5D,MAAM,IAAI;CACV,MAAM,MAAM;CACZ,MAAM,UAAU,OAAO;CACvB,MAAM,WAAW,IAAI,IAAI,OAAO,YAAY,QAAQ,IAAI,IAAI,CAAC,CAAC;CAC9D,IAAI,UAAU;CAEd,IAAI;EACF,MAAM,OAAO,6BAA6B,KAAK,IAAI,IAAI,CAAC,GAAG;EAE3D,IAAI,SAAS,QACX,aAAa,QAAQ,YAAY,GAAG;OAC/B,IAAI,SAAS,SAClB,aAAa,WAAW,UAAU;EAGpC,UAAU,aAAa,QAAQ,UAAU,MAAM;CACjD,QAAQ,CAER;CAGA,IAAI,SAAS;EACX,MAAM,aAAa,KAAA;EAEnB,OAAO;GAAE,OAAO;GAAM,UAAU;GAAM,MAAM;EAAK;CACnD;CAEA,IAAI;CAEJ,IAAI;CACJ,IAAI;CACJ,IAAI;CAEJ,IAAI;CACJ,IAAI,WAAW,EAAE;CACjB,IAAI,YAAY;CAEhB,IAAI,QAAQ;CAIZ,MAAM,mBAAmB;EACvB,IAAI,CAAC,OAAO,aACV,OA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-0,0 +1,7 @@
1
+ import { o as BeaconConfig } from "./index-t-jJl5-d.js";
2
+ /**
3
+ * Starts Beacon in the browser and records a pageview after the first render and every
4
+ * navigation. Call it from the root `+layout.svelte` script: like `afterNavigate`, it must run
5
+ * during component initialization. Does nothing during SSR.
6
+ */
7
+ export declare function initBeacon(config: Omit<BeaconConfig, "autoPageviews">): void;
@@ -0,0 +1,20 @@
1
+ import { afterNavigate } from "$app/navigation";
2
+ import { n as init, r as page } from "./src-DaAShSXp.js";
3
+ // src/sveltekit.ts
4
+ /**
5
+ * Starts Beacon in the browser and records a pageview after the first render and every
6
+ * navigation. Call it from the root `+layout.svelte` script: like `afterNavigate`, it must run
7
+ * during component initialization. Does nothing during SSR.
8
+ */
9
+ function initBeacon(config) {
10
+ afterNavigate(() => {
11
+ init({
12
+ ...config,
13
+ autoPageviews: false
14
+ });
15
+ page();
16
+ });
17
+ }
18
+ export { initBeacon };
19
+
20
+ //# sourceMappingURL=sveltekit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sveltekit.js","names":[],"sources":["../src/sveltekit.ts"],"sourcesContent":["/// <reference types=\"@sveltejs/kit\" />\n\nimport { afterNavigate } from \"$app/navigation\";\nimport { type BeaconConfig, init, page } from \"./index.js\";\n\n/**\n * Starts Beacon in the browser and records a pageview after the first render and every\n * navigation. Call it from the root `+layout.svelte` script: like `afterNavigate`, it must run\n * during component initialization. Does nothing during SSR.\n */\nexport function initBeacon(config: Omit<BeaconConfig, \"autoPageviews\">): void {\n afterNavigate(() => {\n init({ ...config, autoPageviews: false });\n page();\n });\n}\n"],"mappings":";;;;;;;;AAUA,SAAgB,WAAW,QAAmD;CAC5E,oBAAoB;EAClB,KAAK;GAAE,GAAG;GAAQ,eAAe;EAAM,CAAC;EACxC,KAAK;CACP,CAAC;AACH"}
@@ -0,0 +1,12 @@
1
+ import { o as BeaconConfig } from "./index-t-jJl5-d.js";
2
+ /** The part of a TanStack Router instance (React, Solid or Vue) that Beacon uses. */
3
+ interface TanStackRouter {
4
+ subscribe(event: "onRendered", listener: () => void): unknown;
5
+ }
6
+ /**
7
+ * Starts Beacon in the browser and records a pageview each time the router renders a new
8
+ * location, including hydration in TanStack Start. Call it where you create the router; on the
9
+ * server it does nothing.
10
+ */
11
+ export declare function initBeacon(router: TanStackRouter, config: Omit<BeaconConfig, "autoPageviews">): void;
12
+ export {};
@@ -0,0 +1,18 @@
1
+ import { n as init, r as page } from "./src-DaAShSXp.js";
2
+ // src/tanstack-router.ts
3
+ /**
4
+ * Starts Beacon in the browser and records a pageview each time the router renders a new
5
+ * location, including hydration in TanStack Start. Call it where you create the router; on the
6
+ * server it does nothing.
7
+ */
8
+ function initBeacon(router, config) {
9
+ if (typeof window === "undefined") return;
10
+ init({
11
+ ...config,
12
+ autoPageviews: false
13
+ });
14
+ router.subscribe("onRendered", () => page());
15
+ }
16
+ export { initBeacon };
17
+
18
+ //# sourceMappingURL=tanstack-router.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tanstack-router.js","names":[],"sources":["../src/tanstack-router.ts"],"sourcesContent":["import { type BeaconConfig, init, page } from \"./index.js\";\n\n/** The part of a TanStack Router instance (React, Solid or Vue) that Beacon uses. */\ninterface TanStackRouter {\n subscribe(event: \"onRendered\", listener: () => void): unknown;\n}\n\n/**\n * Starts Beacon in the browser and records a pageview each time the router renders a new\n * location, including hydration in TanStack Start. Call it where you create the router; on the\n * server it does nothing.\n */\nexport function initBeacon(\n router: TanStackRouter,\n config: Omit<BeaconConfig, \"autoPageviews\">,\n): void {\n if (typeof window === \"undefined\") {\n return;\n }\n\n init({ ...config, autoPageviews: false });\n // onRendered runs after the new route (and its <title>) is on screen.\n router.subscribe(\"onRendered\", () => page());\n}\n"],"mappings":";;;;;;;AAYA,SAAgB,WACd,QACA,QACM;CACN,IAAI,OAAO,WAAW,aACpB;CAGF,KAAK;EAAE,GAAG;EAAQ,eAAe;CAAM,CAAC;CAExC,OAAO,UAAU,oBAAoB,KAAK,CAAC;AAC7C"}
package/dist/vue.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { Plugin } from "vue";
2
+ import { i as track, o as BeaconConfig, r as page, t as identify } from "./index-t-jJl5-d.js";
3
+ /** The parts of a Vue Router instance that Beacon uses. */
4
+ interface VueRouter {
5
+ afterEach(hook: (to: unknown, from: unknown, failure?: unknown) => void): () => void;
6
+ isReady(): Promise<unknown>;
7
+ }
8
+ export interface BeaconVueOptions extends BeaconConfig {
9
+ /** Record a pageview after each Vue Router navigation instead of watching the History API. */
10
+ router?: VueRouter;
11
+ }
12
+ /** Vue plugin: `app.use(beacon, { websiteId, endpoint, router })`. Safe during SSR. */
13
+ export declare const beacon: Plugin<[BeaconVueOptions]>;
14
+ /** `track`, `identify` and `page` for `<script setup>` and composables. */
15
+ export declare function useBeacon(): {
16
+ track: typeof track;
17
+ identify: typeof identify;
18
+ page: typeof page;
19
+ };
20
+ export {};
package/dist/vue.js ADDED
@@ -0,0 +1,31 @@
1
+ import { nextTick } from "vue";
2
+ import { i as track, n as init, r as page, t as identify } from "./src-DaAShSXp.js";
3
+ // src/vue.ts
4
+ /** Vue plugin: `app.use(beacon, { websiteId, endpoint, router })`. Safe during SSR. */
5
+ const beacon = { install(app, { router, ...config }) {
6
+ if (typeof window === "undefined") return;
7
+ if (!router) {
8
+ init(config);
9
+ return;
10
+ }
11
+ init({
12
+ ...config,
13
+ autoPageviews: false
14
+ });
15
+ const record = () => void nextTick(() => page());
16
+ app.onUnmount(router.afterEach((_to, _from, failure) => {
17
+ if (!failure) record();
18
+ }));
19
+ router.isReady().then(record, () => void 0);
20
+ } };
21
+ /** `track`, `identify` and `page` for `<script setup>` and composables. */
22
+ function useBeacon() {
23
+ return {
24
+ track,
25
+ identify,
26
+ page
27
+ };
28
+ }
29
+ export { beacon, useBeacon };
30
+
31
+ //# sourceMappingURL=vue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vue.js","names":[],"sources":["../src/vue.ts"],"sourcesContent":["import { nextTick, type Plugin } from \"vue\";\nimport { type BeaconConfig, identify, init, page, track } from \"./index.js\";\n\n/** The parts of a Vue Router instance that Beacon uses. */\ninterface VueRouter {\n afterEach(\n hook: (to: unknown, from: unknown, failure?: unknown) => void,\n ): () => void;\n isReady(): Promise<unknown>;\n}\n\nexport interface BeaconVueOptions extends BeaconConfig {\n /** Record a pageview after each Vue Router navigation instead of watching the History API. */\n router?: VueRouter;\n}\n\n/** Vue plugin: `app.use(beacon, { websiteId, endpoint, router })`. Safe during SSR. */\nexport const beacon: Plugin<[BeaconVueOptions]> = {\n install(app, { router, ...config }) {\n // Nothing to record during SSR.\n if (typeof window === \"undefined\") {\n return;\n }\n\n if (!router) {\n init(config);\n\n return;\n }\n\n init({ ...config, autoPageviews: false });\n\n // After nextTick the new route has rendered and every afterEach hook (e.g. one setting\n // document.title) has run.\n const record = () => void nextTick(() => page());\n\n // A failed navigation never rendered. A back/forward one a guard aborted still shows the\n // refused URL until the router's history.go() undoes it.\n app.onUnmount(\n router.afterEach((_to, _from, failure) => {\n if (!failure) {\n record();\n }\n }),\n );\n // Covers an initial navigation that finished before the plugin was installed. If it failed (a\n // guard threw), the app handles that error: it must not become an unhandled rejection here.\n void router.isReady().then(record, () => undefined);\n },\n};\n\n/** `track`, `identify` and `page` for `<script setup>` and composables. */\nexport function useBeacon() {\n return { track, identify, page };\n}\n"],"mappings":";;;;AAiBA,MAAa,SAAqC,EAChD,QAAQ,KAAK,EAAE,QAAQ,GAAG,UAAU;CAElC,IAAI,OAAO,WAAW,aACpB;CAGF,IAAI,CAAC,QAAQ;EACX,KAAK,MAAM;EAEX;CACF;CAEA,KAAK;EAAE,GAAG;EAAQ,eAAe;CAAM,CAAC;CAIxC,MAAM,eAAe,KAAK,eAAe,KAAK,CAAC;CAI/C,IAAI,UACF,OAAO,WAAW,KAAK,OAAO,YAAY;EACxC,IAAI,CAAC,SACH,OAAO;CAEX,CAAC,CACH;CAGK,OAAO,QAAQ,CAAC,CAAC,KAAK,cAAc,KAAA,CAAS;AACpD,EACF;;AAGA,SAAgB,YAAY;CAC1B,OAAO;EAAE;EAAO;EAAU;CAAK;AACjC"}
package/package.json CHANGED
@@ -1,6 +1,116 @@
1
1
  {
2
2
  "name": "@tbdhdev/beacon-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Privacy-friendly Beacon analytics for frameworks: React, Next.js, Vue, Nuxt, SvelteKit, Solid, SolidStart, Astro and TanStack Router/Start.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ ".": {
10
+ "@beacon/source": "./src/index.ts",
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./react": {
15
+ "@beacon/source": "./src/react.ts",
16
+ "types": "./dist/react.d.ts",
17
+ "default": "./dist/react.js"
18
+ },
19
+ "./vue": {
20
+ "@beacon/source": "./src/vue.ts",
21
+ "types": "./dist/vue.d.ts",
22
+ "default": "./dist/vue.js"
23
+ },
24
+ "./nuxt": {
25
+ "@beacon/source": "./src/nuxt.ts",
26
+ "types": "./dist/nuxt.d.ts",
27
+ "default": "./dist/nuxt.js"
28
+ },
29
+ "./sveltekit": {
30
+ "@beacon/source": "./src/sveltekit.ts",
31
+ "types": "./dist/sveltekit.d.ts",
32
+ "svelte": "./dist/sveltekit.js",
33
+ "default": "./dist/sveltekit.js"
34
+ },
35
+ "./solid": {
36
+ "@beacon/source": "./src/solid.ts",
37
+ "types": "./dist/solid.d.ts",
38
+ "solid": "./dist/solid.js",
39
+ "default": "./dist/solid.js"
40
+ },
41
+ "./astro": {
42
+ "@beacon/source": "./src/astro.ts",
43
+ "types": "./dist/astro.d.ts",
44
+ "default": "./dist/astro.js"
45
+ },
46
+ "./tanstack-router": {
47
+ "@beacon/source": "./src/tanstack-router.ts",
48
+ "types": "./dist/tanstack-router.d.ts",
49
+ "default": "./dist/tanstack-router.js"
50
+ },
51
+ "./server": {
52
+ "@beacon/source": "./src/server.ts",
53
+ "types": "./dist/server.d.ts",
54
+ "default": "./dist/server.js"
55
+ }
56
+ },
57
+ "files": [
58
+ "dist",
59
+ "src",
60
+ "!src/**/*.test.ts"
61
+ ],
62
+ "peerDependencies": {
63
+ "@solidjs/router": ">=0.16",
64
+ "@sveltejs/kit": ">=3",
65
+ "astro": ">=7",
66
+ "nuxt": ">=4",
67
+ "react": ">=19",
68
+ "solid-js": ">=1.9",
69
+ "vue": ">=3.5"
70
+ },
71
+ "peerDependenciesMeta": {
72
+ "@solidjs/router": {
73
+ "optional": true
74
+ },
75
+ "@sveltejs/kit": {
76
+ "optional": true
77
+ },
78
+ "astro": {
79
+ "optional": true
80
+ },
81
+ "nuxt": {
82
+ "optional": true
83
+ },
84
+ "react": {
85
+ "optional": true
86
+ },
87
+ "solid-js": {
88
+ "optional": true
89
+ },
90
+ "vue": {
91
+ "optional": true
92
+ }
93
+ },
94
+ "devDependencies": {
95
+ "@solidjs/router": "^2.0.1",
96
+ "@solidjs/web": "^2.0.4",
97
+ "@sveltejs/kit": "^3",
98
+ "@types/react": "^19.3.3",
99
+ "astro": "^7.4.14",
100
+ "happy-dom": "^21.0.4",
101
+ "nuxt": "^4.7.1",
102
+ "react": "^19.3.1",
103
+ "solid-js": "^2.0.4",
104
+ "solid-js-1": "npm:solid-js@^1.9.20",
105
+ "svelte": "^5.60.2",
106
+ "tsdown": "^0.23.8",
107
+ "vue": "^3.5.47",
108
+ "vue-router": "^5.6.1"
109
+ },
110
+ "scripts": {
111
+ "build": "tsdown",
112
+ "dev": "tsdown --watch",
113
+ "typecheck": "tsc -p .",
114
+ "test": "vitest run"
115
+ }
6
116
  }
package/src/astro.ts ADDED
@@ -0,0 +1,29 @@
1
+ import type { AstroIntegration } from "astro";
2
+ import { type BeaconConfig, init, page } from "./index.js";
3
+
4
+ export type BeaconAstroOptions = Omit<BeaconConfig, "autoPageviews">;
5
+
6
+ /** Astro integration: `integrations: [beacon({ websiteId, endpoint })]` in `astro.config.mjs`. */
7
+ export default function beacon(config: BeaconAstroOptions): AstroIntegration {
8
+ return {
9
+ name: "@tbdhdev/beacon-sdk",
10
+ hooks: {
11
+ "astro:config:setup": ({ injectScript }) => {
12
+ injectScript(
13
+ "page",
14
+ `import { start } from "@tbdhdev/beacon-sdk/astro"; start(${JSON.stringify(config)});`,
15
+ );
16
+ },
17
+ },
18
+ };
19
+ }
20
+
21
+ /**
22
+ * Browser side of the integration, imported by the script it injects into every page. Records
23
+ * the page load and every `<ClientRouter />` (View Transitions) navigation.
24
+ */
25
+ export function start(config: BeaconAstroOptions): void {
26
+ init({ ...config, autoPageviews: false });
27
+ page();
28
+ document.addEventListener("astro:page-load", () => page());
29
+ }