@punchline-analytics/next 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 OpsScale
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,82 @@
1
- # Temporary Holding Version
1
+ # @punchline-analytics/next
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Shows how much of your site's traffic is AI agents, and which ones. This package runs in your Next.js proxy (or middleware), and for each page request it sends a small event to your Punchline Analytics collector, after the response has gone out.
4
+
5
+ - **No cookies, no browser script, nothing added to your pages.**
6
+ - **Doesn't slow pages down.** The event is sent after the response; our code adds about 1 ms.
7
+ - **Never breaks your site.** If Punchline is misconfigured or unreachable, requests continue normally.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install @punchline-analytics/next
13
+ ```
14
+
15
+ Set one environment variable (your Punchline Analytics dashboard gives you the value):
16
+
17
+ ```bash
18
+ PUNCHLINE_DSN=https://<site-id>:<secret>@<your-collector>/api/collect
19
+ ```
20
+
21
+ **Next.js 16:** create `proxy.ts` at the project root, or in `src/` if you use one:
22
+
23
+ ```ts
24
+ import { punchline } from "@punchline-analytics/next";
25
+
26
+ export const proxy = punchline();
27
+
28
+ export const config = {
29
+ matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
30
+ };
31
+ ```
32
+
33
+ **Next.js 15, or to run on the edge runtime:** use `middleware.ts` with `export const middleware = punchline();` and the same `config`.
34
+
35
+ Next.js reads `matcher` at build time, so it has to be written out in your file as shown.
36
+
37
+ ## Already have a proxy or middleware?
38
+
39
+ Call the tracker inside it:
40
+
41
+ ```ts
42
+ import { createTracker } from "@punchline-analytics/next";
43
+ import { NextResponse, type NextFetchEvent, type NextRequest } from "next/server";
44
+
45
+ const tracker = createTracker();
46
+
47
+ export function proxy(request: NextRequest, event: NextFetchEvent) {
48
+ tracker.track(request, event);
49
+ // …your existing logic…
50
+ return NextResponse.next();
51
+ }
52
+ ```
53
+
54
+ ## What gets sent
55
+
56
+ For each page view (`GET`/`HEAD` for pages, plus `.txt`, `.md` and `.xml` files such as `robots.txt` and `llms.txt`), the package sends one event, server to server:
57
+
58
+ - The host, the path and `utm_*` values. Every other query parameter, and the `#fragment`, are removed before sending.
59
+ - The referrer's host only.
60
+ - The `Accept` header, cut to 200 characters.
61
+ - Whether the browser sent `Sec-GPC: 1`.
62
+ - The country code your host provides (`x-vercel-ip-country` on Vercel).
63
+ - Web Bot Auth signature headers, when an agent sends them.
64
+ - The visitor's IP address and user agent. The collector uses these in memory to classify the request and to compute a daily visitor hash, then discards them; they're never stored or logged.
65
+
66
+ Not tracked: images, scripts, styles, other assets, or Next.js link prefetches.
67
+
68
+ ## Options
69
+
70
+ ```ts
71
+ punchline({
72
+ dsn: "...", // default: process.env.PUNCHLINE_DSN
73
+ timeoutMs: 3000, // give up sending after this long
74
+ serverTiming: true, // add `Server-Timing: punchline;dur=…` (default: PUNCHLINE_SERVER_TIMING=1)
75
+ onError: (err) => {}, // configuration or network errors (default: ignored)
76
+ });
77
+ ```
78
+
79
+ ## Troubleshooting
80
+
81
+ - **No events arriving.** Check `PUNCHLINE_DSN` is set for the environment you deployed. Pass `onError: console.error` once to see why sends are failing.
82
+ - **Measuring the overhead.** Set `PUNCHLINE_SERVER_TIMING=1` and look at the `Server-Timing` response header.
@@ -0,0 +1,111 @@
1
+ import { NextRequest, NextFetchEvent, NextResponse } from 'next/server.js';
2
+
3
+ /**
4
+ * The event sent to the collector. Declared here so the published packages'
5
+ * types are self-contained; the check below fails the build if it ever stops
6
+ * matching @punchline/schema's EdgeEvent exactly.
7
+ */
8
+ interface EdgeEvent {
9
+ v: 1;
10
+ siteId: string;
11
+ ts: number;
12
+ method: string;
13
+ host: string;
14
+ path: string;
15
+ utm: Partial<Record<"source" | "medium" | "campaign" | "term" | "content", string>>;
16
+ referrerHost: string | null;
17
+ status: number | null;
18
+ bytes?: number | null;
19
+ params?: Record<string, string>;
20
+ format?: "markdown";
21
+ handoff?: string;
22
+ mintedHandoff?: string;
23
+ clicks?: Record<string, string>;
24
+ accept: string | null;
25
+ query?: string;
26
+ visitorId?: string;
27
+ consent?: true;
28
+ ip: string;
29
+ userAgent: string;
30
+ gpc: boolean;
31
+ country?: string | null;
32
+ signatureHeaders?: {
33
+ signature?: string;
34
+ signatureInput?: string;
35
+ signatureAgent?: string;
36
+ };
37
+ vercelSignals?: Record<string, string>;
38
+ platformSignals?: Record<string, string>;
39
+ }
40
+ /** What only the hosting platform knows about a request. */
41
+ interface RequestFacts {
42
+ ip: string;
43
+ /** ISO 3166-1 alpha-2, or null. */
44
+ country: string | null;
45
+ vercelSignals?: Record<string, string>;
46
+ platformSignals?: Record<string, string>;
47
+ }
48
+ interface Dsn {
49
+ collectorUrl: string;
50
+ siteId: string;
51
+ secret: string;
52
+ }
53
+ interface TrackResult {
54
+ /** Time spent on the request path, or null if the request wasn't tracked. */
55
+ overheadMs: number | null;
56
+ /**
57
+ * A Set-Cookie value for the response: a new visitor cookie, or one that
58
+ * clears it (Global Privacy Control, or the site stopped remembering this
59
+ * visitor). Only when the site remembers visitors (its visitor modes).
60
+ */
61
+ setCookie?: string;
62
+ }
63
+ /** On Vercel, x-forwarded-for is set by the platform to the real client IP. */
64
+ declare function readVercelFacts(request: Request): RequestFacts;
65
+ /** https://<siteId>:<secret>@<host>/<path>. http is allowed only for localhost. */
66
+ declare function parseDsn(raw: string): Dsn;
67
+ /**
68
+ * Server-Timing entry an install adds to a response it counted. The snippet
69
+ * reads it (PerformanceNavigationTiming.serverTiming) and skips its own page
70
+ * view for that load: no identifier, so it works for GPC visitors too, who
71
+ * have no visitor hash for the collector to deduplicate on.
72
+ */
73
+ declare const COUNTED_TIMING = "punchline-pv";
74
+ declare function shouldTrack(request: Request): boolean;
75
+
76
+ interface PunchlineOptions {
77
+ /** Defaults to process.env.PUNCHLINE_DSN (AGENTLENS_DSN, the pre-rename name, still works). */
78
+ dsn?: string;
79
+ /** Abort the forward after this long. Default 3000 ms. */
80
+ timeoutMs?: number;
81
+ /** Add `Server-Timing: punchline;dur=…` to responses. Default: PUNCHLINE_SERVER_TIMING=1. */
82
+ serverTiming?: boolean;
83
+ /** Called on configuration or network errors. Default: ignore. */
84
+ onError?: (err: unknown) => void;
85
+ }
86
+ declare const INTERNAL_HEADER = "x-punchline-internal";
87
+ /** A ready-made proxy function. */
88
+ declare function punchline(options?: PunchlineOptions): (request: NextRequest, event: NextFetchEvent) => Promise<NextResponse>;
89
+ /** For sites with their own proxy: call `track(request, event)` inside it. */
90
+ declare function createTracker(options?: PunchlineOptions): {
91
+ serverTiming: boolean;
92
+ /**
93
+ * Returns the time spent on the request path (null if it wasn't tracked),
94
+ * and a Set-Cookie value to add to the response when the site remembers
95
+ * visitors (a new visitor cookie, or one that clears it).
96
+ */
97
+ track(request: NextRequest, event: Pick<NextFetchEvent, "waitUntil">): TrackResult;
98
+ /** Whether "Serve AI agents markdown" is on for this site (off until the settings load). */
99
+ markdownOn(event: Pick<NextFetchEvent, "waitUntil">): boolean;
100
+ /** The proxy's own HTML fetch for a markdown answer. */
101
+ isInternal(request: Request): Promise<boolean>;
102
+ /**
103
+ * The markdown answer for an AI agent (or a .md / text/markdown request),
104
+ * tracked as the page with format markdown; null to carry on as usual.
105
+ */
106
+ serveMarkdown(request: NextRequest, event: Pick<NextFetchEvent, "waitUntil">): Promise<Response | null>;
107
+ };
108
+ /** The event this package would send for a request (useful for debugging). */
109
+ declare function buildEvent(request: NextRequest, siteId: string, now?: number): EdgeEvent;
110
+
111
+ export { COUNTED_TIMING, type Dsn, type EdgeEvent, INTERNAL_HEADER, type PunchlineOptions, buildEvent, createTracker, parseDsn, punchline, readVercelFacts, shouldTrack };
package/dist/index.js ADDED
@@ -0,0 +1,793 @@
1
+ import { NextResponse } from 'next/server.js';
2
+
3
+ // ../privacy/src/hash.ts
4
+ new TextEncoder();
5
+
6
+ // ../schema/src/types.ts
7
+ var UTM_KEYS = ["source", "medium", "campaign", "term", "content"];
8
+ var ACCEPT_MAX_LENGTH = 200;
9
+
10
+ // ../schema/src/tokens.ts
11
+ var CLICK_ID_PARAMS = ["gclid", "gbraid", "wbraid", "fbclid"];
12
+ var CLICK_ID = /^[A-Za-z0-9_.-]{8,500}$/;
13
+ var HANDOFF_PARAM = "pl_ho";
14
+ var HANDOFF_TOKEN = /^[A-Za-z0-9]{24}$/;
15
+ var VISITOR_COOKIE = "_pl_vid";
16
+ var CONSENT_COOKIE = "_pl_consent";
17
+ var VISITOR_ID = /^[A-Za-z0-9]{22}$/;
18
+ var VISITOR_COOKIE_MAX_AGE_S = 395 * 24 * 60 * 60;
19
+
20
+ // ../schema/src/url-params.ts
21
+ var SENSITIVE_PARAM = /^(e-?mail|mail|email_?address|phone|tel|mobile|name|first_?name|last_?name|full_?name|address|zip|postcode|dob|birthday|ssn|uid|user_?id|userid|user|username|login|customer_?id|account_?id|member_?id|contact_?id|token|access_?token|id_?token|refresh_?token|auth|authorization|code_?verifier|password|passwd|pwd|pass|secret|api_?key|key|session|session_?id|sid|jwt|otp|reset_?token|ip)$/i;
22
+
23
+ // ../schema/src/beacon.ts
24
+ var CONSENT_REGION = /* @__PURE__ */ new Set([
25
+ "AT",
26
+ "BE",
27
+ "BG",
28
+ "HR",
29
+ "CY",
30
+ "CZ",
31
+ "DK",
32
+ "EE",
33
+ "FI",
34
+ "FR",
35
+ "DE",
36
+ "GR",
37
+ "HU",
38
+ "IE",
39
+ "IT",
40
+ "LV",
41
+ "LT",
42
+ "LU",
43
+ "MT",
44
+ "NL",
45
+ "PL",
46
+ "PT",
47
+ "RO",
48
+ "SK",
49
+ "SI",
50
+ "ES",
51
+ "SE",
52
+ "IS",
53
+ "LI",
54
+ "NO",
55
+ "GB",
56
+ "CH"
57
+ ]);
58
+
59
+ // ../schema/src/visitor-modes.ts
60
+ var VISITOR_MODES_OFF = { remember: false, fullUrls: false, consentRegion: "consent" };
61
+ function parseVisitorModes(raw) {
62
+ const r = raw && typeof raw === "object" ? raw : {};
63
+ return { remember: r.remember === true, fullUrls: r.fullUrls === true, consentRegion: r.consentRegion === "always" ? "always" : "consent" };
64
+ }
65
+ function inConsentRegion(country) {
66
+ return !country || CONSENT_REGION.has(country.toUpperCase());
67
+ }
68
+ function visitorModeFor(modes, v) {
69
+ if (v.gpc) return { remember: false, fullUrls: false };
70
+ const allowed = !inConsentRegion(v.country) || modes.consentRegion === "always" || v.consent;
71
+ return { remember: modes.remember && allowed, fullUrls: modes.fullUrls && allowed };
72
+ }
73
+
74
+ // ../privacy/src/url.ts
75
+ var UTM_VALUE_MAX_LENGTH = 200;
76
+ var EMAIL = /[^\s@/?#&=]+@[^\s@/?#&=]+\.[a-z]{2,}/gi;
77
+ function sanitizeUrl(rawUrl, allowed = [], clickTypes = []) {
78
+ const url = new URL(rawUrl);
79
+ const utm = {};
80
+ for (const key of UTM_KEYS) {
81
+ const value = url.searchParams.get(`utm_${key}`)?.trim();
82
+ if (value) utm[key] = redactEmails(value).slice(0, UTM_VALUE_MAX_LENGTH);
83
+ }
84
+ let params;
85
+ for (const a of allowed.slice(0, 20)) {
86
+ const value = url.searchParams.get(a.name);
87
+ if (value === null) continue;
88
+ (params ??= {})[a.name] = a.mode === "presence" ? "1" : redactEmails(value.trim()).slice(0, UTM_VALUE_MAX_LENGTH);
89
+ }
90
+ const handoff = url.searchParams.get(HANDOFF_PARAM);
91
+ let clicks;
92
+ for (const t of CLICK_ID_PARAMS) {
93
+ if (!clickTypes.includes(t)) continue;
94
+ const v = url.searchParams.get(t);
95
+ if (v && CLICK_ID.test(v)) (clicks ??= {})[t] = v;
96
+ }
97
+ return {
98
+ host: url.hostname.toLowerCase(),
99
+ path: redactEmails(safeDecode(url.pathname)),
100
+ utm,
101
+ ...params ? { params } : {},
102
+ ...handoff && HANDOFF_TOKEN.test(handoff) ? { handoff } : {},
103
+ ...clicks ? { clicks } : {}
104
+ };
105
+ }
106
+ function referrerHostOf(referer) {
107
+ if (!referer) return null;
108
+ try {
109
+ const url = new URL(referer);
110
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
111
+ return url.hostname.toLowerCase() || null;
112
+ } catch {
113
+ return null;
114
+ }
115
+ }
116
+ function truncateAccept(accept) {
117
+ return accept ? accept.slice(0, ACCEPT_MAX_LENGTH) : null;
118
+ }
119
+ function redactEmails(value) {
120
+ return value.replace(EMAIL, "[email]");
121
+ }
122
+ var CREDENTIAL_PARAM = /(^|[_.-])(token|access[_-]?token|id[_-]?token|refresh[_-]?token|password|passwd|pass|pwd|secret|key|api[_-]?key|apikey|auth|authorization|code|session|sessionid|sid|sig|signature|otp|jwt|nonce|state|ticket|hash|pl_ho)$/i;
123
+ var QUERY_MAX_LENGTH = 1024;
124
+ function redactQuery(search, max = QUERY_MAX_LENGTH) {
125
+ const raw = search.startsWith("?") ? search.slice(1) : search;
126
+ if (!raw) return null;
127
+ let params;
128
+ try {
129
+ params = new URLSearchParams(raw);
130
+ } catch {
131
+ return null;
132
+ }
133
+ const out = new URLSearchParams();
134
+ for (const [k, v] of params) out.append(redactEmails(k).slice(0, 100), SENSITIVE_PARAM.test(k) || CREDENTIAL_PARAM.test(k) ? "[redacted]" : redactEmails(v).slice(0, 500));
135
+ const text = out.toString();
136
+ return text ? text.slice(0, max) : null;
137
+ }
138
+ function safeDecode(path) {
139
+ try {
140
+ return decodeURIComponent(path);
141
+ } catch {
142
+ return path;
143
+ }
144
+ }
145
+
146
+ // ../edge/src/markdown.ts
147
+ var MARKDOWN_OFF = { enabled: false, agents: "assistants", exclude: [], handoffLinks: false };
148
+ var ASSISTANT_UAS = /\b(ChatGPT-User|OAI-SearchBot|Claude-User|Claude-SearchBot|Perplexity-User|PerplexityBot|MistralAI-User|DuckAssistBot|YouBot|Meta-ExternalFetcher)\b/i;
149
+ var TRAINING_UAS = /\b(GPTBot|ClaudeBot|anthropic-ai|meta-externalagent|Amazonbot|Applebot-Extended|cohere-ai|CCBot|Bytespider)\b/i;
150
+ var SEARCH_UAS = /\b(Googlebot|bingbot|Google-InspectionTool|Storebot-Google|DuckDuckBot|YandexBot|Baiduspider|Applebot)\b(?!-Extended)/i;
151
+ var USER_FETCHERS = /\b(ChatGPT-User|Claude-User|Perplexity-User|MistralAI-User)\b/i;
152
+ var isUserFetch = (request) => USER_FETCHERS.test(request.headers.get("user-agent") ?? "");
153
+ function wantsMarkdown(request, s) {
154
+ if (!s.enabled || request.method !== "GET") return null;
155
+ const url = new URL(request.url);
156
+ const path = htmlPathFor(url.pathname);
157
+ if (s.exclude.some((p) => path === p || path.startsWith(p.endsWith("/") ? p : `${p}/`))) return null;
158
+ if (url.pathname.endsWith(".md")) return "md_path";
159
+ const accept = request.headers.get("accept") ?? "";
160
+ if (/(^|,)\s*text\/markdown\b/i.test(accept) && !/(^|,)\s*text\/html\s*(,|;|$)/i.test(accept.split("text/markdown")[0] ?? "")) return "accept";
161
+ const ua = request.headers.get("user-agent") ?? "";
162
+ if (SEARCH_UAS.test(ua)) return null;
163
+ if (ASSISTANT_UAS.test(ua) || s.agents === "ai" && TRAINING_UAS.test(ua)) return "agent";
164
+ return null;
165
+ }
166
+ function htmlPathFor(pathname) {
167
+ if (!pathname.endsWith(".md")) return pathname;
168
+ const p = pathname.slice(0, -3).replace(/\/index$/, "/");
169
+ return p === "" ? "/" : p;
170
+ }
171
+ function markdownPathFor(pathname) {
172
+ return pathname === "/" || pathname.endsWith("/") ? `${pathname}index.md` : `${pathname}.md`;
173
+ }
174
+ var DROP = /* @__PURE__ */ new Set(["script", "style", "noscript", "template", "svg", "iframe", "nav", "footer", "aside", "form", "button", "select", "dialog", "object", "canvas", "head"]);
175
+ var VOID = /* @__PURE__ */ new Set(["br", "hr", "img", "input", "meta", "link", "source", "wbr", "area", "base", "col", "embed", "param", "track"]);
176
+ var BLOCK = /* @__PURE__ */ new Set(["p", "div", "section", "article", "main", "header", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "li", "pre", "blockquote", "table", "tr", "hr", "figure", "figcaption", "dl", "dt", "dd", "details", "summary"]);
177
+ var ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", ndash: "\u2013", mdash: "\u2014", hellip: "\u2026", rsquo: "\u2019", lsquo: "\u2018", rdquo: "\u201D", ldquo: "\u201C", copy: "\xA9", reg: "\xAE", trade: "\u2122", times: "\xD7", middot: "\xB7", bull: "\u2022" };
178
+ function decodeEntities(s) {
179
+ return s.replace(/&(#x[0-9a-f]{1,6}|#[0-9]{1,7}|[a-z]{2,8});/gi, (m, e) => {
180
+ if (e[0] === "#") {
181
+ const n = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
182
+ return n > 0 && n <= 1114111 && !(n >= 55296 && n <= 57343) ? String.fromCodePoint(n) : "";
183
+ }
184
+ return ENTITIES[e.toLowerCase()] ?? m;
185
+ });
186
+ }
187
+ function parseAttrs(s) {
188
+ const out = {};
189
+ for (const m of s.matchAll(/([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g)) out[m[1].toLowerCase()] = decodeEntities(m[2] ?? m[3] ?? m[4] ?? "");
190
+ return out;
191
+ }
192
+ function parseHtml(html) {
193
+ const root = { tag: "#root", attrs: {}, children: [] };
194
+ const stack = [root];
195
+ const re = /<!--[\s\S]*?-->|<!doctype[^>]*>|<\/([a-zA-Z][a-zA-Z0-9-]*)\s*>|<([a-zA-Z][a-zA-Z0-9-]*)((?:\s+[^>]*?)?)(\/?)>/gi;
196
+ let last = 0;
197
+ const raw = /* @__PURE__ */ new Set(["script", "style", "textarea", "title", "pre"]);
198
+ const lower = html.toLowerCase();
199
+ for (let m = re.exec(html); m; m = re.exec(html)) {
200
+ if (m.index > last) stack[stack.length - 1].children.push(html.slice(last, m.index));
201
+ last = re.lastIndex;
202
+ if (m[0].startsWith("<!")) continue;
203
+ if (m[1]) {
204
+ const tag2 = m[1].toLowerCase();
205
+ const i = stack.map((n) => n.tag).lastIndexOf(tag2);
206
+ if (i > 0) stack.length = i;
207
+ continue;
208
+ }
209
+ const tag = m[2].toLowerCase();
210
+ const node = { tag, attrs: parseAttrs(m[3] ?? ""), children: [] };
211
+ stack[stack.length - 1].children.push(node);
212
+ if (VOID.has(tag) || m[4] === "/") continue;
213
+ if (raw.has(tag) && tag !== "pre") {
214
+ const end = lower.indexOf(`</${tag}`, last);
215
+ const stop = end < 0 ? html.length : end;
216
+ node.children.push(html.slice(last, stop));
217
+ const close = html.indexOf(">", stop);
218
+ last = close < 0 ? html.length : close + 1;
219
+ re.lastIndex = last;
220
+ continue;
221
+ }
222
+ stack.push(node);
223
+ }
224
+ if (last < html.length) stack[stack.length - 1].children.push(html.slice(last));
225
+ return root;
226
+ }
227
+ function find(n, tag) {
228
+ for (const c of n.children) {
229
+ if (typeof c === "string") continue;
230
+ if (c.tag === tag) return c;
231
+ const f = find(c, tag);
232
+ if (f) return f;
233
+ }
234
+ return null;
235
+ }
236
+ var textOf = (n) => typeof n === "string" ? n : n.children.map(textOf).join("");
237
+ var inline = (s) => decodeEntities(s).replace(/\s+/g, " ");
238
+ function absolute(href, base) {
239
+ if (!href || /^(javascript|data|vbscript):/i.test(href.trim())) return null;
240
+ if (href.startsWith("#")) return href;
241
+ try {
242
+ return new URL(href, base).toString();
243
+ } catch {
244
+ return null;
245
+ }
246
+ }
247
+ function render(n, base, ctx = { list: [] }) {
248
+ if (typeof n === "string") return inline(n);
249
+ const tag = n.tag;
250
+ if (DROP.has(tag) || n.attrs.hidden !== void 0 || n.attrs["aria-hidden"] === "true") return "";
251
+ const kids = () => n.children.map((c) => render(c, base, ctx)).join("");
252
+ switch (tag) {
253
+ case "h1":
254
+ case "h2":
255
+ case "h3":
256
+ case "h4":
257
+ case "h5":
258
+ case "h6": {
259
+ const t = kids().trim();
260
+ return t ? `
261
+
262
+ ${"#".repeat(Number(tag[1]))} ${t}
263
+
264
+ ` : "";
265
+ }
266
+ case "p":
267
+ case "div":
268
+ case "section":
269
+ case "article":
270
+ case "main":
271
+ case "header":
272
+ case "figure":
273
+ case "details":
274
+ case "summary":
275
+ case "dl":
276
+ case "dd":
277
+ return `
278
+
279
+ ${kids().trim()}
280
+
281
+ `;
282
+ case "dt":
283
+ return `
284
+
285
+ **${kids().trim()}**
286
+ `;
287
+ case "figcaption":
288
+ return `
289
+
290
+ _${kids().trim()}_
291
+
292
+ `;
293
+ case "br":
294
+ return " \n";
295
+ case "hr":
296
+ return "\n\n---\n\n";
297
+ case "strong":
298
+ case "b": {
299
+ const t = kids().trim();
300
+ return t ? `**${t}**` : "";
301
+ }
302
+ case "em":
303
+ case "i": {
304
+ const t = kids().trim();
305
+ return t ? `_${t}_` : "";
306
+ }
307
+ case "code":
308
+ return `\`${decodeEntities(textOf(n)).replace(/`/g, "'")}\``;
309
+ case "pre":
310
+ return `
311
+
312
+ \`\`\`
313
+ ${decodeEntities(textOf(n)).replace(/```/g, "'''").replace(/\n+$/, "")}
314
+ \`\`\`
315
+
316
+ `;
317
+ case "blockquote":
318
+ return `
319
+
320
+ ${kids().trim().split("\n").map((l) => `> ${l}`).join("\n")}
321
+
322
+ `;
323
+ case "a": {
324
+ const t = kids().trim();
325
+ const href = absolute(n.attrs.href ?? "", base);
326
+ return t && href ? `[${t}](${href})` : t;
327
+ }
328
+ case "img": {
329
+ const src = absolute(n.attrs.src ?? "", base);
330
+ const alt = inline(n.attrs.alt ?? "").trim();
331
+ return src && alt ? `![${alt}](${src})` : "";
332
+ }
333
+ case "ul":
334
+ case "ol": {
335
+ ctx.list.push({ ordered: tag === "ol", n: 0 });
336
+ const body = kids();
337
+ ctx.list.pop();
338
+ return `
339
+
340
+ ${body.replace(/\n{2,}/g, "\n").trim()}
341
+
342
+ `;
343
+ }
344
+ case "li": {
345
+ const l = ctx.list[ctx.list.length - 1] ?? { ordered: false, n: 0 };
346
+ l.n += 1;
347
+ const indent = " ".repeat(Math.max(0, ctx.list.length - 1));
348
+ const body = kids().trim().replace(/\n+/g, `
349
+ ${indent} `);
350
+ return `
351
+ ${indent}${l.ordered ? `${l.n}.` : "-"} ${body}`;
352
+ }
353
+ case "table":
354
+ return renderTable(n, base, ctx);
355
+ case "input":
356
+ case "meta":
357
+ case "link":
358
+ return "";
359
+ default:
360
+ return BLOCK.has(tag) ? `
361
+
362
+ ${kids().trim()}
363
+
364
+ ` : kids();
365
+ }
366
+ }
367
+ function renderTable(n, base, ctx) {
368
+ const rows = [];
369
+ const walk = (x) => {
370
+ for (const c of x.children) {
371
+ if (typeof c === "string") continue;
372
+ if (c.tag === "tr") rows.push(c.children.filter((k) => typeof k !== "string" && (k.tag === "td" || k.tag === "th")).map((cell) => render(cell, base, ctx).replace(/\s+/g, " ").replace(/\|/g, "\\|").trim()));
373
+ else walk(c);
374
+ }
375
+ };
376
+ walk(n);
377
+ if (!rows.length) return "";
378
+ const width = Math.max(...rows.map((r) => r.length));
379
+ const pad = (r) => `| ${[...r, ...Array(width - r.length).fill("")].join(" | ")} |`;
380
+ return `
381
+
382
+ ${[pad(rows[0]), `| ${Array(width).fill("---").join(" | ")} |`, ...rows.slice(1).map(pad)].join("\n")}
383
+
384
+ `;
385
+ }
386
+ var MAX_HTML_BYTES = 2 * 1024 * 1024;
387
+ function htmlToMarkdown(html, pageUrl) {
388
+ const base = new URL(pageUrl);
389
+ const doc = parseHtml(html);
390
+ const title = inline(textOf(find(doc, "title") ?? { tag: "title", attrs: {}, children: [] })).trim();
391
+ const main = find(doc, "main") ?? find(doc, "article") ?? find(doc, "body") ?? doc;
392
+ const body = render(main, base).replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").replace(/\n\n[ \t]+/g, "\n\n").trim();
393
+ const startsWithTitle = title && body.startsWith(`# `);
394
+ return `${title && !startsWithTitle ? `# ${title}
395
+
396
+ ` : ""}${body}
397
+
398
+ ---
399
+ Source: ${base.toString()}
400
+ `;
401
+ }
402
+
403
+ // ../edge/src/index.ts
404
+ var MARKDOWN_ANY = { enabled: true, agents: "ai", exclude: [], handoffLinks: false };
405
+ function createSiteConfig(fetchTimeoutMs = 3e3, now = Date.now) {
406
+ let allowed = [];
407
+ let markdown = MARKDOWN_OFF;
408
+ let clickIds = [];
409
+ let visitors = VISITOR_MODES_OFF;
410
+ let nextAt = 0;
411
+ let inFlight = false;
412
+ let known = false;
413
+ let pending = null;
414
+ const config = {
415
+ /** The markdown settings from the same fetch (off until known). */
416
+ markdown(dsn, waitUntil) {
417
+ config.allowed(dsn, waitUntil);
418
+ return markdown;
419
+ },
420
+ /**
421
+ * The markdown settings, waiting up to maxWaitMs for the first fetch in a
422
+ * new instance. Edge instances start cold and often, so without this an
423
+ * agent's request on a quiet site would usually get HTML. Only for
424
+ * requests that could get markdown; once known, it never waits.
425
+ */
426
+ async markdownReady(dsn, waitUntil, maxWaitMs) {
427
+ config.allowed(dsn, waitUntil);
428
+ if (!known && pending) await Promise.race([pending, new Promise((r) => setTimeout(r, maxWaitMs))]);
429
+ return markdown;
430
+ },
431
+ /** The site's visitor modes (off until known), and whether they're known yet. */
432
+ visitors(dsn, waitUntil) {
433
+ config.allowed(dsn, waitUntil);
434
+ return { modes: visitors, known };
435
+ },
436
+ /** Ad click ID parameters the site opted in to capture (none until known). */
437
+ clickIds(dsn, waitUntil) {
438
+ config.allowed(dsn, waitUntil);
439
+ return clickIds;
440
+ },
441
+ allowed(dsn, waitUntil) {
442
+ if (!inFlight && now() >= nextAt) {
443
+ inFlight = true;
444
+ nextAt = now() + 6e4;
445
+ const url = new URL("/api/edge-config", dsn.collectorUrl);
446
+ url.searchParams.set("site", dsn.siteId);
447
+ pending = fetch(url, { headers: { authorization: `Bearer ${dsn.secret}` }, signal: AbortSignal.timeout(fetchTimeoutMs) }).then(async (res) => {
448
+ if (!res.ok) return;
449
+ const body = await res.json();
450
+ const v = Array.isArray(body.params) ? body.params : [];
451
+ allowed = v.filter((p) => typeof p?.name === "string" && (p.mode === "presence" || p.mode === "value")).slice(0, 20);
452
+ markdown = parseMarkdownSettings(body.markdown);
453
+ visitors = parseVisitorModes(body.visitors);
454
+ clickIds = Array.isArray(body.clickIds) ? body.clickIds.filter((c) => ["gclid", "gbraid", "wbraid", "fbclid"].includes(c)) : [];
455
+ nextAt = now() + 3e5;
456
+ known = true;
457
+ }).catch(() => {
458
+ }).finally(() => {
459
+ inFlight = false;
460
+ });
461
+ waitUntil(pending);
462
+ }
463
+ return allowed;
464
+ }
465
+ };
466
+ return config;
467
+ }
468
+ function parseMarkdownSettings(raw) {
469
+ const r = raw && typeof raw === "object" ? raw : {};
470
+ const exclude = Array.isArray(r.exclude) ? r.exclude.filter((p) => typeof p === "string" && p.startsWith("/")).slice(0, 20) : [];
471
+ return { enabled: r.enabled === true, agents: r.agents === "ai" ? "ai" : "assistants", exclude, handoffLinks: r.handoffLinks === true };
472
+ }
473
+ async function toMarkdownResponse(html, pageUrl) {
474
+ const type = html.headers.get("content-type") ?? "";
475
+ const length = Number(html.headers.get("content-length") ?? "0");
476
+ if (html.status !== 200 || !/^text\/html\b/i.test(type) || length > MAX_HTML_BYTES) return null;
477
+ const text = await html.clone().text();
478
+ if (text.length > MAX_HTML_BYTES) return null;
479
+ const headers = new Headers({ "content-type": "text/markdown; charset=utf-8", vary: "Accept, User-Agent", "x-robots-tag": "noindex", link: `<${pageUrl}>; rel="canonical"` });
480
+ const cache = html.headers.get("cache-control");
481
+ if (cache) headers.set("cache-control", cache);
482
+ return new Response(htmlToMarkdown(text, pageUrl), { status: 200, headers });
483
+ }
484
+ async function withShareLink(md, pageUrl) {
485
+ const token = randomBase62(24);
486
+ const u = new URL(pageUrl);
487
+ const link = `${u.origin}${u.pathname}?${HANDOFF_PARAM}=${token}`;
488
+ const body = `${(await md.text()).replace(/\s+$/, "")}
489
+
490
+ ---
491
+
492
+ Share link to this page: ${link}
493
+ `;
494
+ const headers = new Headers(md.headers);
495
+ headers.set("cache-control", "private, no-store");
496
+ headers.delete("content-length");
497
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
498
+ const tokenHash = Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
499
+ return { response: new Response(body, { status: md.status, headers }), tokenHash };
500
+ }
501
+ function randomBase62(n) {
502
+ const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
503
+ const bytes = crypto.getRandomValues(new Uint8Array(n));
504
+ let out = "";
505
+ while (out.length < n) {
506
+ for (const b of bytes) if (b < 248 && out.length < n) out += ALPHABET[b % 62];
507
+ if (out.length < n) crypto.getRandomValues(bytes);
508
+ }
509
+ return out;
510
+ }
511
+ function readCookie(header, name) {
512
+ for (const part of (header ?? "").split(";")) {
513
+ const i = part.indexOf("=");
514
+ if (i > 0 && part.slice(0, i).trim() === name) return part.slice(i + 1).trim();
515
+ }
516
+ return null;
517
+ }
518
+ function rememberVisitor(request, event, visitors) {
519
+ const cookie = request.headers.get("cookie");
520
+ const existing = readCookie(cookie, VISITOR_COOKIE);
521
+ const consent = readCookie(cookie, CONSENT_COOKIE) === "1";
522
+ const mode = visitorModeFor(visitors.modes, { country: event.country ?? null, consent, gpc: event.gpc });
523
+ const secure = new URL(request.url).protocol === "https:" ? "; Secure" : "";
524
+ if (mode.remember) {
525
+ const id = existing && VISITOR_ID.test(existing) ? existing : randomBase62(22);
526
+ event.visitorId = id;
527
+ if (consent) event.consent = true;
528
+ return id === existing ? void 0 : `${VISITOR_COOKIE}=${id}; Max-Age=${VISITOR_COOKIE_MAX_AGE_S}; Path=/; SameSite=Lax${secure}`;
529
+ }
530
+ if (consent) event.consent = true;
531
+ return existing !== null && (visitors.known || event.gpc) ? `${VISITOR_COOKIE}=; Max-Age=0; Path=/; SameSite=Lax${secure}` : void 0;
532
+ }
533
+ function readVercelFacts(request) {
534
+ const h = request.headers;
535
+ const vercelSignals = {};
536
+ h.forEach((value, name) => {
537
+ if (/^x-vercel-.*(bot|verified)/i.test(name)) vercelSignals[name] = value;
538
+ });
539
+ return {
540
+ ip: h.get("x-forwarded-for")?.split(",")[0]?.trim() || h.get("x-real-ip") || "unknown",
541
+ country: h.get("x-vercel-ip-country"),
542
+ vercelSignals
543
+ };
544
+ }
545
+ function markdownLink(requestUrl) {
546
+ const u = new URL(requestUrl);
547
+ return `<${markdownPathFor(u.pathname)}>; rel="alternate"; type="text/markdown"`;
548
+ }
549
+ function createTracker(options) {
550
+ const onError = options.onError ?? (() => {
551
+ });
552
+ const siteConfig = createSiteConfig(options.timeoutMs ?? 3e3);
553
+ const timeoutMs = options.timeoutMs ?? 3e3;
554
+ let dsn;
555
+ const resolveDsn = () => {
556
+ if (dsn !== void 0) return dsn;
557
+ try {
558
+ dsn = parseDsn((typeof options.dsn === "function" ? options.dsn() : options.dsn) ?? "");
559
+ } catch (err) {
560
+ dsn = null;
561
+ onError(err);
562
+ }
563
+ return dsn;
564
+ };
565
+ return {
566
+ track(request, waitUntil, response) {
567
+ const start = performance.now();
568
+ try {
569
+ const config = resolveDsn();
570
+ if (!config || !shouldTrack(request)) return { overheadMs: null };
571
+ const facts = options.readFacts(request);
572
+ const event = buildEvent(request, config.siteId, facts, Date.now(), siteConfig.allowed(config, waitUntil), siteConfig.clickIds(config, waitUntil));
573
+ const setCookie = rememberVisitor(request, event, siteConfig.visitors(config, waitUntil));
574
+ const send = (e) => fetch(config.collectorUrl, {
575
+ method: "POST",
576
+ headers: { authorization: `Bearer ${config.secret}`, "content-type": "application/json" },
577
+ body: JSON.stringify(e),
578
+ signal: AbortSignal.timeout(timeoutMs)
579
+ }).then((res) => {
580
+ if (!res.ok) onError(new Error(`Punchline collector responded ${res.status}`));
581
+ return res.body?.cancel();
582
+ });
583
+ const sent = response ? response.then(
584
+ (r) => r ? { ...event, status: r.status, ...r.bytes !== null ? { bytes: r.bytes } : {}, ...r.format ? { format: r.format } : {}, ...r.mintedHandoff ? { mintedHandoff: r.mintedHandoff } : {} } : event,
585
+ () => event
586
+ ).then(send) : send(event);
587
+ waitUntil(sent.catch(onError));
588
+ return { overheadMs: performance.now() - start, ...setCookie ? { setCookie } : {} };
589
+ } catch (err) {
590
+ onError(err);
591
+ return { overheadMs: null };
592
+ }
593
+ },
594
+ markdown(waitUntil) {
595
+ try {
596
+ const config = resolveDsn();
597
+ return config ? siteConfig.markdown(config, waitUntil) : MARKDOWN_OFF;
598
+ } catch (err) {
599
+ onError(err);
600
+ return MARKDOWN_OFF;
601
+ }
602
+ },
603
+ async markdownFor(request, waitUntil, maxWaitMs = 1500) {
604
+ try {
605
+ const config = resolveDsn();
606
+ if (!config) return MARKDOWN_OFF;
607
+ if (!wantsMarkdown(request, MARKDOWN_ANY)) return siteConfig.markdown(config, waitUntil);
608
+ return await siteConfig.markdownReady(config, waitUntil, maxWaitMs);
609
+ } catch (err) {
610
+ onError(err);
611
+ return MARKDOWN_OFF;
612
+ }
613
+ }
614
+ };
615
+ }
616
+ function htmlRequestFor(request) {
617
+ const url = new URL(request.url);
618
+ url.pathname = htmlPathFor(url.pathname);
619
+ const headers = new Headers(request.headers);
620
+ headers.set("accept", "text/html");
621
+ return new Request(url, { method: "GET", headers, redirect: "manual" });
622
+ }
623
+ function parseDsn(raw) {
624
+ if (!raw) throw new Error("PUNCHLINE_DSN is not set");
625
+ const url = new URL(raw);
626
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1";
627
+ if (url.protocol !== "https:" && !(local && url.protocol === "http:")) throw new Error("PUNCHLINE_DSN must use https");
628
+ const siteId = decodeURIComponent(url.username);
629
+ const secret = decodeURIComponent(url.password);
630
+ if (!siteId || !secret) throw new Error("PUNCHLINE_DSN needs <siteId>:<secret>@");
631
+ url.username = "";
632
+ url.password = "";
633
+ return { collectorUrl: url.toString(), siteId, secret };
634
+ }
635
+ var COUNTED_TIMING = "punchline-pv";
636
+ var TRACKED_EXTENSIONS = /* @__PURE__ */ new Set(["html", "htm", "txt", "md", "xml"]);
637
+ function shouldTrack(request) {
638
+ if (request.method !== "GET" && request.method !== "HEAD") return false;
639
+ const h = request.headers;
640
+ const dest = h.get("sec-fetch-dest");
641
+ if (dest && dest !== "document") return false;
642
+ if (/prefetch|prerender/i.test(h.get("sec-purpose") ?? "") || /prefetch/i.test(h.get("purpose") ?? "")) return false;
643
+ if (h.has("next-router-prefetch") || h.has("next-router-segment-prefetch")) return false;
644
+ const last = new URL(request.url).pathname.split("/").pop() ?? "";
645
+ const dot = last.lastIndexOf(".");
646
+ return dot <= 0 || TRACKED_EXTENSIONS.has(last.slice(dot + 1).toLowerCase());
647
+ }
648
+ function buildEvent(request, siteId, facts, now = Date.now(), allowed = [], clickTypes = []) {
649
+ const h = request.headers;
650
+ const { host, path, utm, params, handoff, clicks } = sanitizeUrl(request.url, allowed, clickTypes);
651
+ const query = redactQuery(new URL(request.url).search);
652
+ const signature = h.get("signature");
653
+ const signatureInput = h.get("signature-input");
654
+ const signatureAgent = h.get("signature-agent");
655
+ const event = {
656
+ v: 1,
657
+ siteId,
658
+ ts: now,
659
+ method: request.method,
660
+ host,
661
+ path,
662
+ utm,
663
+ referrerHost: referrerHostOf(h.get("referer")),
664
+ status: null,
665
+ ...params ? { params } : {},
666
+ ...handoff ? { handoff } : {},
667
+ ...clicks ? { clicks } : {},
668
+ accept: truncateAccept(h.get("accept")),
669
+ ...query ? { query } : {},
670
+ ip: (facts.ip || "unknown").slice(0, 45),
671
+ userAgent: h.get("user-agent") ?? "",
672
+ gpc: h.get("sec-gpc") === "1",
673
+ country: facts.country && /^[A-Z]{2}$/.test(facts.country) ? facts.country : null
674
+ };
675
+ if (signature || signatureInput || signatureAgent) {
676
+ event.signatureHeaders = {
677
+ ...signature ? { signature } : {},
678
+ ...signatureInput ? { signatureInput } : {},
679
+ ...signatureAgent ? { signatureAgent } : {}
680
+ };
681
+ }
682
+ const bounded = (signals) => {
683
+ const entries = Object.entries(signals ?? {}).slice(0, 10).map(([k, v]) => [k.slice(0, 64), String(v).slice(0, 64)]);
684
+ return entries.length ? Object.fromEntries(entries) : void 0;
685
+ };
686
+ const vercel = bounded(facts.vercelSignals);
687
+ const platform = bounded(facts.platformSignals);
688
+ if (vercel) event.vercelSignals = vercel;
689
+ if (platform) event.platformSignals = platform;
690
+ return event;
691
+ }
692
+ var INTERNAL_HEADER = "x-punchline-internal";
693
+ function punchline(options = {}) {
694
+ const tracker = createTracker2(options);
695
+ return async function proxy(request, event) {
696
+ if (await tracker.isInternal(request)) return NextResponse.next();
697
+ const markdown = await tracker.serveMarkdown(request, event);
698
+ if (markdown) return new NextResponse(markdown.body, markdown);
699
+ const { overheadMs, setCookie } = tracker.track(request, event);
700
+ const response = NextResponse.next();
701
+ if (setCookie) response.headers.append("Set-Cookie", setCookie);
702
+ if (tracker.markdownOn(event) && isPagePath(request)) response.headers.append("Link", markdownLink(request.url));
703
+ if (overheadMs !== null) response.headers.set("Server-Timing", tracker.serverTiming ? `${COUNTED_TIMING}, punchline;dur=${overheadMs.toFixed(3)}` : COUNTED_TIMING);
704
+ return response;
705
+ };
706
+ }
707
+ var isPagePath = (request) => request.method === "GET" && /(^|\/)([^./]*|[^/]*\.html?)$/i.test(new URL(request.url).pathname);
708
+ function createTracker2(options = {}) {
709
+ const tracker = createTracker({
710
+ // An empty env var means unset, so fall through it.
711
+ dsn: () => options.dsn ?? (process.env.PUNCHLINE_DSN || process.env.AGENTLENS_DSN || ""),
712
+ readFacts: readVercelFacts,
713
+ ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
714
+ ...options.onError ? { onError: options.onError } : {}
715
+ });
716
+ const dsnSecret = () => {
717
+ try {
718
+ return parseDsn(options.dsn ?? (process.env.PUNCHLINE_DSN || process.env.AGENTLENS_DSN || "")).secret;
719
+ } catch {
720
+ return null;
721
+ }
722
+ };
723
+ let internalToken;
724
+ const token = () => internalToken ??= (async () => {
725
+ const secret = dsnSecret();
726
+ if (!secret) return null;
727
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`punchline-internal:${secret}`));
728
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
729
+ })();
730
+ return {
731
+ serverTiming: options.serverTiming ?? (process.env.PUNCHLINE_SERVER_TIMING || process.env.AGENTLENS_SERVER_TIMING) === "1",
732
+ /**
733
+ * Returns the time spent on the request path (null if it wasn't tracked),
734
+ * and a Set-Cookie value to add to the response when the site remembers
735
+ * visitors (a new visitor cookie, or one that clears it).
736
+ */
737
+ track(request, event) {
738
+ return tracker.track(request, (p) => event.waitUntil(p));
739
+ },
740
+ /** Whether "Serve AI agents markdown" is on for this site (off until the settings load). */
741
+ markdownOn(event) {
742
+ return tracker.markdown((p) => event.waitUntil(p)).enabled;
743
+ },
744
+ /** The proxy's own HTML fetch for a markdown answer. */
745
+ async isInternal(request) {
746
+ const got = request.headers.get(INTERNAL_HEADER);
747
+ if (!got) return false;
748
+ const want = await token();
749
+ return want !== null && got === want;
750
+ },
751
+ /**
752
+ * The markdown answer for an AI agent (or a .md / text/markdown request),
753
+ * tracked as the page with format markdown; null to carry on as usual.
754
+ */
755
+ async serveMarkdown(request, event) {
756
+ const waitUntil = (p) => event.waitUntil(p);
757
+ try {
758
+ const settings = await tracker.markdownFor(request, waitUntil);
759
+ const reason = wantsMarkdown(request, settings);
760
+ if (!reason) return null;
761
+ const t = await token();
762
+ if (!t) return null;
763
+ if (reason === "md_path") {
764
+ const probe = new Request(request.url, { method: "HEAD", headers: { [INTERNAL_HEADER]: t } });
765
+ const head = await fetch(probe, { redirect: "manual" }).catch(() => null);
766
+ if (head?.ok && !/^text\/html\b/i.test(head.headers.get("content-type") ?? "")) return null;
767
+ }
768
+ const page = htmlRequestFor(request);
769
+ const inner = new Request(page, { headers: new Headers(page.headers) });
770
+ inner.headers.set(INTERNAL_HEADER, t);
771
+ inner.headers.delete("cookie");
772
+ const html = await fetch(inner, { redirect: "manual" });
773
+ const converted = await toMarkdownResponse(html, page.url);
774
+ const shared = converted && settings.handoffLinks && reason === "agent" && isUserFetch(request) ? await withShareLink(converted, page.url) : null;
775
+ const md = shared?.response ?? converted;
776
+ tracker.track(page, waitUntil, Promise.resolve({ status: md ? 200 : html.status, bytes: null, ...md ? { format: "markdown" } : {}, ...shared ? { mintedHandoff: shared.tokenHash } : {} }));
777
+ if (md) return md;
778
+ const headers = new Headers(html.headers);
779
+ headers.delete("content-encoding");
780
+ headers.delete("content-length");
781
+ return new Response(html.body, { status: html.status, statusText: html.statusText, headers });
782
+ } catch (err) {
783
+ options.onError?.(err);
784
+ return null;
785
+ }
786
+ }
787
+ };
788
+ }
789
+ function buildEvent2(request, siteId, now = Date.now()) {
790
+ return buildEvent(request, siteId, readVercelFacts(request), now);
791
+ }
792
+
793
+ export { COUNTED_TIMING, INTERNAL_HEADER, buildEvent2 as buildEvent, createTracker2 as createTracker, parseDsn, punchline, readVercelFacts, shouldTrack };
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@punchline-analytics/next",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "See which visitors are AI agents: Next.js middleware/proxy for Punchline Analytics. Forwards a minimal, privacy-reduced event per page request.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "homepage": "https://punchlineanalytics.com/docs/install-nextjs",
8
+ "keywords": [
9
+ "analytics",
10
+ "ai-agents",
11
+ "bots",
12
+ "nextjs",
13
+ "privacy",
14
+ "cookieless"
15
+ ],
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "README.md",
25
+ "LICENSE"
26
+ ],
27
+ "peerDependencies": {
28
+ "next": ">=15"
29
+ },
30
+ "devDependencies": {
31
+ "@punchline/privacy": "0.0.0",
32
+ "@punchline/schema": "0.0.0",
33
+ "next": "16.4.1",
34
+ "tsup": "8.5.1",
35
+ "typescript": "5.9.3",
36
+ "@punchline/edge": "0.0.0"
37
+ },
38
+ "sideEffects": false,
39
+ "scripts": {
40
+ "build": "tsup"
41
+ },
42
+ "types": "./dist/index.d.ts",
43
+ "main": "./dist/index.js"
6
44
  }