justintsus-experiment Public
// The canonical form of a search query (search/api.ts): what the pages put in ?q=, so a URL// round-trips. Terms in input order joined by single spaces, keys lowercase, values normalized, a// value bare when nothing in it would read differently bare, otherwise quoted with \ and " escaped.import type { DateFilter, SearchQuery, Term, UserRef } from "./ast.ts";// The patterns the parser reads a bare term with: free text that matches one must be quoted to stay// free text.export const QUALIFIER_RE = /^[A-Za-z]+(-[A-Za-z]+)*:/;export const NUMBER_RE = /^#[1-9][0-9]{0,8}$/;const BARE_RE = /^[^\s"]+$/;export function quote(v: string): string { return `"${v.replace(/[\\"]/g, (c) => `\\${c}`)}"`;}export function qualifierValue(v: string): string { return BARE_RE.test(v) ? v : quote(v);}export function textValue(v: string): string { return BARE_RE.test(v) && !v.startsWith("-") && !QUALIFIER_RE.test(v) && !NUMBER_RE.test(v) ? v : quote(v);}export function userText(u: UserRef): string { return u.kind === "me" ? "@me" : u.kind === "id" ? u.id : u.slug;}export function dateText(f: DateFilter): string { switch (f.kind) { case "day": return f.day.text; case "cmp": return `${f.op}${f.day.text}`; case "range": return `${f.from ? f.from.text : "*"}..${f.to ? f.to.text : "*"}`; case "age": return `${f.op}${f.n}${f.unit}`; }}// One term's canonical text: also what duplicates are recognized by.export function termText(t: Term): string { const neg = "neg" in t && t.neg ? "-" : ""; switch (t.kind) { case "is": return `${neg}is:${t.value}`; case "label": return `${neg}label:${qualifierValue(t.value)}`; case "no": return `no:${t.value}`; case "author": return `${neg}author:${qualifierValue(userText(t.user))}`; case "review-requested": return `${neg}review-requested:${qualifierValue(userText(t.user))}`; case "sort": return `sort:${t.value}`; case "date": return `${t.field}:${qualifierValue(dateText(t.filter))}`; case "number": return `#${t.value}`; case "text": return `${neg}${textValue(t.value)}`; }}export function serializeQuery(query: SearchQuery): string { return query.terms.map(termText).join(" ");}