Skip to content

@xtandard/links

@xtandard/links — self-hosted, embeddable branded short links: a memory-first redirect plane, click analytics, conversion attribution and deep links over the storage you already run.

The root export: the core and its types (also on /core and /schema), the redirect handler and resolver (also on /redirect), click enrichment (bots, user agents, geo, privacy), the analytics sink contract and KV rollup sink, rules, deep-link helpers, the hooks contract and the storage contract, the admin panel handler (createFetchHandler), analytics viewer tokens and the auth/authorization contracts. Storage drivers, analytics adapters, auth providers, framework adapters and the React embeds are separate subpaths with optional peer dependencies.

import { … } from "@xtandard/links";

Also re-exports symbols of @xtandard/links/core, @xtandard/links/schema, @xtandard/links/redirect, @xtandard/links/deeplinks, documented on those pages.

Name Summary
addEventToMetrics Add event to metrics in place.
addMetrics Add b into a in place.
aggregateEvents Reference aggregation over an in-memory event list — the semantics every sink must reproduce (the memory sink is exactly this).
bucketRange Every bucket start in [from, to) for the interval, ascending.
bucketStart Align an epoch-millis timestamp down to the interval start (UTC).
buildDestination Merge UTM parameters (never overriding ones already on the destination), forward the short URL’s query (destination params win), and append the click id. Non-http(s) URLs (app schemes) get the same treatment when they parse as URLs; anything unparseable is returned untouched.
buildOpenApiDocument Build the OpenAPI 3.1 document for the admin API.
clientIp Best-effort client IP: CF-Connecting-IP, True-Client-IP, X-Real-IP, then the first X-Forwarded-For entry. Only trust these behind a proxy that sets them; pass getIp to the redirect handler otherwise.
cloudflareGeo Cloudflare: request.cf (Workers) with a CF-IPCountry header fallback (any Cloudflare-proxied origin with IP geolocation enabled).
continentOf Continent code for an ISO alpha-2 country, if known.
createClickIngestor Create a batching ingestor in front of an analytics sink.
createFetchHandler Build the panel fetch handler.
createResolver Create a resolver over a core.
createViewerToken Mint a viewer token. Call this server-side — anyone holding the secret can mint tokens for any tenant.
dailySalt The salt for a given UTC day.
dimensionValue The value of dimension on event ("(none)" when absent). Lead and sale events carry the dimensions of the click they are attributed to.
durationToMs Convert a LinksDuration (5000, "5s", "30m", "2h", "90d") to milliseconds. Throws on malformed strings or negative numbers.
edgeHeadersGeo Fastly / CloudFront / generic proxies: tries the common country headers.
emptyMetrics Zero-valued metrics.
evaluateRules Evaluate a link’s rules. Returns the first matching rule’s destination (or variant), or null when no rule matches.
fnv1a FNV-1a 32-bit hash.
generateSlug Generate a random slug from the domain’s alphabet (Web Crypto).
hashPassword Hash a password for storage on a link.
headerGeo Read geo from arbitrary request headers (any CDN or proxy that sets them).
idPattern Regex an id of the given prefix must match.
idTime The creation time (epoch millis) encoded in an id, or NaN if malformed.
isBot True when the user agent looks automated: crawlers, unfurlers, monitors, headless browsers, HTTP libraries — or is missing entirely.
isMutatingAction True if the action mutates state.
isPreviewBot True when the user agent belongs to a link-preview unfurler (Slack, X, iMessage, …).
matchesCondition Evaluate one condition against the visitor.
matchesQuery Whether event passes the query’s scope (tenant, time, links, filters).
mergeUtm Merge two UTM sets; primary wins.
newId Generate a new time-sortable id, e.g. newId("lnk") → "lnk_01JD…". Ids minted in the same (or an earlier) millisecond increment the previous random part, so creation order and sort order always agree.
normalizeGeo Fill continent from country when missing and uppercase codes.
optedOut Whether the request opted out of tracking (DNT / GPC).
parseAcceptLanguage Parse Accept-Language into primary tags, by q-value, lowercase, de-duplicated.
parseUserAgent Parse a user agent into device / OS / browser families.
pgListenNotify A WatchSubscribe backed by Postgres LISTEN/NOTIFY. Pair with withWatch for the postgres or drizzle-over-pg adapters. Your migration owns the trigger that pg_notifys channel with the changed key as payload; this only LISTENs. client must be a dedicated pg Client (not a Pool).
pickVariant Pick a variant deterministically for seed (same seed → same variant). Returns the variant and its id (explicit id or its index).
protectIp Apply the IP privacy mode.
referrerHost Lowercase referrer host, or "(direct)".
requirePeer Helper for adapters whose subpath requires an optional peer dependency. Throws a clear, actionable error when the peer is missing.
slugKey The lookup key for a slug: NFC-normalized, lowercased unless the domain is case-sensitive.
slugProblem Why a slug is invalid, or null when it is valid.
sortBreakdown Sort + truncate breakdown rows: clicks desc, then leads, sales, key asc.
truncateIp Truncate an IP: last IPv4 octet → 0; IPv6 keeps the first 3 hextets.
utmFromQuery Extract UTM values from a query string.
validateDestinationUrl Validate a destination URL: an absolute URL of at most 8192 characters, never javascript:, data:, vbscript:, file:, blob: or about: (the kit’s validateUrl), then the links policy.
validateDomainInput Validate a domain input. With partial, hostname may be omitted (update).
validateLinkInput Validate a link create/update input (structure + URLs + slug).
validateTenantInput Validate a tenant input.
vercelGeo Vercel: x-vercel-ip-* headers.
verifyPassword Verify a password against a stored hash.
verifyViewerToken Verify a viewer token: format, signature (constant time), then expiry. Returns the claims on success; throws ViewerTokenError otherwise.
visitorHash Compute the daily visitor hash, or undefined when disabled or no IP.
Name Summary
AnalyticsBreakdownRow One breakdown row.
AnalyticsBucket One timeseries bucket.
AnalyticsCapabilities What a sink can do; the UI and API adapt to it.
AnalyticsMetrics Counters reported for every bucket and breakdown row.
AnalyticsQuery An analytics query, always scoped to one tenant.
AnalyticsResult Result of AnalyticsSink.query.
AnalyticsSink The analytics port.
BuildDestinationInput Options for buildDestination.
ClickIngestor A running ingestor.
ClickIngestorOptions Options for createClickIngestor.
CreateFetchHandlerResult Return shape of createFetchHandler.
EventsQuery Query for raw recent events.
HeaderGeoOptions Options for headerGeo.
LinksPanelOptions Options for the panel handler (shared by every framework adapter).
LinksPortalOptions Viewer-token composition for the panel: when set, requests bearing a valid lvt_… token act as a viewer principal scoped to the token’s tenant.
LinkValidationOptions Options for validateLinkInput.
OpenApiOptions Options for buildOpenApiDocument.
ParsedUserAgent Parsed user agent.
PrivacyOptions Privacy options. Defaults are the most private useful setting.
Resolution A resolved domain + link.
Resolver The resolver.
ResolverOptions Options for createResolver.
ResolverStats Cache statistics.
RuleMatch The outcome of rule evaluation.
UrlPolicyOptions Options for destination URL policy.
ViewerTokenClaims The claims carried inside a viewer token.
ViewerTokenOptions Options for createViewerToken.
VisitorContext What the rules engine knows about the visitor. All string values lowercase except country/continent.
Name Summary
AfterEvent Event delivered to LinksHooks.after — the committed mutation.
AfterEventType
AnalyticsDimension Dimensions an analytics query can group or filter by.
AnalyticsInterval Time bucket size for timeseries.
AuthorizationProvider Decides whether an action is permitted.
AuthorizeInput Input passed to AuthorizationProvider.authorize.
BeforeEvent Event delivered to LinksHooks.before — the proposed mutation.
BeforeEventType The discriminant strings of BeforeEvent / AfterEvent.
GeoResolver Resolve geo information for a request. May be async; must not throw (errors are caught).
HookErrorReporter Reports an error thrown by an after hook.
IdPrefix Prefixes for generated ids.
LinksAction The full set of authorizable actions.
LinksCorsOptions CORS for the panel: origin (a string, a list, or a predicate; "*" with credentials echoes the caller’s origin), credentials, methods, headers and maxAge.
LinksHooks A control-plane hook. Implement before, after, or both.
LinksHooksInput Accepts a single hook, an array, or nothing.
LinksResource The resource an action targets. Every resource carries the tenant it belongs to ("*" for “all tenants”, e.g. listing tenants; absent for shared domains and the global audit log), plus the link id or hostname when the action targets one record.
UserAgentParser A user-agent parser.
ViewerTokenError An invalid viewer token (see the ViewerTokenError class).
WaitUntil Something that keeps a background promise alive (Workers / Vercel waitUntil).
Name Summary
ANALYTICS_DIMENSIONS Every dimension, in display order.
DEFAULT_RESERVED_SLUGS Paths the redirect handler never treats as slugs.
DEFAULT_SLUG_LENGTH Default generated slug length.
DEFAULT_VIEWER_ACTIONS What a viewer may do when neither the token nor the panel says otherwise.
DEFAULT_VIEWER_TOKEN_EXPIRES_IN Default token lifetime.
defaultHookErrorReporter Default after-hook error reporter: warn with the [@xtandard/links] prefix, never throw.
HOSTNAME_REGEX Hostname: lowercase labels, optional port is not allowed.
INTERNAL_QUERY_PARAMS Query parameters the redirect consumes and never forwards.
KEY_REGEX Allowed characters for tenant keys and external ids.
MAX_SLUG_LENGTH Maximum slug length.
MUTATING_ACTIONS Actions that mutate state — blocked in readonly mode.
NONE_KEY Value used for events that lack a dimension.
SLUG_ALPHABET Characters generated slugs use on case-insensitive domains (no look-alikes).
VERSION The published package version.
VIEWER_GRANTABLE_ACTIONS Actions a viewer token can ever grant. Everything here is confined to the token’s tenant (and link set); tenant/domain management, the global audit log and minting further tokens are never grantable.
VIEWER_TOKEN_PREFIX Prefix of every viewer token.
ViewerTokenError Thrown by verifyViewerToken for any invalid token — malformed, bad signature, or expired — and by createViewerToken for invalid input. Maps to HTTP 401 at the API layer.
Name Documented on
createKvAnalytics @xtandard/links/analytics/kv
KvAnalytics @xtandard/links/analytics/kv
KvAnalyticsOptions @xtandard/links/analytics/kv
RollupBucket @xtandard/links/analytics/kv
UnsupportedQueryError @xtandard/links/analytics/kv