Google Flights MCP, CLI and Python Library
feat(js): add Google Flights booking links to the TypeScript library (#191)
Punit Arani121d34fea056
diff --git a/fli-js/README.md b/fli-js/README.mdindex 926d224..70f3c8d 100644--- a/fli-js/README.md+++ b/fli-js/README.md@@ -65,6 +65,35 @@ const filters = new DateSearchFilters({const dates = await new SearchDates().search(filters);```+### Booking links++Turn search results into clickable Google Flights links — no extra network+call, fully deterministic.++```ts+import { googleFlightsUrl, SearchFlights } from "fli-js";++const search = new SearchFlights();+const results = await search.search(filters, { currency: "USD" });++// Per-flight deep link: opens the specific itinerary's booking page+// (vendor fares + "Continue" CTA) via a `tfs` protobuf token.+const first = results?.[0];+if (first) {+ console.log(search.buildFlightBookingUrl(first, { currency: "USD" }));+ // https://www.google.com/travel/flights/booking?tfs=…&curr=USD+}++// Search-level deep link: route + dates pre-filled (handy for a date result+// or a quick "view on Google Flights" link).+console.log(googleFlightsUrl("JFK", "LHR", "2026-12-25", null, { currency: "USD" }));+// https://www.google.com/travel/flights?q=Flights%20from%20JFK%20to%20LHR%20on%202026-12-25&curr=USD+```++`buildFlightBookingUrl` accepts a single `FlightResult` (one-way) or an array+of them (round-trip / multi-city). It never throws — on malformed input it+falls back to the generic Google Flights URL.+## HTTP / proxy configurationThe TypeScript port uses native `fetch` (Bun's built-in) and replaces@@ -92,9 +121,10 @@ Set the per-request timeout with `FLI_TIMEOUT=30` (seconds) or via the- `fli-js/models` — `Airport`, `Airline`, `FlightSearchFilters`, `DateSearchFilters`,`FlightSegment`, `FlightResult`, `BookingOption`, all enums.- `fli-js/core` — string-to-enum parsers, segment builders, airport search,- currency token decoders.-- `fli-js/search` — `SearchFlights`, `SearchDates`, `Client`, error classes,- protobuf token helpers (`buildBookingToken`, `extractBookingTokenFromTfu`).+ currency token decoders, deep-link builder (`googleFlightsUrl`).+- `fli-js/search` — `SearchFlights` (incl. `buildFlightBookingUrl`),+ `SearchDates`, `Client`, error classes, protobuf token helpers+ (`buildBookingToken`, `buildTfsToken`, `extractBookingTokenFromTfu`).## Development@@ -116,8 +146,10 @@ Python upstream:- `FlightSearchFilters.format()` produces structurally identicalnested-list payloads (see `tests/integration/filter_format_snapshots.test.ts`).-- `buildBookingToken(...)` reproduces a captured live booking-page token- byte-for-byte (see `tests/search/proto.test.ts`).+- `buildBookingToken(...)` and `buildTfsToken(...)` reproduce captured live+ booking-page tokens byte-for-byte (see `tests/search/proto.test.ts`); the+ resulting `buildFlightBookingUrl(...)` output matches the Python library+ character-for-character.- The wire-format parser handles both the legacy single-chunk JSONPshape and the multi-chunk format used by `GetBookingResults`.diff --git a/fli-js/src/core/index.ts b/fli-js/src/core/index.tsindex c09ee9f..d7d049b 100644--- a/fli-js/src/core/index.ts+++ b/fli-js/src/core/index.ts@@ -18,6 +18,11 @@ export {formatPriceAxisLabel,} from "./currency.ts";export { formatIsoDate, ISO_DATE_RE, parseIsoDate } from "./dates.ts";+export {+ type GoogleFlightsUrlOptions,+ googleFlightsUrl,+ withLocaleParams,+} from "./links.ts";export {ParseError,parseAirlines,diff --git a/fli-js/src/core/links.ts b/fli-js/src/core/links.tsnew file mode 100644index 0000000..1694981--- /dev/null+++ b/fli-js/src/core/links.ts@@ -0,0 +1,72 @@+/**+ * Shared URL helpers for Google Flights deep links.+ *+ * Consumers can surface a clickable Google Flights link alongside search+ * results so a user can open the route (and complete a booking) in a+ * browser. The natural-language `q` form used here is the same one Google's+ * own frontend accepts.+ *+ * `withLocaleParams` lives here (rather than in `search/`) so the core layer+ * stays free of any dependency on the search package; `search/urls.ts`+ * re-exports it for backwards compatibility.+ *+ * 1:1 port of fli/core/links.py.+ */++const GOOGLE_FLIGHTS_URL = "https://www.google.com/travel/flights";++/**+ * Append optional `curr`/`hl`/`gl` parameters to a URL.+ *+ * - `currency` is uppercased ("usd" → "USD") because Google rejects lowercase+ * codes silently.+ * - `language` is passed through verbatim (BCP-47).+ * - `country` is uppercased (ISO 3166-1 alpha-2).+ *+ * All values are percent-encoded; returns `url` unchanged when all three are null.+ */+export function withLocaleParams(+ url: string,+ currency: string | null | undefined,+ language: string | null | undefined,+ country: string | null | undefined,+): string {+ const params: string[] = [];+ if (currency) params.push(`curr=${encodeURIComponent(currency.toUpperCase())}`);+ if (language) params.push(`hl=${encodeURIComponent(language)}`);+ if (country) params.push(`gl=${encodeURIComponent(country.toUpperCase())}`);+ if (params.length === 0) return url;+ const sep = url.includes("?") ? "&" : "?";+ return `${url}${sep}${params.join("&")}`;+}++export interface GoogleFlightsUrlOptions {+ currency?: string | null;+ language?: string | null;+ country?: string | null;+}++/**+ * Build a shareable Google Flights deep link for a route and dates.+ *+ * `origin` and `destination` are bare IATA codes (e.g. `"JFK"`). The returned+ * URL pre-fills the route and outbound date (plus the return date for round+ * trips); locale knobs (`curr`/`hl`/`gl`) are appended when supplied.+ */+export function googleFlightsUrl(+ origin: string,+ destination: string,+ departureDate: string,+ returnDate?: string | null,+ options: GoogleFlightsUrlOptions = {},+): string {+ let query = `Flights from ${origin} to ${destination} on ${departureDate}`;+ if (returnDate) query += ` through ${returnDate}`;+ const url = `${GOOGLE_FLIGHTS_URL}?q=${encodeURIComponent(query)}`;+ return withLocaleParams(+ url,+ options.currency ?? null,+ options.language ?? null,+ options.country ?? null,+ );+}diff --git a/fli-js/src/search/flights.ts b/fli-js/src/search/flights.tsindex eded6a6..77064ed 100644--- a/fli-js/src/search/flights.ts+++ b/fli-js/src/search/flights.ts@@ -4,6 +4,7 @@* 1:1 port of fli/search/flights.py.*/+import type { GoogleFlightsUrlOptions } from "../core/links.ts";import type { BookingOption, FlightResult } from "../models/google-flights/base.ts";import { TripType } from "../models/google-flights/base.ts";import { FlightSearchFilters } from "../models/google-flights/flights.ts";@@ -11,7 +12,7 @@ import { type Client, getClient } from "./client.ts";import { parallelMap } from "./concurrency.ts";import { parseBookingChunk, parseFlightRow } from "./decoders.ts";import { SearchParseError } from "./exceptions.ts";-import { buildBookingToken } from "./proto.ts";+import { buildBookingToken, buildTfsToken, type LegSpec } from "./proto.ts";import { withLocaleParams } from "./urls.ts";import { iterWrbChunks, parseFirstWrbPayload } from "./wire.ts";@@ -30,6 +31,9 @@ export interface BookingOptions {sessionId?: string | null;}+/** Locale knobs for {@link SearchFlights.buildFlightBookingUrl} (alias of the core options). */+export type BookingUrlOptions = GoogleFlightsUrlOptions;+export class SearchFlights {static readonly BASE_URL ="https://www.google.com/_/FlightsFrontendUi/data/travel.frontend.flights.FlightsFrontendService/GetShoppingResults";@@ -201,6 +205,66 @@ export class SearchFlights {return out;}+ /**+ * Build a Google Flights deep-link URL for a specific itinerary.+ *+ * Constructs `https://www.google.com/travel/flights/booking?tfs=…` that opens+ * the booking page pre-loaded with the given itinerary — the airline/OTA fare+ * options and the "Continue" booking CTA included.+ *+ * The `tfs` itinerary token is fully deterministic (built from the flight's+ * airports, dates and flight numbers); no session id or network round-trip is+ * required, so the same itinerary always yields the same URL. This method+ * never throws — on malformed input it falls back to the generic Google+ * Flights URL.+ *+ * @param flight A single `FlightResult` (one-way / single segment) or an+ * array of them (round-trip / multi-city, one element per travel direction).+ */+ buildFlightBookingUrl(+ flight: FlightResult | FlightResult[],+ options: BookingUrlOptions = {},+ ): string {+ const results: FlightResult[] = Array.isArray(flight) ? flight : [flight];+ // Round-trip is exactly 2 segments; one-way and multi-city (3+) both use+ // isOneWay=true (f19=2). Only round-trip sets f19=1.+ const isOneWay = results.length !== 2;++ const iata = (x: unknown): string => String(x).replace(/^_/, "");+ // Match the decoder, which stores datetimes with local components+ // (new Date(y, m-1, d, h, min)); read them back the same way.+ const depDate = (d: Date): string => {+ const y = d.getFullYear();+ const m = String(d.getMonth() + 1).padStart(2, "0");+ const day = String(d.getDate()).padStart(2, "0");+ return `${y}-${m}-${day}`;+ };++ let url: string;+ try {+ const segments: LegSpec[][] = results.map((result) =>+ result.legs.map((leg) => ({+ origin: iata(leg.departure_airport),+ depDate: depDate(leg.departure_datetime),+ dest: iata(leg.arrival_airport),+ airline: iata(leg.airline),+ flightNumber: leg.flight_number,+ })),+ );+ const tfs = buildTfsToken(segments, { isOneWay });+ url = `https://www.google.com/travel/flights/booking?tfs=${tfs}`;+ } catch {+ url = "https://www.google.com/travel/flights";+ }++ return withLocaleParams(+ url,+ options.currency ?? null,+ options.language ?? null,+ options.country ?? null,+ );+ }+private _captureSessionId(inner: unknown): void {if (!Array.isArray(inner)) return;const first = inner[0];diff --git a/fli-js/src/search/index.ts b/fli-js/src/search/index.tsindex 27f0a45..cf557ab 100644--- a/fli-js/src/search/index.ts+++ b/fli-js/src/search/index.ts@@ -19,14 +19,18 @@ export {} from "./exceptions.ts";export {type BookingOptions,+ type BookingUrlOptions,SearchFlights,type SearchOptions,} from "./flights.ts";export {+ type BuildTfsTokenOptions,buildBookingToken,+ buildTfsToken,decodeBookingToken,extractBookingTokenFromTfu,extractSessionIdFromTfu,+ type LegSpec,} from "./proto.ts";export { withLocaleParams } from "./urls.ts";export { iterWrbChunks, parseFirstWrbPayload } from "./wire.ts";diff --git a/fli-js/src/search/proto.ts b/fli-js/src/search/proto.tsindex 4227f54..abe42ec 100644--- a/fli-js/src/search/proto.ts+++ b/fli-js/src/search/proto.ts@@ -288,3 +288,124 @@ export function extractSessionIdFromTfu(tfu: string): string {}return session;}++// ---------------------------------------------------------------------------+// Deep-link URL parameter builder (tfs)+// ---------------------------------------------------------------------------++/**+ * Encode a non-negative BigInt as a protobuf varint.+ *+ * The `number`-based {@link varint} cannot represent values above+ * `Number.MAX_SAFE_INTEGER`; the `tfs` token's f16 field is max-uint64, so it+ * needs a BigInt encoder.+ */+function varintBig(value: bigint): Uint8Array {+ if (value < 0n) throw new Error("varint encoder takes non-negative ints only");+ const bytes: number[] = [];+ let v = value;+ while (true) {+ const byte = Number(v & 0x7fn);+ v >>= 7n;+ if (v > 0n) {+ bytes.push(byte | 0x80);+ } else {+ bytes.push(byte);+ break;+ }+ }+ return new Uint8Array(bytes);+}++/**+ * Encode bytes as URL-safe base64 without `=` padding.+ *+ * The `tfs` query parameter uses the urlsafe alphabet (`-`/`_`) with padding+ * stripped.+ */+function toUrlsafeB64(bytes: Uint8Array): string {+ if (typeof Buffer !== "undefined") {+ return Buffer.from(bytes).toString("base64url");+ }+ return base64Encode(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");+}++/** One physical leg within a booking-URL segment. */+export interface LegSpec {+ /** IATA code of the departure airport (e.g. `"SFO"`). */+ origin: string;+ /** Departure date in `YYYY-MM-DD` format. */+ depDate: string;+ /** IATA code of the arrival airport (e.g. `"PHX"`). */+ dest: string;+ /** Airline IATA code (e.g. `"AA"`). */+ airline: string;+ /** Flight number string (e.g. `"2413"`). */+ flightNumber: string;+}++export interface BuildTfsTokenOptions {+ /** `true` for one-way (incl. multi-city); `false` for round-trip. */+ isOneWay?: boolean;+}++/**+ * Build the `tfs` query parameter for a Google Flights deep-link URL.+ *+ * The `tfs` token encodes the complete itinerary — one segment per travel+ * direction, each segment containing one leg per physical flight. It is+ * deterministic (no session id required) and can be constructed purely from+ * search-result data.+ *+ * 1:1 port of fli/search/_proto.py::build_tfs_token.+ *+ * @throws Error when `segments` is empty or any segment has no legs.+ */+export function buildTfsToken(segments: LegSpec[][], options: BuildTfsTokenOptions = {}): string {+ const isOneWay = options.isOneWay ?? true;+ if (segments.length === 0) throw new Error("segments must be non-empty");+ for (let i = 0; i < segments.length; i++) {+ const seg = segments[i];+ if (!seg || seg.length === 0) throw new Error(`segment ${i} has no legs`);+ }++ let segmentProtos: Uint8Array = new Uint8Array(0);+ for (const seg of segments) {+ let legsProto: Uint8Array = new Uint8Array(0);+ for (const leg of seg) {+ const legProto = concatBytes(+ lengthDelim(1, utf8.encode(leg.origin)),+ lengthDelim(2, utf8.encode(leg.depDate)),+ lengthDelim(3, utf8.encode(leg.dest)),+ lengthDelim(5, utf8.encode(leg.airline)),+ lengthDelim(6, utf8.encode(leg.flightNumber)),+ );+ legsProto = concatBytes(legsProto, lengthDelim(4, legProto));+ }++ const first = seg[0] as LegSpec;+ const last = seg[seg.length - 1] as LegSpec;+ const segProto = concatBytes(+ lengthDelim(2, utf8.encode(first.depDate)),+ legsProto,+ lengthDelim(13, concatBytes(varintField(1, 1), lengthDelim(2, utf8.encode(first.origin)))),+ lengthDelim(14, concatBytes(varintField(1, 1), lengthDelim(2, utf8.encode(last.dest)))),+ );+ segmentProtos = concatBytes(segmentProtos, lengthDelim(3, segProto));+ }++ const MAX_U64 = (1n << 64n) - 1n;+ const f19 = isOneWay ? 2 : 1;++ const payload = concatBytes(+ varintField(1, 28),+ varintField(2, 2),+ segmentProtos,+ varintField(8, 1),+ varintField(9, 1),+ varintField(14, 1),+ lengthDelim(16, concatBytes(tag(1, 0), varintBig(MAX_U64))),+ varintField(19, f19),+ );+ return toUrlsafeB64(payload);+}diff --git a/fli-js/src/search/urls.ts b/fli-js/src/search/urls.tsindex a4acacd..98a0085 100644--- a/fli-js/src/search/urls.ts+++ b/fli-js/src/search/urls.ts@@ -1,29 +1,9 @@/*** URL helpers for the FlightsFrontendService RPCs.- * 1:1 port of fli/search/_urls.py.- */--/**- * Append optional `curr`/`hl`/`gl` parameters to a URL.*- * - `currency` is uppercased ("usd" → "USD") because Google rejects lowercase- * codes silently.- * - `language` is passed through verbatim (BCP-47).- * - `country` is uppercased (ISO 3166-1 alpha-2).- *- * All values are percent-encoded; returns `url` unchanged when all three are null.+ * The implementation lives in `core/links.ts` so the same helper can build the+ * public-facing Google Flights deep links. Re-exported here to keep+ * `search/urls.ts` stable for existing importers.*/-export function withLocaleParams(- url: string,- currency: string | null | undefined,- language: string | null | undefined,- country: string | null | undefined,-): string {- const params: string[] = [];- if (currency) params.push(`curr=${encodeURIComponent(currency.toUpperCase())}`);- if (language) params.push(`hl=${encodeURIComponent(language)}`);- if (country) params.push(`gl=${encodeURIComponent(country.toUpperCase())}`);- if (params.length === 0) return url;- const sep = url.includes("?") ? "&" : "?";- return `${url}${sep}${params.join("&")}`;-}++export { withLocaleParams } from "../core/links.ts";diff --git a/fli-js/tests/core/links.test.ts b/fli-js/tests/core/links.test.tsnew file mode 100644index 0000000..fc782ee--- /dev/null+++ b/fli-js/tests/core/links.test.ts@@ -0,0 +1,60 @@+/**+ * Tests for the shared Google Flights deep-link helpers.+ */++import { describe, expect, test } from "bun:test";+import { googleFlightsUrl, withLocaleParams } from "../../src/core/links.ts";++describe("withLocaleParams", () => {+ const BASE = "https://www.google.com/travel/flights";++ test("no-op when all null", () => {+ expect(withLocaleParams(BASE, null, null, null)).toBe(BASE);+ });++ test("uppercases currency", () => {+ expect(withLocaleParams(BASE, "eur", null, null)).toBe(`${BASE}?curr=EUR`);+ });++ test("passes language verbatim, uppercases country", () => {+ expect(withLocaleParams(BASE, null, "en-GB", "gb")).toBe(`${BASE}?hl=en-GB&gl=GB`);+ });++ test("uses & when url already has a query", () => {+ expect(withLocaleParams(`${BASE}?q=x`, "USD", null, null)).toBe(`${BASE}?q=x&curr=USD`);+ });+});++describe("googleFlightsUrl", () => {+ test("one-way contains route and date", () => {+ const url = googleFlightsUrl("JFK", "LHR", "2026-07-15");+ expect(url.startsWith("https://www.google.com/travel/flights?q=")).toBe(true);+ expect(url).toContain("JFK");+ expect(url).toContain("LHR");+ expect(url).toContain("2026-07-15");+ });++ test("encodes the natural-language query", () => {+ const url = googleFlightsUrl("JFK", "LHR", "2026-07-15");+ expect(url).toBe(+ "https://www.google.com/travel/flights?q=Flights%20from%20JFK%20to%20LHR%20on%202026-07-15",+ );+ });++ test("round-trip appends the return date", () => {+ const url = googleFlightsUrl("JFK", "LHR", "2026-07-15", "2026-07-22");+ expect(url).toContain("2026-07-22");+ expect(decodeURIComponent(url)).toContain("through 2026-07-22");+ });++ test("locale params appended", () => {+ const url = googleFlightsUrl("JFK", "LHR", "2026-07-15", null, {+ currency: "EUR",+ language: "en-GB",+ country: "GB",+ });+ expect(url).toContain("curr=EUR");+ expect(url).toContain("hl=en-GB");+ expect(url).toContain("gl=GB");+ });+});diff --git a/fli-js/tests/search/flights_booking_url.test.ts b/fli-js/tests/search/flights_booking_url.test.tsnew file mode 100644index 0000000..76b3e59--- /dev/null+++ b/fli-js/tests/search/flights_booking_url.test.ts@@ -0,0 +1,198 @@+/**+ * Tests for SearchFlights.buildFlightBookingUrl.+ *+ * All tests are purely in-process: no network calls, no live API. The tfs+ * itinerary token is fully deterministic from the flight data.+ */++import { describe, expect, test } from "bun:test";+import { Buffer } from "node:buffer";+import { Airline } from "../../src/models/airline.ts";+import { Airport } from "../../src/models/airport.ts";+import type { FlightLeg, FlightResult } from "../../src/models/google-flights/base.ts";+import { SearchFlights } from "../../src/search/flights.ts";++/** Build a leg with a LOCAL departure datetime (matches the decoder). */+function makeLeg(+ airline: Airline,+ flightNumber: string,+ dep: Airport,+ arr: Airport,+ depDate: string,+): FlightLeg {+ const [y, m, d] = depDate.split("-").map((p) => Number.parseInt(p, 10)) as [+ number,+ number,+ number,+ ];+ const dt = new Date(y, m - 1, d, 8, 0);+ const arrDt = new Date(y, m - 1, d, 10, 0);+ return {+ airline,+ flight_number: flightNumber,+ departure_airport: dep,+ arrival_airport: arr,+ departure_datetime: dt,+ arrival_datetime: arrDt,+ duration: 120,+ };+}++function oneWay(airline: Airline = Airline.AA, flightNumber = "1"): FlightResult {+ return {+ legs: [makeLeg(airline, flightNumber, Airport.SFO, Airport.PHX, "2026-09-01")],+ price: 100,+ currency: "USD",+ duration: 120,+ stops: 0,+ };+}++function roundTrip(): [FlightResult, FlightResult] {+ const outbound: FlightResult = {+ legs: [makeLeg(Airline.AA, "100", Airport.JFK, Airport.LAX, "2026-09-01")],+ price: 200,+ currency: "USD",+ duration: 180,+ stops: 0,+ };+ const inbound: FlightResult = {+ legs: [makeLeg(Airline.AA, "200", Airport.LAX, Airport.JFK, "2026-09-08")],+ price: null,+ currency: "USD",+ duration: 180,+ stops: 0,+ };+ return [outbound, inbound];+}++function connection(): FlightResult {+ return {+ legs: [+ makeLeg(Airline.UA, "101", Airport.SFO, Airport.ORD, "2026-09-01"),+ makeLeg(Airline.UA, "202", Airport.ORD, Airport.JFK, "2026-09-01"),+ ],+ price: 150,+ currency: "USD",+ duration: 360,+ stops: 1,+ };+}++function tfsBytes(url: string): Uint8Array {+ const tfs = new URL(url).searchParams.get("tfs");+ if (!tfs) throw new Error("no tfs param");+ const pad = (4 - (tfs.length % 4)) % 4;+ const standard = (tfs + "=".repeat(pad)).replace(/-/g, "+").replace(/_/g, "/");+ return new Uint8Array(Buffer.from(standard, "base64"));+}++describe("buildFlightBookingUrl", () => {+ const search = new SearchFlights();++ test("one-way has tfs", () => {+ const url = search.buildFlightBookingUrl(oneWay());+ expect(url.startsWith("https://www.google.com/travel/flights/booking?tfs=")).toBe(true);+ });++ test("round-trip has tfs", () => {+ expect(search.buildFlightBookingUrl(roundTrip()).includes("tfs=")).toBe(true);+ });++ test("tfs is urlsafe with no padding", () => {+ const tfs = new URL(search.buildFlightBookingUrl(oneWay())).searchParams.get("tfs") ?? "";+ expect(tfs.includes("=")).toBe(false);+ expect(tfs.includes("+")).toBe(false);+ expect(tfs.includes("/")).toBe(false);+ });++ test("no tfu param emitted", () => {+ expect(search.buildFlightBookingUrl(oneWay()).includes("tfu")).toBe(false);+ });++ test("deterministic — same itinerary, same URL", () => {+ expect(search.buildFlightBookingUrl(oneWay())).toBe(search.buildFlightBookingUrl(oneWay()));+ });++ test("locale params appended", () => {+ const url = search.buildFlightBookingUrl(oneWay(), {+ currency: "EUR",+ language: "en-GB",+ country: "GB",+ });+ expect(url).toContain("curr=EUR");+ expect(url).toContain("hl=en-GB");+ expect(url).toContain("gl=GB");+ });++ test("no locale params when not provided", () => {+ const url = search.buildFlightBookingUrl(oneWay());+ expect(url).not.toContain("curr=");+ expect(url).not.toContain("hl=");+ expect(url).not.toContain("gl=");+ });++ test("connection flight encodes each leg in tfs", () => {+ const raw = tfsBytes(search.buildFlightBookingUrl(connection()));+ const text = Buffer.from(raw).toString("latin1");+ expect(text.includes("101")).toBe(true);+ expect(text.includes("202")).toBe(true);+ expect(text.includes("ORD")).toBe(true);+ });++ test("round-trip encodes two segments in tfs", () => {+ const raw = tfsBytes(search.buildFlightBookingUrl(roundTrip()));+ let count = 0;+ for (const b of raw) if (b === 0x1a) count++;+ expect(count).toBeGreaterThanOrEqual(2);+ });++ test("multi-city (3 segments) encodes f19=2 (one-way), not round-trip", () => {+ const multiCity: FlightResult[] = [+ {+ legs: [makeLeg(Airline.AA, "1", Airport.JFK, Airport.LAX, "2026-09-01")],+ price: 100,+ currency: "USD",+ duration: 120,+ stops: 0,+ },+ {+ legs: [makeLeg(Airline.AA, "2", Airport.LAX, Airport.ORD, "2026-09-05")],+ price: 100,+ currency: "USD",+ duration: 120,+ stops: 0,+ },+ {+ legs: [makeLeg(Airline.AA, "3", Airport.ORD, Airport.JFK, "2026-09-10")],+ price: 100,+ currency: "USD",+ duration: 120,+ stops: 0,+ },+ ];+ const raw = tfsBytes(search.buildFlightBookingUrl(multiCity));+ // f19 tag 0x98 0x01, value 2 (one-way/multi-city) — must not be 1 (round-trip).+ expect(Array.from(raw.slice(-3))).toEqual([0x98, 0x01, 0x02]);+ });++ test("digit-prefixed airline code strips the underscore", () => {+ const flight = oneWay(Airline._3F, "101");+ const text = Buffer.from(tfsBytes(search.buildFlightBookingUrl(flight))).toString("latin1");+ expect(text.includes("3F")).toBe(true);+ expect(text.includes("_3F")).toBe(false);+ });++ test("never throws on malformed data — falls back to a Google Flights URL", () => {+ const bad = {+ legs: [{ departure_datetime: undefined }],+ price: null,+ } as unknown as FlightResult;+ const url = search.buildFlightBookingUrl(bad);+ expect(url).toContain("google.com");+ });++ test("returns a string", () => {+ expect(typeof search.buildFlightBookingUrl(oneWay())).toBe("string");+ });+});diff --git a/fli-js/tests/search/proto.test.ts b/fli-js/tests/search/proto.test.tsindex 7864fc4..43c62eb 100644--- a/fli-js/tests/search/proto.test.ts+++ b/fli-js/tests/search/proto.test.ts@@ -10,9 +10,11 @@ import { Buffer } from "node:buffer";import {_readVarint,buildBookingToken,+ buildTfsToken,decodeBookingToken,extractBookingTokenFromTfu,extractSessionIdFromTfu,+ type LegSpec,} from "../../src/search/proto.ts";// Captured live 2026-05-14 (JFK → LAX outbound AA171, return AA28, RT $346.80).@@ -254,3 +256,103 @@ describe("extractBookingTokenFromTfu", () => {).toThrow();});});++// Captured live 2026-05-28 — byte-perfect golden references for the tfs token.+// Round-trip JFK→LAX (AA171 out, AA28 return).+const LIVE_TFS_RT =+ "CBwQAho_EgoyMDI2LTA3LTE1Ih8KA0pGSxIKMjAyNi0wNy0xNRoDTEFYKgJBQTIDMTcxagcIAR" ++ "IDSkZLcgcIARIDTEFYGj4SCjIwMjYtMDctMTkiHgoDTEFYEgoyMDI2LTA3LTE5GgNKRksqAkFBMgIy" ++ "OGoHCAESA0xBWHIHCAESA0pGS0ABSAFwAYIBCwj___________8BmAEB";+// One-way nonstop LAX→ORD (UA729).+const LIVE_TFS_OW =+ "CBwQAho_EgoyMDI2LTA4LTE1Ih8KA0xBWBIKMjAyNi0wOC0xNRoDT1JEKgJVQTIDNzI5" ++ "agcIARIDTEFYcgcIARIDT1JEQAFIAXABggELCP___________wGYAQI";+// One-way 2-stop BOS→DEN(WN739)→SJC(WN389)→SEA(WN389).+const LIVE_TFS_3LEG =+ "CBwQAhqBARIKMjAyNi0wOC0xNSIfCgNCT1MSCjIwMjYtMDgtMTUaA0RFTioCV04yAzczOSIfCgNERU4S" ++ "CjIwMjYtMDgtMTUaA1NKQyoCV04yAzM4OSIfCgNTSkMSCjIwMjYtMDgtMTUaA1NFQSoCV04yAzM4OWoH" ++ "CAESA0JPU3IHCAESA1NFQUABSAFwAYIBCwj___________8BmAEC";++function tfsBytes(tfs: string): Uint8Array {+ return decodeUrlsafe(tfs);+}++describe("buildTfsToken", () => {+ test("round-trip reproduces captured tfs byte-for-byte", () => {+ const segments: LegSpec[][] = [+ [{ origin: "JFK", depDate: "2026-07-15", dest: "LAX", airline: "AA", flightNumber: "171" }],+ [{ origin: "LAX", depDate: "2026-07-19", dest: "JFK", airline: "AA", flightNumber: "28" }],+ ];+ const built = buildTfsToken(segments, { isOneWay: false });+ expect([...tfsBytes(built)]).toEqual([...tfsBytes(LIVE_TFS_RT)]);+ });++ test("one-way nonstop reproduces captured tfs byte-for-byte", () => {+ const segments: LegSpec[][] = [+ [{ origin: "LAX", depDate: "2026-08-15", dest: "ORD", airline: "UA", flightNumber: "729" }],+ ];+ const built = buildTfsToken(segments, { isOneWay: true });+ expect([...tfsBytes(built)]).toEqual([...tfsBytes(LIVE_TFS_OW)]);+ });++ test("multi-leg connection reproduces captured tfs byte-for-byte", () => {+ const segments: LegSpec[][] = [+ [+ { origin: "BOS", depDate: "2026-08-15", dest: "DEN", airline: "WN", flightNumber: "739" },+ { origin: "DEN", depDate: "2026-08-15", dest: "SJC", airline: "WN", flightNumber: "389" },+ { origin: "SJC", depDate: "2026-08-15", dest: "SEA", airline: "WN", flightNumber: "389" },+ ],+ ];+ const built = buildTfsToken(segments, { isOneWay: true });+ expect([...tfsBytes(built)]).toEqual([...tfsBytes(LIVE_TFS_3LEG)]);+ });++ test("f19 is 2 for one-way", () => {+ const built = buildTfsToken(+ [[{ origin: "SFO", depDate: "2026-09-01", dest: "PHX", airline: "AA", flightNumber: "100" }]],+ { isOneWay: true },+ );+ const raw = tfsBytes(built);+ expect(Array.from(raw.slice(-3))).toEqual([0x98, 0x01, 0x02]);+ });++ test("f19 is 1 for round-trip", () => {+ const built = buildTfsToken(+ [+ [{ origin: "JFK", depDate: "2026-09-01", dest: "LAX", airline: "AA", flightNumber: "1" }],+ [{ origin: "LAX", depDate: "2026-09-08", dest: "JFK", airline: "AA", flightNumber: "2" }],+ ],+ { isOneWay: false },+ );+ const raw = tfsBytes(built);+ expect(Array.from(raw.slice(-3))).toEqual([0x98, 0x01, 0x01]);+ });++ test("urlsafe, no padding", () => {+ const built = buildTfsToken([+ [{ origin: "SFO", depDate: "2026-09-01", dest: "PHX", airline: "AA", flightNumber: "100" }],+ ]);+ expect(built.includes("=")).toBe(false);+ expect(built.includes("+")).toBe(false);+ expect(built.includes("/")).toBe(false);+ });++ test("three legs encode to 159 bytes", () => {+ const segments: LegSpec[][] = [+ [+ { origin: "BOS", depDate: "2026-08-15", dest: "DEN", airline: "WN", flightNumber: "739" },+ { origin: "DEN", depDate: "2026-08-15", dest: "SJC", airline: "WN", flightNumber: "389" },+ { origin: "SJC", depDate: "2026-08-15", dest: "SEA", airline: "WN", flightNumber: "389" },+ ],+ ];+ expect(tfsBytes(buildTfsToken(segments, { isOneWay: true })).length).toBe(159);+ });++ test("empty segments throws", () => {+ expect(() => buildTfsToken([])).toThrow("non-empty");+ });++ test("empty leg list throws", () => {+ expect(() => buildTfsToken([[]])).toThrow("no legs");+ });+});