@usenotra/geo
Version:
Request capture SDK for AI traffic attribution and agent feedback collection
81 lines (77 loc) • 2.35 kB
JavaScript
// src/constants.ts
var JOURNEY_ID_PARAM = "ntr";
var JOURNEY_ID_PATTERN = /^[A-Za-z0-9_-]{8,32}$/;
// src/link-target.ts
var HTTP_PROTOCOL = /^https?:\/\//i;
var EXISTING_JOURNEY_PARAM = new RegExp(`[?&](?:amp;)?${JOURNEY_ID_PARAM}=`);
var RESOLVE_BASE = "https://journey.invalid";
function isSameHost(target, host) {
if (!host) {
return false;
}
try {
const parsed = new URL(target, RESOLVE_BASE);
return parsed.hostname.toLowerCase() === host.trim().toLowerCase();
} catch {
return false;
}
}
function isTaggableTarget(target, host) {
const value = target.trim();
if (value.length === 0 || value.startsWith("#") || value.startsWith("<")) {
return false;
}
if (EXISTING_JOURNEY_PARAM.test(value)) {
return false;
}
if (value.startsWith("//")) {
return isSameHost(value, host);
}
if (value.startsWith("/")) {
return true;
}
if (HTTP_PROTOCOL.test(value)) {
return isSameHost(value, host);
}
return false;
}
function appendJourneyParam(target, journeyId, ampersand = "&") {
const hashIndex = target.indexOf("#");
const base = hashIndex === -1 ? target : target.slice(0, hashIndex);
const fragment = hashIndex === -1 ? "" : target.slice(hashIndex);
let separator = "?";
if (base.endsWith("?")) {
separator = "";
} else if (base.includes("?")) {
separator = ampersand;
}
return `${base}${separator}${JOURNEY_ID_PARAM}=${journeyId}${fragment}`;
}
// src/html.ts
var ANCHOR_TAG = /<a\b[^>]*>/gi;
var HREF_ATTRIBUTE = /(\shref\s*=\s*)(?:"([^"]*)"|'([^']*)')/i;
var ENCODED_AMPERSAND = "&";
function tagHtmlLinks(html, journeyId, options = {}) {
if (!JOURNEY_ID_PATTERN.test(journeyId)) {
return html;
}
return html.replace(
ANCHOR_TAG,
(tag) => tag.replace(
HREF_ATTRIBUTE,
(match, prefix, doubleQuoted, singleQuoted) => {
const target = doubleQuoted ?? singleQuoted;
if (target === void 0) {
return match;
}
if (!isTaggableTarget(target, options.host)) {
return match;
}
const quote = doubleQuoted === void 0 ? "'" : '"';
const ampersand = target.includes(ENCODED_AMPERSAND) ? ENCODED_AMPERSAND : "&";
return `${prefix}${quote}${appendJourneyParam(target, journeyId, ampersand)}${quote}`;
}
)
);
}
export { tagHtmlLinks };