highseat 0.2.0 → 0.3.1

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/proxy2.js DELETED
@@ -1,235 +0,0 @@
1
- //#region src/env.ts
2
- /**
3
- * The variables the package reads from a customer's environment. Each is named in full, never
4
- * looked up by a computed key: Next.js inlines a `NEXT_PUBLIC_` variable into browser code only
5
- * where the source spells out `process.env.NEXT_PUBLIC_…`. The server variables return
6
- * `undefined` where the runtime has no `process`: a Cloudflare Worker without `nodejs_compat`,
7
- * whose options carry the values instead.
8
- */
9
- /** The site id for `<Highseat />` in Next.js. Public, so it reaches the browser. */
10
- function findNextSite() {
11
- return process.env.NEXT_PUBLIC_HIGHSEAT_SITE;
12
- }
13
- /**
14
- * The site's proxy path: `option` when given, else `HIGHSEAT_PATH`, a server variable shared by
15
- * `<Highseat />`, `withHighseat()` and the proxy handler. A value written without its leading
16
- * slash gets one, as Installation settings shows it (`/3f9a0c1e2b`). An empty value counts as
17
- * unset.
18
- */
19
- function findProxyPath(option) {
20
- const path = option ?? (typeof process === "undefined" ? void 0 : process.env.HIGHSEAT_PATH);
21
- if (!path) return;
22
- return path.startsWith("/") ? path : `/${path}`;
23
- }
24
- /** The site secret for the proxy handler. */
25
- function findSecret() {
26
- if (typeof process === "undefined") return;
27
- return process.env.HIGHSEAT_SECRET;
28
- }
29
- /**
30
- * Whether this runs inside `next build`, which loads every route without serving one. Set in the
31
- * build's route workers only: `next.config.ts` receives the phase as an argument instead.
32
- */
33
- function isNextBuild() {
34
- if (typeof process === "undefined") return false;
35
- return process.env.NEXT_PHASE === "phase-production-build";
36
- }
37
- //#endregion
38
- //#region src/proxy.ts
39
- const DEFAULT_UPSTREAM = "https://cdn.highseat.com";
40
- const SECRET_PREFIXES = [
41
- "hs_secret_",
42
- "hs_proxy_",
43
- "ana_proxy_"
44
- ];
45
- const CLIENT_IP_HEADERS = {
46
- vercel: "x-real-ip",
47
- cloudflare: "cf-connecting-ip",
48
- netlify: "x-nf-client-connection-ip",
49
- nginx: "x-real-ip"
50
- };
51
- const SCRIPT_REQUEST_HEADERS = ["user-agent", "if-none-match"];
52
- const EVENT_REQUEST_HEADERS = [
53
- "content-type",
54
- "user-agent",
55
- "origin"
56
- ];
57
- const RESPONSE_HEADERS = [
58
- "content-type",
59
- "etag",
60
- "cache-control",
61
- "vary",
62
- "retry-after",
63
- "x-hs-ip",
64
- "x-hs-ip-source"
65
- ];
66
- const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([
67
- 101,
68
- 204,
69
- 205,
70
- 304
71
- ]);
72
- const UPSTREAM_TIMEOUT_MS = 1e4;
73
- const MAX_EVENT_BYTES = 524288;
74
- function getClientIpReader(clientIp) {
75
- if (typeof clientIp === "function") return {
76
- read: (request) => clientIp(request)?.trim() ?? "",
77
- source: "the clientIp function"
78
- };
79
- const header = CLIENT_IP_HEADERS[clientIp];
80
- if (!header) throw new Error(`highseat/proxy: unknown clientIp preset "${String(clientIp)}".`);
81
- return {
82
- read: (request) => request.headers.get(header)?.trim() ?? "",
83
- source: `the "${clientIp}" preset's ${header} header`
84
- };
85
- }
86
- function copyHeaders(from, to, names) {
87
- for (const name of names) {
88
- const value = from.get(name);
89
- if (value !== null) to.set(name, value);
90
- }
91
- }
92
- function answerError(status, error) {
93
- return Response.json({ error }, {
94
- status,
95
- headers: { "cache-control": "no-store" }
96
- });
97
- }
98
- function answerOtherPath() {
99
- return answerError(404, "Not the proxy path. The Highseat proxy answers on its own path only.");
100
- }
101
- /** The site secret, or `undefined` when none is set. Throws on a value that is not one. */
102
- function findValidSecret(option) {
103
- const secret = option ?? findSecret();
104
- if (!secret) return;
105
- if (!SECRET_PREFIXES.some((prefix) => secret.startsWith(prefix))) throw new Error(`highseat/proxy: not a site secret. Copy it from the site's Installation settings; it starts with "${SECRET_PREFIXES[0]}".`);
106
- return secret;
107
- }
108
- let hasWarnedMissing = false;
109
- /**
110
- * The handler for a proxy missing a variable: every request goes to `fallback`, or the proxy
111
- * path answers 503 naming what is missing.
112
- */
113
- function createDisabledProxy(missing, path, fallback) {
114
- const names = missing.join(" and ");
115
- if (!hasWarnedMissing && !isNextBuild()) {
116
- hasWarnedMissing = true;
117
- console.warn(`highseat/proxy: ${names} not set, so the proxy is off and ${fallback ? "every request goes to `fallback`" : "the proxy path answers 503"}.`);
118
- }
119
- return async function proxy(request) {
120
- if (fallback) return fallback(request);
121
- if (path !== void 0 && new URL(request.url).pathname !== path) return answerOtherPath();
122
- return answerError(503, `The Highseat proxy is off: set ${names}.`);
123
- };
124
- }
125
- /** The request body, or `undefined` once it passes `MAX_EVENT_BYTES`. */
126
- async function readEventBody(request) {
127
- if (Number(request.headers.get("content-length")) > MAX_EVENT_BYTES) return;
128
- if (!request.body) return /* @__PURE__ */ new Uint8Array();
129
- const reader = request.body.getReader();
130
- const chunks = [];
131
- let size = 0;
132
- for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
133
- size += chunk.value.byteLength;
134
- if (size > MAX_EVENT_BYTES) {
135
- reader.cancel();
136
- return;
137
- }
138
- chunks.push(chunk.value);
139
- }
140
- const body = new Uint8Array(size);
141
- let offset = 0;
142
- for (const chunk of chunks) {
143
- body.set(chunk, offset);
144
- offset += chunk.byteLength;
145
- }
146
- return body;
147
- }
148
- /**
149
- * Creates the first-party proxy handler for a site. A GET serves the tracker script and a POST
150
- * forwards its events, both to the ingest host, with the site secret and the visitor's IP. The
151
- * returned function takes a `Request` and returns a `Response`, so it mounts as a Next.js route
152
- * handler, a Cloudflare Worker, a Pages Function, a Netlify or Vercel function, an Astro
153
- * endpoint or a Hono route.
154
- *
155
- * A missing path or secret never throws: the handler passes every request to `fallback`, or
156
- * answers the proxy path with a 503 naming the variable, and warns once. A value that is not a
157
- * site secret throws, since that is a copying mistake rather than a variable left unset.
158
- */
159
- function createProxy(options) {
160
- const path = findProxyPath(options.path);
161
- const { fallback } = options;
162
- let foundSecret;
163
- try {
164
- foundSecret = findValidSecret(options.secret);
165
- } catch (error) {
166
- if (!isNextBuild()) throw error;
167
- return () => Promise.reject(error);
168
- }
169
- const upstream = new URL(options.upstream ?? DEFAULT_UPSTREAM).origin;
170
- const missing = [...fallback && path === void 0 ? ["HIGHSEAT_PATH"] : [], ...foundSecret ? [] : ["HIGHSEAT_SECRET"]];
171
- if (!foundSecret || missing.length) return createDisabledProxy(missing, path, fallback);
172
- const secret = foundSecret;
173
- const clientIpReader = getClientIpReader(options.clientIp);
174
- let hasWarnedNoIp = false;
175
- function readClientIp(request) {
176
- const ip = clientIpReader.read(request);
177
- if (!ip && !hasWarnedNoIp) {
178
- hasWarnedNoIp = true;
179
- console.warn(`highseat/proxy: no visitor IP in ${clientIpReader.source}, so Highseat refuses every event. Set clientIp to the outermost proxy in front of this server.`);
180
- }
181
- return ip;
182
- }
183
- function buildUpstreamHeaders(request, names) {
184
- const headers = new Headers({
185
- "accept-encoding": "identity",
186
- "x-hs-secret": secret,
187
- "x-hs-client-ip": readClientIp(request)
188
- });
189
- copyHeaders(request.headers, headers, names);
190
- return headers;
191
- }
192
- async function forward(url, init) {
193
- let response;
194
- try {
195
- response = await fetch(url, {
196
- ...init,
197
- signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)
198
- });
199
- } catch {
200
- return answerError(502, "Highseat is unreachable from this proxy.");
201
- }
202
- const headers = new Headers();
203
- copyHeaders(response.headers, headers, RESPONSE_HEADERS);
204
- if (init.method === "POST") headers.set("cache-control", "no-store");
205
- const body = NULL_BODY_STATUSES.has(response.status) ? null : response.body;
206
- return new Response(body, {
207
- status: response.status,
208
- headers
209
- });
210
- }
211
- return async function proxy(request) {
212
- if (path !== void 0 && new URL(request.url).pathname !== path) return fallback ? fallback(request) : answerOtherPath();
213
- if (request.method === "GET" || request.method === "HEAD") return forward(`${upstream}/script.js`, {
214
- method: request.method,
215
- headers: buildUpstreamHeaders(request, SCRIPT_REQUEST_HEADERS)
216
- });
217
- if (request.method === "POST") {
218
- const body = await readEventBody(request);
219
- if (!body) return answerError(413, "The event batch is too large.");
220
- return forward(`${upstream}/api/event`, {
221
- method: "POST",
222
- headers: buildUpstreamHeaders(request, EVENT_REQUEST_HEADERS),
223
- body
224
- });
225
- }
226
- return new Response(null, {
227
- status: 405,
228
- headers: { allow: "GET, HEAD, POST" }
229
- });
230
- };
231
- }
232
- //#endregion
233
- export { findNextSite as n, findProxyPath as r, createProxy as t };
234
-
235
- //# sourceMappingURL=proxy2.js.map
package/proxy2.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"proxy2.js","names":[],"sources":["../src/env.ts","../src/proxy.ts"],"sourcesContent":["/**\n * The variables the package reads from a customer's environment. Each is named in full, never\n * looked up by a computed key: Next.js inlines a `NEXT_PUBLIC_` variable into browser code only\n * where the source spells out `process.env.NEXT_PUBLIC_…`. The server variables return\n * `undefined` where the runtime has no `process`: a Cloudflare Worker without `nodejs_compat`,\n * whose options carry the values instead.\n */\n\n/** The site id for `<Highseat />` in Next.js. Public, so it reaches the browser. */\nexport function findNextSite(): string | undefined {\n return process.env.NEXT_PUBLIC_HIGHSEAT_SITE\n}\n\n/**\n * The site's proxy path: `option` when given, else `HIGHSEAT_PATH`, a server variable shared by\n * `<Highseat />`, `withHighseat()` and the proxy handler. A value written without its leading\n * slash gets one, as Installation settings shows it (`/3f9a0c1e2b`). An empty value counts as\n * unset.\n */\nexport function findProxyPath(option?: string): string | undefined {\n const path = option ?? (typeof process === \"undefined\" ? undefined : process.env.HIGHSEAT_PATH)\n if (!path) return\n return path.startsWith(\"/\") ? path : `/${path}`\n}\n\n/** The site secret for the proxy handler. */\nexport function findSecret(): string | undefined {\n if (typeof process === \"undefined\") return\n return process.env.HIGHSEAT_SECRET\n}\n\n/**\n * Whether this runs inside `next build`, which loads every route without serving one. Set in the\n * build's route workers only: `next.config.ts` receives the phase as an argument instead.\n */\nexport function isNextBuild(): boolean {\n if (typeof process === \"undefined\") return false\n return process.env.NEXT_PHASE === \"phase-production-build\"\n}\n","import { findProxyPath, findSecret, isNextBuild } from \"./env\"\n\n/** A host whose own header carries the visitor's IP. */\nexport type ClientIpPreset = \"vercel\" | \"cloudflare\" | \"netlify\" | \"nginx\"\n\n/**\n * Where the proxy reads the visitor's IP: a host preset, or a function for any other setup. A\n * function returns the IP, or nothing when the request carries none.\n */\nexport type ClientIp = ClientIpPreset | ((request: Request) => string | null | undefined)\n\nexport interface ProxyOptions {\n /**\n * The site's proxy path from Installation settings, such as `/3f9a0c1e2b`, with or without its\n * leading slash. A request on any\n * other path is answered 404, or handed to `fallback`. Defaults to the `HIGHSEAT_PATH`\n * environment variable. Leave both unset on a host whose router already sends only the proxy\n * path here, such as a file named after the path.\n */\n path?: string\n /**\n * The site secret, `hs_secret_…`, or an older one that starts `hs_proxy_` or `ana_proxy_`.\n * Defaults to the `HIGHSEAT_SECRET` environment variable. Without one the proxy is off: the\n * proxy path answers 503, or every request goes to `fallback`.\n */\n secret?: string\n /**\n * Where the visitor's IP comes from: `vercel`, `cloudflare`, `netlify`, `nginx` (the\n * `X-Real-IP` header your nginx sets), or a function. A visitor can write any header the host\n * does not overwrite, so there is no default.\n *\n * The outermost proxy that sets the header decides the preset. Behind a proxied Cloudflare\n * record, use `cloudflare` on any origin, not only a Worker or a Pages Function: a Next.js,\n * TanStack Start or Node server behind Cloudflare, with or without Traefik or nginx in between,\n * sees a Cloudflare edge address in `X-Real-IP`, and the visitor's IP in `cf-connecting-ip`.\n */\n clientIp: ClientIp\n /** The ingest origin the proxy forwards to. Defaults to `https://cdn.highseat.com`. */\n upstream?: string\n /**\n * Answers a request on any path other than `path`, for a handler that sees every request on\n * the site: `fetch` in a Cloudflare Worker routed on the whole site, `next` in a Pages\n * Function. Needs `path`: without it, or without the secret, the proxy is off and every\n * request goes here, so the site still serves in a development setup without the variables.\n */\n fallback?: (request: Request) => Response | Promise<Response>\n}\n\n/** A fetch handler, the shape every supported runtime and framework route accepts. */\nexport type ProxyHandler = (request: Request) => Promise<Response>\n\nconst DEFAULT_UPSTREAM = \"https://cdn.highseat.com\"\n// The current prefix first. Ingest still accepts the secrets minted under the older two, so a\n// site keeps its secret when it moves to this handler.\nconst SECRET_PREFIXES = [\"hs_secret_\", \"hs_proxy_\", \"ana_proxy_\"]\n\nconst CLIENT_IP_HEADERS: Record<ClientIpPreset, string> = {\n vercel: \"x-real-ip\",\n // Read from the inbound request: Cloudflare overwrites it on the Worker's own subrequest.\n cloudflare: \"cf-connecting-ip\",\n netlify: \"x-nf-client-connection-ip\",\n nginx: \"x-real-ip\",\n}\n\n// The visitor headers each direction forwards. Copied by name, so a cookie, an `Authorization`\n// header or a visitor's own `x-hs-*` header never reaches ingest.\nconst SCRIPT_REQUEST_HEADERS = [\"user-agent\", \"if-none-match\"]\nconst EVENT_REQUEST_HEADERS = [\"content-type\", \"user-agent\", \"origin\"]\n\n// The upstream headers the response keeps. Rebuilt by name because Node, Bun and Deno hand back\n// a decompressed body under the original `content-encoding` and `content-length`, which would\n// describe bytes this handler no longer has. `x-hs-ip` and `x-hs-ip-source` show which IP\n// ingest resolved, for `curl -i` against the proxy path.\nconst RESPONSE_HEADERS = [\n \"content-type\",\n \"etag\",\n \"cache-control\",\n \"vary\",\n \"retry-after\",\n \"x-hs-ip\",\n \"x-hs-ip-source\",\n]\n\n// Statuses whose response must not carry a body, which the Response constructor enforces.\nconst NULL_BODY_STATUSES = new Set([101, 204, 205, 304])\n\nconst UPSTREAM_TIMEOUT_MS = 10_000\n\n// Ingest refuses a larger batch, so a bigger body is answered here without buffering the rest.\nconst MAX_EVENT_BYTES = 512 * 1024\n\ninterface ClientIpReader {\n read: (request: Request) => string\n /** Where `read` looks, for the warning about an empty IP. */\n source: string\n}\n\nfunction getClientIpReader(clientIp: ClientIp): ClientIpReader {\n if (typeof clientIp === \"function\") {\n return { read: request => clientIp(request)?.trim() ?? \"\", source: \"the clientIp function\" }\n }\n\n const header = CLIENT_IP_HEADERS[clientIp]\n if (!header) throw new Error(`highseat/proxy: unknown clientIp preset \"${String(clientIp)}\".`)\n return {\n read: request => request.headers.get(header)?.trim() ?? \"\",\n source: `the \"${clientIp}\" preset's ${header} header`,\n }\n}\n\nfunction copyHeaders(from: Headers, to: Headers, names: string[]) {\n for (const name of names) {\n const value = from.get(name)\n if (value !== null) to.set(name, value)\n }\n}\n\nfunction answerError(status: number, error: string) {\n return Response.json({ error }, { status, headers: { \"cache-control\": \"no-store\" } })\n}\n\n// A JSON body rather than an empty 404, so `curl -i` on the route handler's own URL tells this\n// answer apart from ingest's.\nfunction answerOtherPath() {\n return answerError(404, \"Not the proxy path. The Highseat proxy answers on its own path only.\")\n}\n\n/** The site secret, or `undefined` when none is set. Throws on a value that is not one. */\nfunction findValidSecret(option: string | undefined): string | undefined {\n const secret = option ?? findSecret()\n if (!secret) return\n\n if (!SECRET_PREFIXES.some(prefix => secret.startsWith(prefix))) {\n throw new Error(\n `highseat/proxy: not a site secret. Copy it from the site's Installation settings; it starts with \"${SECRET_PREFIXES[0]}\".`,\n )\n }\n return secret\n}\n\n// The handler can be created per request (a Worker that reads its options from `env`), so a\n// missing variable is reported once per process rather than once per handler.\nlet hasWarnedMissing = false\n\n/**\n * The handler for a proxy missing a variable: every request goes to `fallback`, or the proxy\n * path answers 503 naming what is missing.\n */\nfunction createDisabledProxy(\n missing: string[],\n path: string | undefined,\n fallback: ProxyOptions[\"fallback\"],\n): ProxyHandler {\n const names = missing.join(\" and \")\n\n // A Next.js build loads every route without serving one, often without the runtime variables.\n if (!hasWarnedMissing && !isNextBuild()) {\n hasWarnedMissing = true\n const outcome = fallback ? \"every request goes to `fallback`\" : \"the proxy path answers 503\"\n console.warn(`highseat/proxy: ${names} not set, so the proxy is off and ${outcome}.`)\n }\n\n return async function proxy(request) {\n if (fallback) return fallback(request)\n if (path !== undefined && new URL(request.url).pathname !== path) return answerOtherPath()\n return answerError(503, `The Highseat proxy is off: set ${names}.`)\n }\n}\n\n/** The request body, or `undefined` once it passes `MAX_EVENT_BYTES`. */\nasync function readEventBody(request: Request): Promise<Uint8Array<ArrayBuffer> | undefined> {\n if (Number(request.headers.get(\"content-length\")) > MAX_EVENT_BYTES) return\n if (!request.body) return new Uint8Array()\n\n const reader = request.body.getReader()\n const chunks: Uint8Array[] = []\n let size = 0\n\n for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {\n size += chunk.value.byteLength\n if (size > MAX_EVENT_BYTES) {\n void reader.cancel()\n return\n }\n chunks.push(chunk.value)\n }\n\n const body = new Uint8Array(size)\n let offset = 0\n for (const chunk of chunks) {\n body.set(chunk, offset)\n offset += chunk.byteLength\n }\n return body\n}\n\n/**\n * Creates the first-party proxy handler for a site. A GET serves the tracker script and a POST\n * forwards its events, both to the ingest host, with the site secret and the visitor's IP. The\n * returned function takes a `Request` and returns a `Response`, so it mounts as a Next.js route\n * handler, a Cloudflare Worker, a Pages Function, a Netlify or Vercel function, an Astro\n * endpoint or a Hono route.\n *\n * A missing path or secret never throws: the handler passes every request to `fallback`, or\n * answers the proxy path with a 503 naming the variable, and warns once. A value that is not a\n * site secret throws, since that is a copying mistake rather than a variable left unset.\n */\nexport function createProxy(options: ProxyOptions): ProxyHandler {\n const path = findProxyPath(options.path)\n const { fallback } = options\n let foundSecret: string | undefined\n\n try {\n foundSecret = findValidSecret(options.secret)\n } catch (error) {\n // Next.js loads every route while it builds, so there the error waits for the first request\n // rather than failing a build that never serves one.\n if (!isNextBuild()) throw error\n return () => Promise.reject(error)\n }\n\n const upstream = new URL(options.upstream ?? DEFAULT_UPSTREAM).origin\n\n // Without a secret, ingest would read every visitor as this server and drop it as datacenter\n // traffic. Without a path, a handler that sees every request cannot tell the proxy's apart.\n const missing = [\n ...(fallback && path === undefined ? [\"HIGHSEAT_PATH\"] : []),\n ...(foundSecret ? [] : [\"HIGHSEAT_SECRET\"]),\n ]\n if (!foundSecret || missing.length) return createDisabledProxy(missing, path, fallback)\n\n const secret = foundSecret\n\n const clientIpReader = getClientIpReader(options.clientIp)\n let hasWarnedNoIp = false\n\n // Ingest answers 400 to every event without a visitor IP and says nothing about the preset,\n // so the first request without one names the source it read.\n function readClientIp(request: Request) {\n const ip = clientIpReader.read(request)\n\n if (!ip && !hasWarnedNoIp) {\n hasWarnedNoIp = true\n console.warn(\n `highseat/proxy: no visitor IP in ${clientIpReader.source}, so Highseat refuses every event. Set clientIp to the outermost proxy in front of this server.`,\n )\n }\n return ip\n }\n\n function buildUpstreamHeaders(request: Request, names: string[]) {\n const headers = new Headers({\n // The response never copies `content-encoding`, so ingest is asked for a plain body.\n \"accept-encoding\": \"identity\",\n \"x-hs-secret\": secret,\n \"x-hs-client-ip\": readClientIp(request),\n })\n copyHeaders(request.headers, headers, names)\n return headers\n }\n\n async function forward(url: string, init: RequestInit) {\n let response: Response\n\n try {\n response = await fetch(url, { ...init, signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS) })\n } catch {\n return answerError(502, \"Highseat is unreachable from this proxy.\")\n }\n\n const headers = new Headers()\n copyHeaders(response.headers, headers, RESPONSE_HEADERS)\n if (init.method === \"POST\") headers.set(\"cache-control\", \"no-store\")\n\n const body = NULL_BODY_STATUSES.has(response.status) ? null : response.body\n return new Response(body, { status: response.status, headers })\n }\n\n return async function proxy(request) {\n if (path !== undefined && new URL(request.url).pathname !== path) {\n return fallback ? fallback(request) : answerOtherPath()\n }\n\n if (request.method === \"GET\" || request.method === \"HEAD\") {\n return forward(`${upstream}/script.js`, {\n method: request.method,\n headers: buildUpstreamHeaders(request, SCRIPT_REQUEST_HEADERS),\n })\n }\n\n if (request.method === \"POST\") {\n const body = await readEventBody(request)\n if (!body) return answerError(413, \"The event batch is too large.\")\n\n return forward(`${upstream}/api/event`, {\n method: \"POST\",\n headers: buildUpstreamHeaders(request, EVENT_REQUEST_HEADERS),\n body,\n })\n }\n\n return new Response(null, { status: 405, headers: { allow: \"GET, HEAD, POST\" } })\n }\n}\n"],"mappings":";;;;;;;;;AASA,SAAgB,eAAmC;CACjD,OAAO,QAAQ,IAAI;AACrB;;;;;;;AAQA,SAAgB,cAAc,QAAqC;CACjE,MAAM,OAAO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QAAQ,KAAa,MAAmB;EACrD,IAAI;EAEJ,IAAI;GACF,WAAW,MAAM,MAAM,KAAK;IAAE,GAAG;IAAM,QAAQ,YAAY,QAAQ,mBAAmB;GAAE,CAAC;EAC3F,QAAQ;GACN,OAAO,YAAY,KAAK,0CAA0C;EACpE;EAEA,MAAM,UAAU,IAAI,QAAQ;EAC5B,YAAY,SAAS,SAAS,SAAS,gBAAgB;EACvD,IAAI,KAAK,WAAW,QAAQ,QAAQ,IAAI,iBAAiB,UAAU;EAEnE,MAAM,OAAO,mBAAmB,IAAI,SAAS,MAAM,IAAI,OAAO,SAAS;EACvE,OAAO,IAAI,SAAS,MAAM;GAAE,QAAQ,SAAS;GAAQ;EAAQ,CAAC;CAChE;CAEA,OAAO,eAAe,MAAM,SAAS;EACnC,IAAI,SAAS,KAAA,KAAa,IAAI,IAAI,QAAQ,GAAG,CAAC,CAAC,aAAa,MAC1D,OAAO,WAAW,SAAS,OAAO,IAAI,gBAAgB;EAGxD,IAAI,QAAQ,WAAW,SAAS,QAAQ,WAAW,QACjD,OAAO,QAAQ,GAAG,SAAS,aAAa;GACtC,QAAQ,QAAQ;GAChB,SAAS,qBAAqB,SAAS,sBAAsB;EAC/D,CAAC;EAGH,IAAI,QAAQ,WAAW,QAAQ;GAC7B,MAAM,OAAO,MAAM,cAAc,OAAO;GACxC,IAAI,CAAC,MAAM,OAAO,YAAY,KAAK,+BAA+B;GAElE,OAAO,QAAQ,GAAG,SAAS,aAAa;IACtC,QAAQ;IACR,SAAS,qBAAqB,SAAS,qBAAqB;IAC5D;GACF,CAAC;EACH;EAEA,OAAO,IAAI,SAAS,MAAM;GAAE,QAAQ;GAAK,SAAS,EAAE,OAAO,kBAAkB;EAAE,CAAC;CAClF;AACF"}
package/react2.js DELETED
@@ -1,64 +0,0 @@
1
- import { identify, inject } from "./index.js";
2
- import { useEffect, useRef } from "react";
3
- //#region src/identity.ts
4
- /**
5
- * Identifies `userId` when it differs from `previous`, the id identified last, and returns the id
6
- * identified now. `undefined` means the session has not loaded, so it changes nothing and keeps
7
- * `previous`: a session that reloads with the same user calls `identify` once, not twice.
8
- */
9
- function syncIdentity(previous, userId) {
10
- if (userId === void 0 || userId === previous) return previous;
11
- identify(userId);
12
- return userId;
13
- }
14
- //#endregion
15
- //#region src/react.ts
16
- /**
17
- * Keeps the visitor's user id in step with a session. Each new value is passed to `identify`
18
- * once: an id identifies the visitor, `null` clears the id at sign-out or session expiry, and
19
- * `undefined`, a session still loading, changes nothing. Works in any client component, with or
20
- * without `<Highseat />` on the page, and before the tracker has loaded.
21
- *
22
- * Tell loading apart from signed out: `useIdentify(session?.user.id)` passes `undefined` after
23
- * sign-out too, so it never clears the id.
24
- *
25
- * ```tsx
26
- * const { data, isPending } = useSession()
27
- * useIdentify(isPending ? undefined : (data?.user.id ?? null))
28
- * ```
29
- */
30
- function useIdentify(userId) {
31
- const identified = useRef(void 0);
32
- useEffect(() => {
33
- identified.current = syncIdentity(identified.current, userId);
34
- }, [userId]);
35
- }
36
- /**
37
- * Loads the Highseat tracker. Render it once, in the root layout. It adds the script tag after
38
- * the page mounts and renders nothing; mounting it again adds no second tag, and the tracker
39
- * counts client-side navigation on its own. With `userId`, it also identifies the visitor, as
40
- * {@link useIdentify} does.
41
- */
42
- function Highseat({ site, src, outbound, downloads, hashRouting, userId }) {
43
- useEffect(() => {
44
- inject({
45
- site,
46
- src,
47
- outbound,
48
- downloads,
49
- hashRouting
50
- });
51
- }, [
52
- site,
53
- src,
54
- outbound,
55
- downloads,
56
- hashRouting
57
- ]);
58
- useIdentify(userId);
59
- return null;
60
- }
61
- //#endregion
62
- export { useIdentify as n, Highseat as t };
63
-
64
- //# sourceMappingURL=react2.js.map
package/react2.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"react2.js","names":[],"sources":["../src/identity.ts","../src/react.ts"],"sourcesContent":["import { identify, type UserId } from \"./index\"\n\n/**\n * Identifies `userId` when it differs from `previous`, the id identified last, and returns the id\n * identified now. `undefined` means the session has not loaded, so it changes nothing and keeps\n * `previous`: a session that reloads with the same user calls `identify` once, not twice.\n */\nexport function syncIdentity(previous: UserId, userId: UserId): UserId {\n if (userId === undefined || userId === previous) return previous\n identify(userId)\n return userId\n}\n","\"use client\"\n\nimport { useEffect, useRef } from \"react\"\nimport { syncIdentity } from \"./identity\"\nimport { inject, type InjectOptions, type UserId } from \"./index\"\n\nexport interface HighseatProps extends InjectOptions {\n /**\n * The signed-in user's id from your own system, never an email or other personal data. Pass\n * `null` once the visitor is signed out, and `undefined` while the session is still loading.\n * See {@link useIdentify}.\n */\n userId?: UserId\n}\n\n/**\n * Keeps the visitor's user id in step with a session. Each new value is passed to `identify`\n * once: an id identifies the visitor, `null` clears the id at sign-out or session expiry, and\n * `undefined`, a session still loading, changes nothing. Works in any client component, with or\n * without `<Highseat />` on the page, and before the tracker has loaded.\n *\n * Tell loading apart from signed out: `useIdentify(session?.user.id)` passes `undefined` after\n * sign-out too, so it never clears the id.\n *\n * ```tsx\n * const { data, isPending } = useSession()\n * useIdentify(isPending ? undefined : (data?.user.id ?? null))\n * ```\n */\nexport function useIdentify(userId: UserId): void {\n // The id this component identified last. A ref survives Strict Mode's second effect run, so\n // the same id is never sent twice.\n const identified = useRef<UserId>(undefined)\n\n useEffect(() => {\n identified.current = syncIdentity(identified.current, userId)\n }, [userId])\n}\n\n/**\n * Loads the Highseat tracker. Render it once, in the root layout. It adds the script tag after\n * the page mounts and renders nothing; mounting it again adds no second tag, and the tracker\n * counts client-side navigation on its own. With `userId`, it also identifies the visitor, as\n * {@link useIdentify} does.\n */\nexport function Highseat({\n site,\n src,\n outbound,\n downloads,\n hashRouting,\n userId,\n}: HighseatProps): null {\n useEffect(() => {\n inject({ site, src, outbound, downloads, hashRouting })\n }, [site, src, outbound, downloads, hashRouting])\n\n useIdentify(userId)\n\n return null\n}\n"],"mappings":";;;;;;;;AAOA,SAAgB,aAAa,UAAkB,QAAwB;CACrE,IAAI,WAAW,KAAA,KAAa,WAAW,UAAU,OAAO;CACxD,SAAS,MAAM;CACf,OAAO;AACT;;;;;;;;;;;;;;;;;ACkBA,SAAgB,YAAY,QAAsB;CAGhD,MAAM,aAAa,OAAe,KAAA,CAAS;CAE3C,gBAAgB;EACd,WAAW,UAAU,aAAa,WAAW,SAAS,MAAM;CAC9D,GAAG,CAAC,MAAM,CAAC;AACb;;;;;;;AAQA,SAAgB,SAAS,EACvB,MACA,KACA,UACA,WACA,aACA,UACsB;CACtB,gBAAgB;EACd,OAAO;GAAE;GAAM;GAAK;GAAU;GAAW;EAAY,CAAC;CACxD,GAAG;EAAC;EAAM;EAAK;EAAU;EAAW;CAAW,CAAC;CAEhD,YAAY,MAAM;CAElB,OAAO;AACT"}