Functions: peepless/server
From src/server.ts and the modules it re-exports, read at build time.
SOURCES
valueconst SOURCES: readonly Source[]
countryOf()
functionfunction countryOf(req: Request): string | null
The default country reader: a two-letter code from the host's geo header, lowercased, or null.
createHandler()
functionfunction createHandler(opts: HandlerOptions): (req: Request) => Promise<Response>
The counter endpoint. POST a beacon from peepless's client; anything else is refused.
Successful and silently-dropped beacons (bots, over the limit) both answer 204, so a
bot learns nothing from the reply.
createStatsHandler()
functionfunction createStatsHandler(opts: StatsOptions): (req: Request) => Promise<Response>
The read side over HTTP: GET ?project=my-app&since=2026-11-01&until=2026-11-30 with
Authorization: Bearer <token> answers a Summary as JSON (openapi.yaml). since and
until default to the last 30 days, today included. Serve it on its own path, never the
beacon's: it is for your server or a stats page's server, and its token never goes to a browser.
d1Store()
functionfunction d1Store(db: D1Like): ReadableStore
isBot()
functionfunction isBot(ua: string | null | undefined): boolean
True when the User-Agent names a bot, crawler, link previewer or automation tool.
Only a positive match drops a count: a missing or unusual User-Agent may be a
proxy's doing, and treating it as a bot could silently stop every count.
memoryStore()
functionfunction memoryStore(): ReadableStore & { totals: Map<string, number> }Counts in memory, for tests and local development. totals is "day|project|counter" → count.
postgresStore()
functionfunction postgresStore(query: Query): ReadableStore
readCounts()
functionasync function readCounts(store: ReadableStore, query: { project: string; since: string; until: string }): Promise<CountRow[]>Reads a project's counts for a range of UTC days (YYYY-MM-DD, both inclusive), checking the
query first. Pass the rows to summarize for a report.
sourceOf()
functionfunction sourceOf(ref: unknown, ownHosts: readonly string[], sources: readonly Source[] = SOURCES): string
The source key for a referring hostname: "direct" when there is none or it is the site itself, "other" when no source matches.
summarize()
functionfunction summarize(rows: readonly CountRow[], range?: { since: string; until: string }): SummaryTurns stored rows into a report: totals, sources, campaigns, countries, pages, events and a
per-day series. With range, days covers every day in it; without, the days the rows span.
supabaseStore()
functionfunction supabaseStore(opts: { url: string; key: string; fetch?: typeof fetch }): ReadableStoreCounts in Supabase, through peepless_add and peepless_counts in
starters/supabase/schema.sql. Use the service-role or a secret key, on the server only.
CountRow
typeinterface CountRow {
/** UTC day, YYYY-MM-DD. */
day: string
counter: string
count: number
}One stored total: a counter's count for one UTC day.
D1Like
typeinterface D1Like {
prepare(sql: string): D1StatementLike
batch(statements: D1StatementLike[]): Promise<unknown>
}The parts of a D1 binding peepless uses, so no Cloudflare types are needed to import it.
D1StatementLike
typeinterface D1StatementLike {
bind(...values: unknown[]): D1StatementLike
all<T = Record<string, unknown>>(): Promise<{ results: T[] }>
}
DayTotals
typeinterface DayTotals {
day: string
pageviews: number
visits: number
humans: number
}One day's headline numbers.
HandlerOptions
typeinterface HandlerOptions {
/** Projects by name, the name each client passes as `project`. */
projects: Record<string, ProjectConfig>
store: Store
/** Beacons per address per project per minute before the rest are dropped. Default 60. */
perMinute?: number
/**
* The visitor's two-letter country code, or null. Default: the first of
* x-vercel-ip-country, cf-ipcountry and cloudfront-viewer-country. Pass `() => null`
* to count no countries.
*/
country?: (req: Request) => string | null | undefined
/** Where a visit came from, first match wins. Default: SOURCES. */
sources?: readonly Source[]
/**
* The address the rate limit keys on. Default: the first x-forwarded-for entry, then x-real-ip,
* then cf-connecting-ip. A client can set x-forwarded-for itself on a host that passes it
* through untouched, so name the header your host sets: on Cloudflare,
* `(req) => req.headers.get('cf-connecting-ip')`. Return null to put everyone in one bucket.
* The address is never stored, and the limit lives in this instance's memory.
*/
address?: (req: Request) => string | null | undefined
/**
* Decides whether a User-Agent is a bot, whose beacons are dropped. Default: the built-in
* `isBot`. Wrap it to add your own: `(ua) => isBot(ua) || /mymonitor/i.test(ua ?? '')`.
*/
isBot?: (ua: string | null) => boolean
}
ProjectConfig
typeinterface ProjectConfig {
/** The site's origin(s), e.g. "https://example.com". Beacons from anywhere else are refused. "www." is accepted too. */
origin: string | readonly string[]
/** The "used it" events this project may count, e.g. ["signed_up", "exported"]. */
events?: readonly string[]
/** The page-type patterns the client sends (the same list as its `routes`). Anything else counts as page:other. */
routes?: readonly string[]
/**
* Campaign tags this project counts as via:<tag>, from ?ref= (or ?utm_source=) on a visit,
* e.g. ["newsletter", "launch"]. The client's `campaigns` lists the same. Any other tag counts as via:other.
*/
campaigns?: readonly string[]
}
Query
typetype Query = (text: string, params: unknown[]) => Promise<readonly Record<string, unknown>[]>
Runs one SQL statement with $1-style parameters and resolves to its rows. Adapters:
- pg: (text, params) => pool.query(text, params).then((r) => r.rows)
- postgres.js: (text, params) => sql.unsafe(text, params)
- Neon: (text, params) => neon(process.env.DATABASE_URL).query(text, params)
ReadableStore
typeinterface ReadableStore extends Store {
/** Every count for the project from `since` to `until`, both whole UTC days, inclusive. */
read(project: string, since: string, until: string): Promise<CountRow[]>
}A store you can also read back from: what readCounts and createStatsHandler need.
Source
typeinterface Source {
key: string
/** "example.com" matches it and its subdomains; "google.*" matches google.com, google.co.uk and so on. */
hosts: readonly string[]
}
StatsOptions
typeinterface StatsOptions {
store: ReadableStore
/**
* The bearer token a reader must send: a long random secret (at least 16 characters),
* not the database key. Until one is set, every request gets 503.
*/
token: string | undefined
}
Store
typeinterface Store {
/** Add one to each counter's total for this UTC day. */
add(project: string, counters: readonly string[], day: string): Promise<void>
}
Summary
typeinterface Summary {
pageviews: number
visits: number
/** Engaged visits: a real input, or 10 s on screen. */
humans: number
/** `from:*`, by source key ("search", "direct"), largest first. */
sources: Record<string, number>
/** `via:*`, by campaign tag, largest first. Empty for a project without `campaigns`. */
campaigns: Record<string, number>
/** `country:*`, by lowercase country code ("us", "xx" for unknown), largest first. */
countries: Record<string, number>
/** `page:*`, by route pattern ("/blog/*", "other"), largest first. */
pages: Record<string, number>
/** The project's own events, largest first. */
events: Record<string, number>
/** Every day in the range, oldest first, with zeros for days with nothing. */
days: DayTotals[]
}A report built from counter names, so nobody has to parse from: by hand.