@sentry/core
Version:
Base implementation for all Sentry JavaScript SDKs
198 lines (197 loc) • 8.54 kB
JavaScript
import { filterCollectedUrl, filterCollectedUrlQuery } from "./data-collection/filterCollectedUrl.js";
import { HTTP_REQUEST_METHOD, HTTP_ROUTE, SENTRY_ORIGIN, SENTRY_SEGMENT_NAME_SOURCE, SERVER_ADDRESS, URL_DOMAIN, URL_FRAGMENT, URL_FULL, URL_PATH, URL_PORT, URL_QUERY, URL_SCHEME, URL_TEMPLATE } from "@sentry/conventions/attributes";
// src/utils/url.ts
const DEFAULT_BASE_URL = "thismessage:/";
/**
* Checks if the URL object is relative
*
* @param url - The URL object to check
* @returns True if the URL object is relative, false otherwise
*/
function isURLObjectRelative(url) {
return "isRelative" in url;
}
/**
* Parses string to a URL object
*
* @param url - The URL to parse
* @returns The parsed URL object or undefined if the URL is invalid
*/
function parseStringToURLObject(url, urlBase) {
const isRelative = url.indexOf("://") <= 0 && url.indexOf("//") !== 0;
const base = urlBase ?? (isRelative ? DEFAULT_BASE_URL : void 0);
try {
if ("canParse" in URL && !URL.canParse(url, base)) return;
const fullUrlObject = new URL(url, base);
if (isRelative) return {
isRelative,
pathname: fullUrlObject.pathname,
search: fullUrlObject.search,
hash: fullUrlObject.hash
};
return fullUrlObject;
} catch {}
}
/**
* Takes a URL object and returns a sanitized string which is safe to use as span name
* see: https://develop.sentry.dev/sdk/data-handling/#structuring-data
*/
function getSanitizedUrlStringFromUrlObject(url) {
if (isURLObjectRelative(url)) return url.pathname;
const newUrl = new URL(url);
newUrl.search = "";
newUrl.hash = "";
if (["80", "443"].includes(newUrl.port)) newUrl.port = "";
if (newUrl.password) newUrl.password = "%filtered%";
if (newUrl.username) newUrl.username = "%filtered%";
return newUrl.toString();
}
/**
* Normalizes a query string for the `url.query` attribute, which is specced without the leading `?`.
*
* Accepts either a raw query string (`URL.search`, which includes the `?`) or an already-stripped one.
* Empty results become `undefined` so callers can assign the return value to an attribute
* unconditionally — setting an attribute to `undefined` is a no-op.
*/
function getUrlQuery(query) {
return query?.replace(/^\?/, "") || void 0;
}
/**
* Normalizes a fragment for the `url.fragment` attribute, which is specced without the leading `#`.
*
* Accepts either a raw fragment (`URL.hash`, which includes the `#`) or an already-stripped one.
* Empty results become `undefined` so callers can assign the return value to an attribute
* unconditionally — setting an attribute to `undefined` is a no-op.
*/
function getUrlFragment(fragment) {
return fragment?.replace(/^#/, "") || void 0;
}
/**
* The domain a request goes to, for the `url.domain` attribute and low-cardinality span names.
*
* Relative URLs need a `base` to resolve against — browsers have the page origin, server runtimes do
* not. URLs with no domain at all, such as data URLs, return `undefined`.
*/
function getUrlDomain(url, base) {
try {
return new URL(url, base).hostname || void 0;
} catch {
return;
}
}
function getHttpSpanNameFromUrlObject(urlObject, kind, request, routeName) {
return `${request?.method?.toUpperCase() ?? "GET"} ${routeName ? routeName : urlObject ? kind === "client" ? getSanitizedUrlStringFromUrlObject(urlObject) : urlObject.pathname : "/"}`;
}
/**
* Takes a parsed URL object and returns a set of attributes for the span
* that represents the HTTP request for that url. This is used for both server
* and client http spans.
*
* Follows https://opentelemetry.io/docs/specs/semconv/http/.
*
* @param urlObject - see {@link parseStringToURLObject}
* @param kind - The type of HTTP operation (server or client)
* @param spanOrigin - The origin of the span
* @param request - The request object, see {@link PartialRequest}
* @param routeName - The name of the route, must be low cardinality
* @param client - The client the span belongs to, used to resolve `dataCollection.urlQueryParams`.
* Falls back to the current scope's client when omitted, which is the wrong one in a multi-client setup.
* @returns The span name and attributes for the HTTP operation
*/
function getHttpSpanDetailsFromUrlObject(urlObject, kind, spanOrigin, request, routeName, client) {
const attributes = { [SENTRY_ORIGIN]: spanOrigin };
let nameSource = "url";
if (routeName) {
attributes[kind === "server" ? HTTP_ROUTE : URL_TEMPLATE] = routeName;
nameSource = "route";
}
if (request?.method) attributes[HTTP_REQUEST_METHOD] = request.method.toUpperCase();
if (urlObject) {
attributes[URL_FULL] = filterCollectedUrl(isURLObjectRelative(urlObject) ? getSanitizedUrlStringFromUrlObject(urlObject) : urlObject.href, client);
attributes[URL_QUERY] = filterCollectedUrlQuery(getUrlQuery(urlObject.search), client);
attributes[URL_FRAGMENT] = getUrlFragment(urlObject.hash);
if (urlObject.pathname) {
attributes[URL_PATH] = urlObject.pathname;
if (urlObject.pathname === "/") nameSource = "route";
}
if (!isURLObjectRelative(urlObject)) {
if (urlObject.port) attributes[URL_PORT] = Number(urlObject.port);
if (urlObject.protocol) attributes[URL_SCHEME] = urlObject.protocol.replace(/:$/, "");
if (urlObject.hostname) attributes[kind === "server" ? SERVER_ADDRESS : URL_DOMAIN] = urlObject.hostname;
}
}
if (kind === "server") attributes[SENTRY_SEGMENT_NAME_SOURCE] = nameSource;
return [getHttpSpanNameFromUrlObject(urlObject, kind, request, routeName), attributes];
}
/**
* Parses string form of URL into an object
* // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B
* // intentionally using regex and not <a/> href parsing trick because React Native and other
* // environments where DOM might not be available
* @returns parsed URL object
*/
function parseUrl(url) {
if (!url) return {};
const match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
if (!match) return {};
const query = match[6] || "";
const fragment = match[8] || "";
return {
host: match[4],
path: match[5],
protocol: match[2],
search: query,
hash: fragment,
relative: match[5] + query + fragment
};
}
/**
* Strip the query string and fragment off of a given URL or path (if present)
*
* @param urlPath Full URL or path, including possible query string and/or fragment
* @returns URL or path without query string or fragment
*/
function stripUrlQueryAndFragment(urlPath) {
return urlPath.split(/[?#]/, 1)[0];
}
/**
* Takes a URL object and returns a sanitized string which is safe to use as span name
* see: https://develop.sentry.dev/sdk/data-handling/#structuring-data
*/
function getSanitizedUrlString(url) {
const { protocol, host, path } = url;
const filteredHost = host?.replace(/^.*@/, "[filtered]:[filtered]@").replace(/(:80)$/, "").replace(/(:443)$/, "") || "";
return `${protocol ? `${protocol}://` : ""}${filteredHost}${path || ""}`;
}
/**
* Strips the content from a data URL, returning a placeholder with the MIME type.
*
* Data URLs can be very long (e.g. base64 encoded scripts for Web Workers),
* with little valuable information, often leading to envelopes getting dropped due
* to size limit violations. Therefore, we strip data URLs and replace them with a
* placeholder.
*
* @param url - The URL to process
* @param includeDataPrefix - If true, includes the first 10 characters of the data stream
* for debugging (e.g., to identify magic bytes like WASM's AGFzbQ).
* Defaults to true.
* @returns For data URLs, returns a short format like `data:text/javascript;base64,SGVsbG8gV2... [truncated]`.
* For non-data URLs, returns the original URL unchanged.
*/
function stripDataUrlContent(url, includeDataPrefix = true) {
if (url.startsWith("data:")) {
const match = url.match(/^data:([^;,]+)/);
const mimeType = match ? match[1] : "text/plain";
const isBase64 = url.includes(";base64,");
const dataStart = url.indexOf(",");
let dataPrefix = "";
if (includeDataPrefix && dataStart !== -1) {
const data = url.slice(dataStart + 1);
dataPrefix = data.length > 10 ? `${data.slice(0, 10)}... [truncated]` : data;
}
return `data:${mimeType}${isBase64 ? ",base64" : ""}${dataPrefix ? `,${dataPrefix}` : ""}`;
}
return url;
}
export { getHttpSpanDetailsFromUrlObject, getSanitizedUrlString, getSanitizedUrlStringFromUrlObject, getUrlDomain, getUrlFragment, getUrlQuery, isURLObjectRelative, parseStringToURLObject, parseUrl, stripDataUrlContent, stripUrlQueryAndFragment };
//# sourceMappingURL=url.js.map