UNPKG

@usenotra/geo

Version:

Request capture SDK for AI traffic attribution and agent feedback collection

298 lines (291 loc) • 7.52 kB
// src/constants.ts var DEFAULT_ENDPOINT = "https://ingest.usenotra.com"; var INGEST_PATH = "/api/geo/ingest"; var PREFETCH_PURPOSE_HEADERS = ["sec-purpose", "purpose", "x-moz"]; var INGEST_TIMEOUT_MS = 2e3; var DEFAULT_EXCLUDE = ["/api"]; var ASSET_PATH_PREFIXES = [ "/_next/", "/_nuxt/", "/_vercel/", "/_astro/", "/_app/immutable/", "/__nextjs", "/static/" ]; var LLMS_TXT_FILE = /^llms(-full)?\.txt$/i; var ASSET_EXTENSIONS = [ ".avif", ".css", ".eot", ".gif", ".ico", ".jpeg", ".jpg", ".js", ".json", ".map", ".mjs", ".mp3", ".mp4", ".otf", ".pdf", ".png", ".svg", ".ttf", ".txt", ".wasm", ".webm", ".webmanifest", ".webp", ".woff", ".woff2", ".xml", ".zip" ]; // src/send.ts function ingestUrl(endpoint) { const value = endpoint ?? DEFAULT_ENDPOINT; let end = value.length; while (end > 0 && value[end - 1] === "/") { end -= 1; } const base = value.slice(0, end); return `${base}${INGEST_PATH}`; } async function sendRequestLog(payload, options) { const send = options.fetch ?? globalThis.fetch; try { const response = await send(ingestUrl(options.endpoint), { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${options.token}` }, body: JSON.stringify(payload), keepalive: true, signal: AbortSignal.timeout(INGEST_TIMEOUT_MS) }); if (!response.ok) { void response.body?.cancel().catch(() => void 0); throw new Error(`GEO ingest request failed (HTTP ${response.status})`); } } catch (error) { reportGeoError(options.onError, error); } } function reportGeoError(onError, error) { try { onError?.(error); } catch { } } // src/exclude.ts function matchesPath(pathname, prefix) { if (prefix === "/") { return true; } const normalized = prefix.endsWith("/") ? prefix.slice(0, -1) : prefix; return pathname === normalized || pathname.startsWith(`${normalized}/`); } function isAssetPath(pathname) { for (const prefix of ASSET_PATH_PREFIXES) { if (pathname.startsWith(prefix)) { return true; } } const lastSegment = pathname.slice(pathname.lastIndexOf("/") + 1); if (LLMS_TXT_FILE.test(lastSegment)) { return false; } const dot = lastSegment.lastIndexOf("."); if (dot <= 0) { return false; } return ASSET_EXTENSIONS.includes(lastSegment.slice(dot).toLowerCase()); } function matchesRule(request, url, rule) { if (typeof rule === "string") { return matchesPath(url.pathname, rule); } if (rule instanceof RegExp) { return rule.test(url.pathname); } return rule(request, url); } function matchesAnyRule(request, url, rules) { for (const rule of rules) { if (matchesRule(request, url, rule)) { return true; } } return false; } function isExcluded(request, url, rules) { return matchesAnyRule(request, url, rules); } function shouldTrackRequest(request, url, exclude) { if (request.method.toUpperCase() !== "GET") { return false; } if (isAssetPath(url.pathname)) { return false; } return !isExcluded(request, url, exclude ?? DEFAULT_EXCLUDE); } // src/serialize.ts function header(headers, name) { return headers.get(name) ?? void 0; } function decode(value) { if (!value) { return; } try { return decodeURIComponent(value); } catch { return value; } } function readIp(headers) { const forwardedFor = headers.get("x-forwarded-for"); const first = forwardedFor?.split(",")[0]?.trim(); if (first) { return first; } return header(headers, "x-real-ip") ?? header(headers, "x-vercel-forwarded-for"); } function readGeo(headers) { const location = { country: header(headers, "x-vercel-ip-country") ?? header(headers, "cf-ipcountry"), region: header(headers, "x-vercel-ip-country-region"), city: decode(header(headers, "x-vercel-ip-city")), timezone: header(headers, "x-vercel-ip-timezone"), latitude: header(headers, "x-vercel-ip-latitude"), longitude: header(headers, "x-vercel-ip-longitude") }; const hasValue = Object.values(location).some((value) => value !== void 0); return hasValue ? location : void 0; } var TRACING_HEADERS = ["traceparent", "b3", "x-b3-traceid"]; function isPrefetch(headers) { return headers.has("next-router-prefetch") || PREFETCH_PURPOSE_HEADERS.some( (name) => headers.get(name)?.toLowerCase().includes("prefetch") ); } function readSignals(headers) { return { clientHints: headers.has("sec-ch-ua"), fetchMode: header(headers, "sec-fetch-mode") ?? null, tracing: TRACING_HEADERS.some((name) => headers.has(name)), prefetch: isPrefetch(headers) }; } function serializeRequest(request) { const { headers } = request; return { timestamp: (/* @__PURE__ */ new Date()).toISOString(), method: request.method, url: request.url, ip: readIp(headers), geo: readGeo(headers), referer: header(headers, "referer"), userAgent: header(headers, "user-agent"), accept: header(headers, "accept"), acceptLanguage: header(headers, "accept-language"), requestId: header(headers, "x-request-id") ?? header(headers, "x-vercel-id"), signals: readSignals(headers) }; } // src/tracker.ts function isSampled(sample) { if (sample === void 0 || sample >= 1) { return true; } if (sample <= 0) { return false; } return Math.random() < sample; } var Tracker = class { options; constructor(options) { this.options = options; } buildPayload(request) { let url; try { url = new URL(request.url); } catch (error) { reportGeoError(this.options.onError, error); return null; } if (!shouldTrackRequest(request, url, this.options.exclude)) { return null; } if (!isSampled(this.options.sample)) { return null; } return serializeRequest(request); } async track(request) { if (!this.options.token) { return; } try { const payload = this.buildPayload(request); if (!payload) { return; } await sendRequestLog(payload, this.options); } catch (error) { reportGeoError(this.options.onError, error); } } }; // src/netlify.ts function toGeoLocation(geo) { if (!geo) { return; } const location = { country: geo.country?.code, region: geo.subdivision?.code, city: geo.city, timezone: geo.timezone, latitude: geo.latitude === void 0 ? void 0 : String(geo.latitude), longitude: geo.longitude === void 0 ? void 0 : String(geo.longitude) }; const hasValue = Object.values(location).some((value) => value !== void 0); return hasValue ? location : void 0; } var Tracker2 = class { options; tracker; constructor(options) { this.options = options; this.tracker = new Tracker(options); } track(request, context) { try { const payload = this.tracker.buildPayload(request); if (!payload) { return; } const geo = toGeoLocation(context?.geo) ?? payload.geo; const pending = sendRequestLog({ ...payload, geo }, this.options); if (typeof context?.waitUntil === "function") { context.waitUntil(pending); } } catch (error) { reportGeoError(this.options.onError, error); } } }; function createGeoHandler(options) { const tracker = new Tracker2(options); return (request, context) => { tracker.track(request, context); }; } export { Tracker2 as Tracker, createGeoHandler };