@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,40 @@
1
+ type BeaconProps = Record<string, string | number | boolean>;
2
+ interface BeaconApi {
3
+ /** Track a custom event, e.g. `track("signup_clicked", { plan: "pro" })`. */
4
+ track: (name: string, props?: BeaconProps) => void;
5
+ /** Opt-in identification for your own logged-in apps. Kept in memory only. */
6
+ identify: (id: string, traits?: BeaconProps) => void;
7
+ /** Record a pageview for `url` (default: the current location). Repeats of the last page are ignored. */
8
+ page: (url?: string) => void;
9
+ }
10
+ interface BeaconConfig {
11
+ /** Website id from the Beacon dashboard. */
12
+ websiteId: string;
13
+ /**
14
+ * Event endpoint: your ingest origin + prefix + event path (Settings → Tracking), e.g.
15
+ * `https://beacon.example.com/x/e`. Relative URLs resolve against the page. Default `/x/e`.
16
+ */
17
+ endpoint?: string;
18
+ /**
19
+ * Record the first pageview and history navigations (pushState, replaceState to another path,
20
+ * back/forward). Set `false` to call `page()` from your router instead. Default `true`.
21
+ */
22
+ autoPageviews?: boolean;
23
+ /**
24
+ * The app routes in the URL hash (`/#/pricing`, e.g. Vue's `createWebHashHistory` or React
25
+ * Router's `HashRouter`): record the hash route as the page path. Default `false`.
26
+ */
27
+ hashRouting?: boolean;
28
+ /** Track clicks on links to other hosts. */
29
+ outbound?: boolean;
30
+ /** Track clicks on file downloads (pdf, zip, csv, ...). */
31
+ downloads?: boolean;
32
+ /** Send LCP, CLS, INP and TTFB when the page is hidden. */
33
+ webVitals?: boolean;
34
+ }
35
+ /** Starts Beacon. Safe to call during SSR (no-op) and more than once (later calls are ignored). */
36
+ declare function init(config: BeaconConfig): void;
37
+ declare function track(name: string, props?: BeaconProps): void;
38
+ declare function identify(id: string, traits?: BeaconProps): void;
39
+ declare function page(url?: string): void;
40
+ export { BeaconApi as a, track as i, init as n, BeaconConfig as o, page as r, BeaconProps as s, identify as t };
@@ -0,0 +1,2 @@
1
+ import { a as BeaconApi, i as track, n as init, o as BeaconConfig, r as page, s as BeaconProps, t as identify } from "./index-t-jJl5-d.js";
2
+ export { type BeaconApi, type BeaconConfig, type BeaconProps, identify, init, page, track };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { t as identify, n as init, r as page, i as track } from "./src-DaAShSXp.js";
package/dist/nuxt.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { NuxtModule } from "nuxt/schema";
2
+ import { o as BeaconConfig } from "./index-t-jJl5-d.js";
3
+ export type BeaconNuxtOptions = Omit<BeaconConfig, "autoPageviews">;
4
+ /**
5
+ * Nuxt module: add `"@tbdhdev/beacon-sdk/nuxt"` to `modules` and set options under `beacon`. Starts
6
+ * Beacon in the browser, records a pageview once each page has rendered and auto-imports
7
+ * `useBeacon()`.
8
+ */
9
+ declare const beaconModule: NuxtModule<BeaconNuxtOptions>;
10
+ export { beaconModule as default };
package/dist/nuxt.js ADDED
@@ -0,0 +1,42 @@
1
+ import { addImports, addPluginTemplate, defineNuxtModule } from "nuxt/kit";
2
+ // src/nuxt.ts
3
+ /**
4
+ * Nuxt module: add `"@tbdhdev/beacon-sdk/nuxt"` to `modules` and set options under `beacon`. Starts
5
+ * Beacon in the browser, records a pageview once each page has rendered and auto-imports
6
+ * `useBeacon()`.
7
+ */
8
+ const beaconModule = defineNuxtModule({
9
+ meta: {
10
+ name: "@tbdhdev/beacon-sdk",
11
+ configKey: "beacon"
12
+ },
13
+ setup(options, nuxt) {
14
+ const { public: runtime } = nuxt.options.runtimeConfig;
15
+ runtime.beacon = {
16
+ ...options,
17
+ ...runtime.beacon
18
+ };
19
+ addPluginTemplate({
20
+ filename: "beacon.client.mjs",
21
+ mode: "client",
22
+ getContents: () => `import { defineNuxtPlugin, useRuntimeConfig } from "#app";
23
+ import { init, page } from "@tbdhdev/beacon-sdk";
24
+
25
+ export default defineNuxtPlugin((nuxtApp) => {
26
+ const record = () => setTimeout(() => page(), 0);
27
+
28
+ init({ ...useRuntimeConfig().public.beacon, autoPageviews: false });
29
+ nuxtApp.hook("app:suspense:resolve", record);
30
+ nuxtApp.hook("page:loading:end", record);
31
+ });
32
+ `
33
+ });
34
+ addImports({
35
+ name: "useBeacon",
36
+ from: "@tbdhdev/beacon-sdk/vue"
37
+ });
38
+ }
39
+ });
40
+ export { beaconModule as default };
41
+
42
+ //# sourceMappingURL=nuxt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nuxt.js","names":[],"sources":["../src/nuxt.ts"],"sourcesContent":["import { addImports, addPluginTemplate, defineNuxtModule } from \"nuxt/kit\";\nimport type { NuxtModule } from \"nuxt/schema\";\nimport type { BeaconConfig } from \"./index.js\";\n\nexport type BeaconNuxtOptions = Omit<BeaconConfig, \"autoPageviews\">;\n\n/**\n * Nuxt module: add `\"@tbdhdev/beacon-sdk/nuxt\"` to `modules` and set options under `beacon`. Starts\n * Beacon in the browser, records a pageview once each page has rendered and auto-imports\n * `useBeacon()`.\n */\nconst beaconModule: NuxtModule<BeaconNuxtOptions> =\n defineNuxtModule<BeaconNuxtOptions>({\n meta: { name: \"@tbdhdev/beacon-sdk\", configKey: \"beacon\" },\n setup(options, nuxt) {\n const { public: runtime } = nuxt.options.runtimeConfig;\n\n // Public runtime config, so NUXT_PUBLIC_BEACON_WEBSITE_ID (and the other options) can be set\n // when the app starts instead of when it is built. Values already set there win.\n runtime.beacon = {\n ...options,\n ...(runtime.beacon as Partial<BeaconNuxtOptions> | undefined),\n };\n // A generated client plugin: the package ships no runtime file that needs Nuxt's aliases.\n // page:loading:end runs once per navigation (query-only ones included) and on first load.\n // Nuxt writes the new <title> in a microtask after it, hence setTimeout; router.afterEach\n // would be even earlier. A first load that shows error.vue renders no page and has no\n // page:loading:end, hence app:suspense:resolve too, which runs once the first page (or\n // error.vue) has resolved and Nuxt has written its head (page() skips the repeat).\n addPluginTemplate({\n filename: \"beacon.client.mjs\",\n mode: \"client\",\n getContents:\n () => `import { defineNuxtPlugin, useRuntimeConfig } from \"#app\";\nimport { init, page } from \"@tbdhdev/beacon-sdk\";\n\nexport default defineNuxtPlugin((nuxtApp) => {\n const record = () => setTimeout(() => page(), 0);\n\n init({ ...useRuntimeConfig().public.beacon, autoPageviews: false });\n nuxtApp.hook(\"app:suspense:resolve\", record);\n nuxtApp.hook(\"page:loading:end\", record);\n});\n`,\n });\n addImports({ name: \"useBeacon\", from: \"@tbdhdev/beacon-sdk/vue\" });\n },\n });\n\nexport default beaconModule;\n"],"mappings":";;;;;;;AAWA,MAAM,eACJ,iBAAoC;CAClC,MAAM;EAAE,MAAM;EAAuB,WAAW;CAAS;CACzD,MAAM,SAAS,MAAM;EACnB,MAAM,EAAE,QAAQ,YAAY,KAAK,QAAQ;EAIzC,QAAQ,SAAS;GACf,GAAG;GACH,GAAI,QAAQ;EACd;EAOA,kBAAkB;GAChB,UAAU;GACV,MAAM;GACN,mBACQ;;;;;;;;;;;EAWV,CAAC;EACD,WAAW;GAAE,MAAM;GAAa,MAAM;EAA0B,CAAC;CACnE;AACF,CAAC"}
@@ -0,0 +1,6 @@
1
+ import { o as BeaconConfig } from "./index-t-jJl5-d.js";
2
+ /**
3
+ * Starts Beacon on mount, so a server layout (e.g. Next.js `app/layout.tsx`) can render it
4
+ * without its own client wrapper. Render it once; later prop changes are ignored.
5
+ */
6
+ export declare function Beacon(props: BeaconConfig): null;
package/dist/react.js ADDED
@@ -0,0 +1,15 @@
1
+ "use client";
2
+ import { useEffect } from "react";
3
+ import { n as init } from "./src-DaAShSXp.js";
4
+ // src/react.ts
5
+ /**
6
+ * Starts Beacon on mount, so a server layout (e.g. Next.js `app/layout.tsx`) can render it
7
+ * without its own client wrapper. Render it once; later prop changes are ignored.
8
+ */
9
+ function Beacon(props) {
10
+ useEffect(() => init(props));
11
+ return null;
12
+ }
13
+ export { Beacon };
14
+
15
+ //# sourceMappingURL=react.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"react.js","names":[],"sources":["../src/react.ts"],"sourcesContent":["\"use client\";\nimport { useEffect } from \"react\";\nimport { type BeaconConfig, init } from \"./index.js\";\n\n/**\n * Starts Beacon on mount, so a server layout (e.g. Next.js `app/layout.tsx`) can render it\n * without its own client wrapper. Render it once; later prop changes are ignored.\n */\nexport function Beacon(props: BeaconConfig): null {\n useEffect(() => init(props));\n\n return null;\n}\n"],"mappings":";;;;;;;;AAQA,SAAgB,OAAO,OAA2B;CAChD,gBAAgB,KAAK,KAAK,CAAC;CAE3B,OAAO;AACT"}
@@ -0,0 +1,58 @@
1
+ export type BeaconProps = Record<string, string | number | boolean>;
2
+ export interface BeaconServerConfig {
3
+ /** Website id from the Beacon dashboard. */
4
+ websiteId: string;
5
+ /** Full event URL: your Beacon origin + ingest prefix + event path, e.g. `https://beacon.example.com/x/e`. */
6
+ endpoint: string;
7
+ /** API key with the `write:events` scope. Keep it in a server-only env var. */
8
+ apiKey: string;
9
+ /** Give up on a request (and reject) after this many milliseconds. Default `5000`. */
10
+ timeoutMs?: number;
11
+ }
12
+ /** Optional request details. Forward `ip` and `userAgent` to count the event toward the end user's visit. */
13
+ export interface BeaconEventContext {
14
+ /** Page the event belongs to (absolute URL). */
15
+ url?: string;
16
+ title?: string;
17
+ referrer?: string;
18
+ /** The end user's IP, e.g. from `x-forwarded-for`. Used for the visitor hash and country, never stored. */
19
+ ip?: string;
20
+ /** The end user's `user-agent` header. */
21
+ userAgent?: string;
22
+ /** Your own user id, like `identify()` in the browser. */
23
+ distinctId?: string;
24
+ language?: string;
25
+ }
26
+ export interface BeaconServer {
27
+ /** Send a custom event. Rejects if Beacon refuses it (bad key, unknown website, invalid payload). */
28
+ track(name: string, props?: BeaconProps, context?: BeaconEventContext): Promise<void>;
29
+ /** Send an identify event for `distinctId`, with optional traits. */
30
+ identify(distinctId: string, traits?: BeaconProps, context?: BeaconEventContext): Promise<void>;
31
+ }
32
+ export declare function createBeaconServer(config: BeaconServerConfig): BeaconServer;
33
+ export interface BeaconProxyConfig {
34
+ /** Full event URL: your Beacon origin + ingest prefix + event path, e.g. `https://beacon.example.com/x/e`. */
35
+ endpoint: string;
36
+ /** API key with the `write:events` scope. It vouches for the visitor IP the proxy forwards. */
37
+ apiKey: string;
38
+ /**
39
+ * The visitor's IP, from a source your host guarantees: `forwardedFor(request)` behind a proxy that
40
+ * sets `x-forwarded-for` (Vercel, Caddy), Cloudflare's `cf-connecting-ip`, ... Without one, Beacon
41
+ * tells visitors apart only by user agent, with no country, and they share one rate limit.
42
+ */
43
+ clientIp?: string | null | undefined;
44
+ /** Give up on Beacon after this many milliseconds and answer 502. Default `5000`. */
45
+ timeoutMs?: number;
46
+ }
47
+ /**
48
+ * The last `x-forwarded-for` entry: the visitor's IP behind a proxy that sets or appends to the header
49
+ * (Vercel, Caddy, Nginx with `$proxy_add_x_forwarded_for`). With nothing in front, visitors write
50
+ * their own, so don't use it there.
51
+ */
52
+ export declare function forwardedFor(request: Request): string | undefined;
53
+ /**
54
+ * Forwards a browser event, posted by `@tbdhdev/beacon-sdk` to a route on your own site, to Beacon. Ad
55
+ * blockers that refuse requests to analytics hosts let a same-site request through. Answers with
56
+ * Beacon's status and no body. Point the browser SDK's `endpoint` at the route, e.g. `/api/e`.
57
+ */
58
+ export declare function proxyBeacon(request: Request, config: BeaconProxyConfig): Promise<Response>;
package/dist/server.js ADDED
@@ -0,0 +1,102 @@
1
+ // src/server.ts
2
+ function createBeaconServer(config) {
3
+ const send = async (type, name, props, { url, title, referrer, ip, userAgent, distinctId, language } = {}) => {
4
+ const apiKey = config.apiKey?.trim();
5
+ const websiteId = config.websiteId?.trim();
6
+ for (const [field, value] of Object.entries({
7
+ apiKey,
8
+ websiteId
9
+ })) if (!value) throw new Error(`Beacon did not send "${name}": ${field} is missing`);
10
+ const response = await fetch(config.endpoint, {
11
+ method: "POST",
12
+ headers: {
13
+ Authorization: `Bearer ${apiKey}`,
14
+ "Content-Type": "application/json"
15
+ },
16
+ body: JSON.stringify({
17
+ website: websiteId,
18
+ type,
19
+ name,
20
+ props,
21
+ url,
22
+ title,
23
+ referrer,
24
+ ip,
25
+ language,
26
+ user_agent: userAgent,
27
+ id: distinctId
28
+ }),
29
+ signal: AbortSignal.timeout(config.timeoutMs ?? 5e3)
30
+ });
31
+ await response.body?.cancel().catch(() => void 0);
32
+ if (!response.ok) throw new Error(`Beacon rejected "${name}": HTTP ${response.status}`);
33
+ };
34
+ return {
35
+ track: (name, props, context) => send("event", name, props, context),
36
+ identify: (distinctId, traits, context) => send("identify", "identify", traits, {
37
+ ...context,
38
+ distinctId
39
+ })
40
+ };
41
+ }
42
+ const PROXIED_HEADERS = [
43
+ "content-type",
44
+ "user-agent",
45
+ "accept-language",
46
+ "origin",
47
+ "dnt",
48
+ "sec-gpc"
49
+ ];
50
+ /**
51
+ * The last `x-forwarded-for` entry: the visitor's IP behind a proxy that sets or appends to the header
52
+ * (Vercel, Caddy, Nginx with `$proxy_add_x_forwarded_for`). With nothing in front, visitors write
53
+ * their own, so don't use it there.
54
+ */
55
+ function forwardedFor(request) {
56
+ return request.headers.get("x-forwarded-for")?.split(",").at(-1)?.trim() || void 0;
57
+ }
58
+ let warnedNoIp = false;
59
+ /**
60
+ * Forwards a browser event, posted by `@tbdhdev/beacon-sdk` to a route on your own site, to Beacon. Ad
61
+ * blockers that refuse requests to analytics hosts let a same-site request through. Answers with
62
+ * Beacon's status and no body. Point the browser SDK's `endpoint` at the route, e.g. `/api/e`.
63
+ */
64
+ async function proxyBeacon(request, config) {
65
+ const apiKey = config.apiKey?.trim();
66
+ for (const [field, value] of Object.entries({
67
+ endpoint: config.endpoint,
68
+ apiKey
69
+ })) if (!value) return new Response(`Beacon proxy: ${field} is missing`, { status: 500 });
70
+ const ip = config.clientIp?.trim();
71
+ if (!ip && !warnedNoIp) {
72
+ warnedNoIp = true;
73
+ console.warn("Beacon proxy: no visitor IP, so visitors are told apart only by user agent and share one rate limit. Pass clientIp.");
74
+ }
75
+ const headers = new Headers({
76
+ Authorization: `Bearer ${apiKey}`,
77
+ "Beacon-Forwarded-For": ip || "unknown",
78
+ "User-Agent": "",
79
+ "Accept-Language": ""
80
+ });
81
+ for (const name of PROXIED_HEADERS) {
82
+ const value = request.headers.get(name);
83
+ if (value !== null) headers.set(name, value);
84
+ }
85
+ const init = {
86
+ method: "POST",
87
+ headers,
88
+ body: request.body,
89
+ duplex: "half",
90
+ signal: AbortSignal.timeout(config.timeoutMs ?? 5e3)
91
+ };
92
+ try {
93
+ const response = await fetch(config.endpoint, init);
94
+ await response.body?.cancel().catch(() => void 0);
95
+ return new Response(null, { status: response.status });
96
+ } catch {
97
+ return new Response(null, { status: 502 });
98
+ }
99
+ }
100
+ export { createBeaconServer, forwardedFor, proxyBeacon };
101
+
102
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","names":[],"sources":["../src/server.ts"],"sourcesContent":["// Server-side events, and a first-party proxy for browser events, for any runtime with `fetch`:\n// Node, Bun, Deno, edge functions, CI. Authenticated with an API key, so never import this into\n// browser code.\n// Same shape as the browser entry's BeaconProps. Defined here so the server entry never pulls in\n// the DOM-based core, even for type checking.\nexport type BeaconProps = Record<string, string | number | boolean>;\n\nexport interface BeaconServerConfig {\n /** Website id from the Beacon dashboard. */\n websiteId: string;\n /** Full event URL: your Beacon origin + ingest prefix + event path, e.g. `https://beacon.example.com/x/e`. */\n endpoint: string;\n /** API key with the `write:events` scope. Keep it in a server-only env var. */\n apiKey: string;\n /** Give up on a request (and reject) after this many milliseconds. Default `5000`. */\n timeoutMs?: number;\n}\n\n/** Optional request details. Forward `ip` and `userAgent` to count the event toward the end user's visit. */\nexport interface BeaconEventContext {\n /** Page the event belongs to (absolute URL). */\n url?: string;\n title?: string;\n referrer?: string;\n /** The end user's IP, e.g. from `x-forwarded-for`. Used for the visitor hash and country, never stored. */\n ip?: string;\n /** The end user's `user-agent` header. */\n userAgent?: string;\n /** Your own user id, like `identify()` in the browser. */\n distinctId?: string;\n language?: string;\n}\n\nexport interface BeaconServer {\n /** Send a custom event. Rejects if Beacon refuses it (bad key, unknown website, invalid payload). */\n track(\n name: string,\n props?: BeaconProps,\n context?: BeaconEventContext,\n ): Promise<void>;\n /** Send an identify event for `distinctId`, with optional traits. */\n identify(\n distinctId: string,\n traits?: BeaconProps,\n context?: BeaconEventContext,\n ): Promise<void>;\n}\n\nexport function createBeaconServer(config: BeaconServerConfig): BeaconServer {\n const send = async (\n type: string,\n name: string,\n props: BeaconProps | undefined,\n {\n url,\n title,\n referrer,\n ip,\n userAgent,\n distinctId,\n language,\n }: BeaconEventContext = {},\n ) => {\n // Without a key, ingest would treat this as a browser event and answer an unhelpful 403.\n // Trimmed: a key read from a secrets file often ends in a newline, which no header may hold.\n const apiKey = config.apiKey?.trim();\n const websiteId = config.websiteId?.trim();\n\n for (const [field, value] of Object.entries({ apiKey, websiteId })) {\n if (!value) {\n throw new Error(`Beacon did not send \"${name}\": ${field} is missing`);\n }\n }\n\n const response = await fetch(config.endpoint, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n // Fields picked one by one: extra keys on a context object can't replace the event's own.\n body: JSON.stringify({\n website: websiteId,\n type,\n name,\n props,\n url,\n title,\n referrer,\n ip,\n language,\n user_agent: userAgent,\n id: distinctId,\n }),\n signal: AbortSignal.timeout(config.timeoutMs ?? 5000),\n });\n\n // The status is the whole answer: free the connection instead of leaving the body unread.\n await response.body?.cancel().catch(() => undefined);\n\n if (!response.ok) {\n throw new Error(`Beacon rejected \"${name}\": HTTP ${response.status}`);\n }\n };\n\n return {\n track: (name, props, context) => send(\"event\", name, props, context),\n identify: (distinctId, traits, context) =>\n send(\"identify\", \"identify\", traits, { ...context, distinctId }),\n };\n}\n\nexport interface BeaconProxyConfig {\n /** Full event URL: your Beacon origin + ingest prefix + event path, e.g. `https://beacon.example.com/x/e`. */\n endpoint: string;\n /** API key with the `write:events` scope. It vouches for the visitor IP the proxy forwards. */\n apiKey: string;\n /**\n * The visitor's IP, from a source your host guarantees: `forwardedFor(request)` behind a proxy that\n * sets `x-forwarded-for` (Vercel, Caddy), Cloudflare's `cf-connecting-ip`, ... Without one, Beacon\n * tells visitors apart only by user agent, with no country, and they share one rate limit.\n */\n // `| undefined`: lookups like `forwardedFor()` return it, which exactOptionalPropertyTypes refuses.\n clientIp?: string | null | undefined;\n /** Give up on Beacon after this many milliseconds and answer 502. Default `5000`. */\n timeoutMs?: number;\n}\n\n// The browser headers ingest reads. Cookies and everything else stay on your server.\nconst PROXIED_HEADERS = [\n \"content-type\",\n \"user-agent\",\n \"accept-language\",\n \"origin\",\n \"dnt\",\n \"sec-gpc\",\n];\n\n/**\n * The last `x-forwarded-for` entry: the visitor's IP behind a proxy that sets or appends to the header\n * (Vercel, Caddy, Nginx with `$proxy_add_x_forwarded_for`). With nothing in front, visitors write\n * their own, so don't use it there.\n */\nexport function forwardedFor(request: Request): string | undefined {\n return (\n request.headers.get(\"x-forwarded-for\")?.split(\",\").at(-1)?.trim() ||\n undefined\n );\n}\n\nlet warnedNoIp = false;\n\n/**\n * Forwards a browser event, posted by `@tbdhdev/beacon-sdk` to a route on your own site, to Beacon. Ad\n * blockers that refuse requests to analytics hosts let a same-site request through. Answers with\n * Beacon's status and no body. Point the browser SDK's `endpoint` at the route, e.g. `/api/e`.\n */\nexport async function proxyBeacon(\n request: Request,\n config: BeaconProxyConfig,\n): Promise<Response> {\n const apiKey = config.apiKey?.trim();\n\n for (const [field, value] of Object.entries({\n endpoint: config.endpoint,\n apiKey,\n })) {\n if (!value) {\n return new Response(`Beacon proxy: ${field} is missing`, { status: 500 });\n }\n }\n\n const ip = config.clientIp?.trim();\n\n if (!ip && !warnedNoIp) {\n warnedNoIp = true;\n console.warn(\n \"Beacon proxy: no visitor IP, so visitors are told apart only by user agent and share one rate limit. Pass clientIp.\",\n );\n }\n\n const headers = new Headers({\n Authorization: `Bearer ${apiKey}`,\n // Ingest's ProxyHeader. \"unknown\" still marks the request as proxied, so browser rules apply.\n \"Beacon-Forwarded-For\": ip || \"unknown\",\n // Left out, the runtime sends its own (\"node\", \"*\"), which Beacon would take for the visitor's.\n \"User-Agent\": \"\",\n \"Accept-Language\": \"\",\n });\n\n for (const name of PROXIED_HEADERS) {\n const value = request.headers.get(name);\n\n if (value !== null) {\n headers.set(name, value);\n }\n }\n\n // Streamed, not buffered: Beacon stops reading past its 16 KiB cap, so a huge upload never sits in\n // your server's memory. `duplex` is required for a stream body but missing from the DOM types.\n const init: RequestInit & { duplex: \"half\" } = {\n method: \"POST\",\n headers,\n body: request.body,\n duplex: \"half\",\n signal: AbortSignal.timeout(config.timeoutMs ?? 5000),\n };\n\n try {\n const response = await fetch(config.endpoint, init);\n\n await response.body?.cancel().catch(() => undefined);\n\n return new Response(null, { status: response.status });\n } catch {\n // Unreachable, timed out, or a malformed endpoint: the visitor's page must not care.\n return new Response(null, { status: 502 });\n }\n}\n"],"mappings":";AAgDA,SAAgB,mBAAmB,QAA0C;CAC3E,MAAM,OAAO,OACX,MACA,MACA,OACA,EACE,KACA,OACA,UACA,IACA,WACA,YACA,aACsB,CAAC,MACtB;EAGH,MAAM,SAAS,OAAO,QAAQ,KAAK;EACnC,MAAM,YAAY,OAAO,WAAW,KAAK;EAEzC,KAAK,MAAM,CAAC,OAAO,UAAU,OAAO,QAAQ;GAAE;GAAQ;EAAU,CAAC,GAC/D,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,wBAAwB,KAAK,KAAK,MAAM,YAAY;EAIxE,MAAM,WAAW,MAAM,MAAM,OAAO,UAAU;GAC5C,QAAQ;GACR,SAAS;IACP,eAAe,UAAU;IACzB,gBAAgB;GAClB;GAEA,MAAM,KAAK,UAAU;IACnB,SAAS;IACT;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,YAAY;IACZ,IAAI;GACN,CAAC;GACD,QAAQ,YAAY,QAAQ,OAAO,aAAa,GAAI;EACtD,CAAC;EAGD,MAAM,SAAS,MAAM,OAAO,CAAC,CAAC,YAAY,KAAA,CAAS;EAEnD,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,oBAAoB,KAAK,UAAU,SAAS,QAAQ;CAExE;CAEA,OAAO;EACL,QAAQ,MAAM,OAAO,YAAY,KAAK,SAAS,MAAM,OAAO,OAAO;EACnE,WAAW,YAAY,QAAQ,YAC7B,KAAK,YAAY,YAAY,QAAQ;GAAE,GAAG;GAAS;EAAW,CAAC;CACnE;AACF;AAmBA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;AAOA,SAAgB,aAAa,SAAsC;CACjE,OACE,QAAQ,QAAQ,IAAI,iBAAiB,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,KAAK,KAChE,KAAA;AAEJ;AAEA,IAAI,aAAa;;;;;;AAOjB,eAAsB,YACpB,SACA,QACmB;CACnB,MAAM,SAAS,OAAO,QAAQ,KAAK;CAEnC,KAAK,MAAM,CAAC,OAAO,UAAU,OAAO,QAAQ;EAC1C,UAAU,OAAO;EACjB;CACF,CAAC,GACC,IAAI,CAAC,OACH,OAAO,IAAI,SAAS,iBAAiB,MAAM,cAAc,EAAE,QAAQ,IAAI,CAAC;CAI5E,MAAM,KAAK,OAAO,UAAU,KAAK;CAEjC,IAAI,CAAC,MAAM,CAAC,YAAY;EACtB,aAAa;EACb,QAAQ,KACN,qHACF;CACF;CAEA,MAAM,UAAU,IAAI,QAAQ;EAC1B,eAAe,UAAU;EAEzB,wBAAwB,MAAM;EAE9B,cAAc;EACd,mBAAmB;CACrB,CAAC;CAED,KAAK,MAAM,QAAQ,iBAAiB;EAClC,MAAM,QAAQ,QAAQ,QAAQ,IAAI,IAAI;EAEtC,IAAI,UAAU,MACZ,QAAQ,IAAI,MAAM,KAAK;CAE3B;CAIA,MAAM,OAAyC;EAC7C,QAAQ;EACR;EACA,MAAM,QAAQ;EACd,QAAQ;EACR,QAAQ,YAAY,QAAQ,OAAO,aAAa,GAAI;CACtD;CAEA,IAAI;EACF,MAAM,WAAW,MAAM,MAAM,OAAO,UAAU,IAAI;EAElD,MAAM,SAAS,MAAM,OAAO,CAAC,CAAC,YAAY,KAAA,CAAS;EAEnD,OAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,SAAS,OAAO,CAAC;CACvD,QAAQ;EAEN,OAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;CAC3C;AACF"}
@@ -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 per Solid Router location change. Render
4
+ * it once inside the router, e.g. in the root layout. Works on Solid 1 (SolidStart) and Solid 2.
5
+ * Nothing runs during SSR.
6
+ */
7
+ export declare function Beacon(props: Omit<BeaconConfig, "autoPageviews">): null;
package/dist/solid.js ADDED
@@ -0,0 +1,44 @@
1
+ import { useIsRouting, useLocation } from "@solidjs/router";
2
+ import * as Solid from "solid-js";
3
+ import { n as init, r as page } from "./src-DaAShSXp.js";
4
+ // src/solid.ts
5
+ const { createReaction, untrack } = Solid;
6
+ const { onSettled } = Solid;
7
+ /**
8
+ * Starts Beacon in the browser and records a pageview per Solid Router location change. Render
9
+ * it once inside the router, e.g. in the root layout. Works on Solid 1 (SolidStart) and Solid 2.
10
+ * Nothing runs during SSR.
11
+ */
12
+ function Beacon(props) {
13
+ const location = useLocation();
14
+ const isRouting = useIsRouting();
15
+ const url = () => location.pathname + location.search;
16
+ const record = () => setTimeout(() => page(), 0);
17
+ const track = createReaction(() => {
18
+ record();
19
+ track(url);
20
+ });
21
+ const settled = createReaction(() => {
22
+ if (untrack(isRouting)) settled(isRouting);
23
+ else record();
24
+ });
25
+ init(untrack(() => ({
26
+ ...props,
27
+ autoPageviews: false
28
+ })));
29
+ track(url);
30
+ if (typeof window !== "undefined") {
31
+ const first = () => setTimeout(() => {
32
+ if (untrack(isRouting)) settled(isRouting);
33
+ else page();
34
+ }, 0);
35
+ if (onSettled) onSettled(() => {
36
+ first();
37
+ });
38
+ else first();
39
+ }
40
+ return null;
41
+ }
42
+ export { Beacon };
43
+
44
+ //# sourceMappingURL=solid.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"solid.js","names":[],"sources":["../src/solid.ts"],"sourcesContent":["import { useIsRouting, useLocation } from \"@solidjs/router\";\nimport * as Solid from \"solid-js\";\nimport { type BeaconConfig, init, page } from \"./index.js\";\n\nconst { createReaction, untrack } = Solid;\n// Solid 2 only (Solid 1 has no onSettled): runs once the enclosing <Loading> boundary shows its\n// content, so the first pageview gets the first route's title even when that route is async.\nconst { onSettled } = Solid as { onSettled?: typeof Solid.onSettled };\n\n/**\n * Starts Beacon in the browser and records a pageview per Solid Router location change. Render\n * it once inside the router, e.g. in the root layout. Works on Solid 1 (SolidStart) and Solid 2.\n * Nothing runs during SSR.\n */\nexport function Beacon(props: Omit<BeaconConfig, \"autoPageviews\">): null {\n const location = useLocation();\n const isRouting = useIsRouting();\n const url = () => location.pathname + location.search;\n // <Title> (Solid's head registry) writes in a microtask queued by the same pass.\n const record = () => setTimeout(() => page(), 0);\n // createReaction works the same in Solid 1 and 2 (createEffect and onMount don't). It fires once\n // per change, after the new route rendered, so it re-arms itself each time. Its callbacks keep\n // block bodies: Solid 2 treats a returned value as a cleanup.\n const track = createReaction(() => {\n record();\n track(url);\n });\n // The first page waits out a navigation in flight: a <Beacon> in a layout mounts while the\n // router is still loading that route, and a redirect on load is not a page of its own.\n const settled = createReaction(() => {\n if (untrack(isRouting)) {\n settled(isRouting);\n } else {\n record();\n }\n });\n\n // Read once, like init() itself: later prop changes are ignored.\n init(untrack(() => ({ ...props, autoPageviews: false })));\n track(url);\n\n // init() and page() do nothing during SSR, but skip the timer there too.\n if (typeof window !== \"undefined\") {\n const first = () =>\n setTimeout(() => {\n if (untrack(isRouting)) {\n settled(isRouting);\n } else {\n page();\n }\n }, 0);\n\n if (onSettled) {\n onSettled(() => {\n first();\n });\n } else {\n first();\n }\n }\n\n return null;\n}\n"],"mappings":";;;;AAIA,MAAM,EAAE,gBAAgB,YAAY;AAGpC,MAAM,EAAE,cAAc;;;;;;AAOtB,SAAgB,OAAO,OAAkD;CACvE,MAAM,WAAW,YAAY;CAC7B,MAAM,YAAY,aAAa;CAC/B,MAAM,YAAY,SAAS,WAAW,SAAS;CAE/C,MAAM,eAAe,iBAAiB,KAAK,GAAG,CAAC;CAI/C,MAAM,QAAQ,qBAAqB;EACjC,OAAO;EACP,MAAM,GAAG;CACX,CAAC;CAGD,MAAM,UAAU,qBAAqB;EACnC,IAAI,QAAQ,SAAS,GACnB,QAAQ,SAAS;OAEjB,OAAO;CAEX,CAAC;CAGD,KAAK,eAAe;EAAE,GAAG;EAAO,eAAe;CAAM,EAAE,CAAC;CACxD,MAAM,GAAG;CAGT,IAAI,OAAO,WAAW,aAAa;EACjC,MAAM,cACJ,iBAAiB;GACf,IAAI,QAAQ,SAAS,GACnB,QAAQ,SAAS;QAEjB,KAAK;EAET,GAAG,CAAC;EAEN,IAAI,WACF,gBAAgB;GACd,MAAM;EACR,CAAC;OAED,MAAM;CAEV;CAEA,OAAO;AACT"}