Google Flights MCP, CLI and Python Library
docs: add TypeScript docs/examples and reorganize by language (#186)
Punit Arani4942911bfc93
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlindex 4ac8531..d60ebd4 100644--- a/.github/workflows/publish.yml+++ b/.github/workflows/publish.yml@@ -2,14 +2,14 @@ name: Upload Python Package# Triggers:# - release: published -> auto-publish when a GH Release is created manually-# (e.g. via the manual fallback in docs/guides/release.md)+# (e.g. the manual release fallback)# - workflow_dispatch -> manual publish, used for TestPyPI smoke tests or# recovery (e.g. shipping a tag that release.yml failed# to publish). Pick the tag/branch in the dispatch UI.## This workflow is NOT called from release.yml -- release.yml inlines its own-# publish steps. See docs/guides/release.md for the rationale (PyPI Trusted-# Publishing attestations are incompatible with reusable workflow chains).+# publish steps because PyPI Trusted Publishing attestations are incompatible+# with reusable workflow chains. See the Releasing section in CLAUDE.md.on:release:diff --git a/AGENTS.md b/AGENTS.mdindex 0b702cb..b0b4f26 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -27,8 +27,9 @@ All standard commands are in the `Makefile` and `CLAUDE.md`. Key ones:Releases are manual: GitHub Actions → **Release** → Run workflow on `main`,choose `bump=patch|minor|major|explicit`. Run with `dry_run=true` first to-preview. Bump logic is in `scripts/bump_version.py` (testable). Full guide:-`docs/guides/release.md`.+preview. Bump logic is in `scripts/bump_version.py` (testable). See the+Releasing section in `CLAUDE.md` and the `.github/workflows/release*.yml`+workflows for the full process.### MCP server notesdiff --git a/CLAUDE.md b/CLAUDE.mdindex 8f7ac93..07db516 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -163,7 +163,8 @@ notes. The version-bump logic lives in `scripts/bump_version.py` (coveredby `tests/scripts/test_bump_version.py`); the same script handles both`pyproject.toml` (via `--pyproject`) and `package.json` (via`--package-json`), and the tag prefix is controlled by `--tag-prefix`.-Full process: `docs/guides/release.md` (PyPI), `docs/guides/release-npm.md` (npm).+The release workflows (`.github/workflows/release.yml` and+`release-npm.yml`) are the source of truth for the exact steps.## Code Style and Standardsdiff --git a/README.md b/README.mdindex 989cb95..afbf1a5 100644--- a/README.md+++ b/README.md@@ -368,17 +368,17 @@ for flight in flights:### Running Examples-We provide 11 comprehensive examples in the `examples/` directory that demonstrate various use cases:+Runnable examples live in [`examples/python/`](examples/python):```bash# Run examples with uv (recommended)-uv run python examples/basic_one_way_search.py-uv run python examples/round_trip_search.py-uv run python examples/date_range_search.py+uv run python examples/python/basic_one_way_search.py+uv run python examples/python/round_trip_search.py+uv run python examples/python/date_range_search.py# Or install dependencies first, then run directlypip install pydantic curl_cffi httpx-python examples/basic_one_way_search.py+python examples/python/basic_one_way_search.py```**Available Examples:**@@ -386,6 +386,8 @@ python examples/basic_one_way_search.py* `basic_one_way_search.py` - Simple one-way flight search* `round_trip_search.py` - Round-trip flight booking* `date_range_search.py` - Find cheapest dates+* `multi_city_search.py` - Multi-city itinerary across several legs+* `advanced_filters_search.py` - Alliances, airline exclusions, layovers, locale* `complex_flight_search.py` - Advanced filtering and multi-passenger* `time_restrictions_search.py` - Time-based filtering* `date_search_with_preferences.py` - Weekend filtering@@ -395,32 +397,65 @@ python examples/basic_one_way_search.py* `complex_round_trip_validation.py` - Advanced round-trip with validation* `advanced_date_search_validation.py` - Complex date search with filtering-> 💡 **Tip**: Examples include automatic dependency checking and will show helpful installation instructions if-> dependencies are missing.-## Examples-For comprehensive examples demonstrating all features, see the [`examples/`](examples/) directory:+Examples are organized by language, with parallel scripts so you can compare the+two APIs:++* **Python** — [`examples/python/`](examples/python)+* **TypeScript** — [`examples/typescript/`](examples/typescript)```bash-# Quick test - run a simple example-uv run python examples/basic_one_way_search.py+# Python+uv run python examples/python/complex_flight_search.py-# Run all examples to explore different features-uv run python examples/round_trip_search.py-uv run python examples/complex_flight_search.py-uv run python examples/price_tracking.py+# TypeScript (from examples/typescript, after `bun install`)+bun run multi_city_search.ts```**Example Categories:*** **Basic Usage**: One-way, round-trip, date searches-* **Advanced Filtering**: Time restrictions, airlines, seat classes+* **Advanced Filtering**: Time restrictions, airlines, alliances, seat classes, locale* **Data Analysis**: Price tracking, result processing with pandas* **Error Handling**: Retry logic, robust error management-* **Complex Scenarios**: Multi-passenger, validation, business rules+* **Complex Scenarios**: Multi-city, multi-passenger, validation, business rules++Each example is self-contained — change the airports, dates, and filters at the top of the script to fit your search.++## TypeScript / JavaScript++Fli is also available as a 1:1 TypeScript port, published to npm as+[`fli-js`](https://www.npmjs.com/package/fli-js). Same models, same filter encoding,+same direct-API approach.++```bash+bun add fli-js # or: npm install fli-js+```++```ts+import { Airport, FlightSearchFilters, FlightSegment, SearchFlights, SeatType } from "fli-js";++const inDays = (n: number) => new Date(Date.now() + n * 86_400_000).toISOString().slice(0, 10);++const filters = new FlightSearchFilters({+ passenger_info: { adults: 1, children: 0, infants_in_seat: 0, infants_on_lap: 0 },+ flight_segments: [+ new FlightSegment({+ departure_airport: [[[Airport.JFK, 0]]],+ arrival_airport: [[[Airport.LAX, 0]]],+ travel_date: inDays(30),+ }),+ ],+ seat_type: SeatType.ECONOMY,+});++const results = await new SearchFlights().search(filters, { currency: "USD" });+```-Each example is self-contained and includes automatic dependency checking with helpful installation instructions.+The TypeScript source lives in [`fli-js/`](fli-js); see the+[TypeScript Quick Start](https://punitarani.github.io/fli/typescript/quickstart/)+for the full guide.## Developmentdiff --git a/docs/guides/release-npm.md b/docs/guides/release-npm.mddeleted file mode 100644index 1c0ed1e..0000000--- a/docs/guides/release-npm.md+++ /dev/null@@ -1,151 +0,0 @@-# Releasing fli-js to npm--Releases of the TypeScript / JavaScript package `fli-js` on-[npmjs.com](https://www.npmjs.com/package/fli-js) are driven by a manual-GitHub Actions workflow. There is no auto-publish on push to `main`;-cutting a release is always an explicit, one-click action — same shape-as the Python release flow, but on its own schedule.--## Overview--The npm release pipeline is two workflows, parallel to the PyPI pair:--| Workflow | File | Trigger |-| --- | --- | --- |-| **Release npm** | `.github/workflows/release-npm.yml` | `workflow_dispatch` only |-| **Upload npm Package** | `.github/workflows/publish-npm.yml` | `release: published` (fli-js-v* tags), `workflow_dispatch`, `workflow_call` |--`release-npm.yml` bumps the version in `fli-js/package.json`, refreshes-`fli-js/bun.lock`, commits to `main`, creates an annotated tag-`fli-js-vX.Y.Z` and a GitHub Release, then calls `publish-npm.yml` to-build the package and upload it to npm with provenance attestation.--`publish-npm.yml` can also be triggered independently — by publishing a-GitHub Release with a `fli-js-v*` tag, or via `workflow_dispatch`-(defaults to a dry-run pack-only build).--The Python (`flights`) and JavaScript (`fli`) packages are versioned-**independently**. Python releases use the tag prefix `v` (e.g.-`v0.9.0`); JS releases use `fli-js-v` (e.g. `fli-js-v0.2.0`). The two-publish workflows filter on the tag prefix so a Python release does not-trigger an npm publish (and vice versa).--## Cutting a release--1. Go to **Actions → Release npm → Run workflow** on `main`.-2. Choose the bump:- * `patch` (default) — bugfixes, small changes- * `minor` — new features, additive changes- * `major` — breaking changes- * `explicit` — set an exact version (also fill in the `version` input)-3. Optional: set `dry_run: true` to preview the next version and release- notes without committing or publishing. The preview appears in the run- summary.-4. Run again with `dry_run: false` to actually release.--The workflow will:--1. Compute the next version from `fli-js/package.json`.-2. Verify the tag `fli-js-vX.Y.Z` doesn't already exist- (locally and on the remote).-3. Generate release notes from the commits in the range- `<previous fli-js tag>..HEAD`, filtered to paths- `fli-js/` and `data/`.-4. Update `fli-js/package.json` and `fli-js/bun.lock`.-5. Commit `chore(release): fli-js-vX.Y.Z` to `main`, tag- `fli-js-vX.Y.Z`, push both.-6. Create a GitHub Release with the generated notes.-7. Trigger `publish-npm.yml`:- * Run the existing `fli-js.yml` test pipeline- (format / lint / typecheck / tests).- * Re-install with `bun install --frozen-lockfile`.- * Verify generated enums are in sync with `data/`.- * Build via `bun run build` (`tsc -p tsconfig.build.json`).- * Sanity-check the build output and `npm pack --dry-run` contents.- * Pack the tarball, upload it as an artifact.- * Publish to npm with `npm publish --provenance --access public`.--## Previewing locally--```bash-# What would a minor bump produce?-python scripts/bump_version.py \- --package-json fli-js/package.json \- --bump minor \- --tag-prefix fli-js-v--# Show the commits that would land in the next release-git log --pretty=format:'- %s (%h)' \- "$(git tag --list 'fli-js-v*' --sort=-v:refname | head -n1)..HEAD" \- -- fli-js data--# Validate the build end-to-end-cd fli-js-bun install --frozen-lockfile-bun run build-npm pack --dry-run-```--`bump_version.py` only prints by default — pass `--write` to actually-modify `fli-js/package.json`.--## Repository prerequisites--These need to be in place once on the GitHub side:--* **`NPM_TOKEN` secret** — an npm automation token bound to a user with- publish rights on the `fli` package. Create one at- <https://www.npmjs.com/settings/~/tokens> (type *Automation*) and add- it under **Settings → Secrets and variables → Actions → New repository- secret**.-* **`npm` GitHub environment** — `publish-npm.yml` references- `environment: npm`. Create it under **Settings → Environments** if you- want manual approvals or environment-scoped secrets. Otherwise the- default environment-less behaviour applies.-* **Provenance** — `publish-npm.yml` requests `id-token: write` and runs- `npm publish --provenance`. No extra config required; the action runs- on a public repo with publicly-readable workflow logs, which is what- npm provenance attestation requires.-* **Branch protection on `main`** must permit pushes from- `github-actions[bot]`. If protection blocks the bot, the release- workflow's push will fail; switch the checkout step's `token:` to a- PAT secret instead.--## Troubleshooting--* **`Tag fli-js-vX.Y.Z already exists`** — someone tagged the same- version earlier (locally or on origin). Bump again or use- `bump=explicit` with a different version.-* **Push to `main` rejected** — branch protection is blocking the bot.- Either add `github-actions[bot]` to the bypass list, or wire a PAT- into the checkout step's `token:`.-* **`npm publish` fails with `EOTP` or 401** — the `NPM_TOKEN` is- expired, has the wrong scope, or doesn't have publish rights on the- package. Re-issue an Automation token from npm and update the secret.-* **`npm publish` fails with provenance error** — the workflow must run- on a public repo and the runner must be an ephemeral GitHub-hosted- runner. Provenance is unavailable on self-hosted runners.-* **`Generated enums are out of date`** — `bun run generate:enums`- produced a diff. Regenerate locally, commit, and re-run the release.--## Manual fallback--If the workflow is broken and a release is urgent, you can still:--1. Bump the version in `fli-js/package.json` and `fli-js/bun.lock` on a- branch, merge to `main`.-2. Tag `fli-js-vX.Y.Z` and push the tag.-3. Create a GitHub Release in the UI from that tag — `publish-npm.yml`'s- `release: published` trigger will pick it up and publish.--If even that fails, publishing locally as a last resort:--```bash-cd fli-js-bun install --frozen-lockfile-bun run build-npm publish --provenance --access public-```--(requires `npm login` first, and skips the GitHub Release / provenance-attestation since the build didn't happen in CI.)diff --git a/docs/guides/release.md b/docs/guides/release.mddeleted file mode 100644index 8927ff5..0000000--- a/docs/guides/release.md+++ /dev/null@@ -1,142 +0,0 @@-# Releasing (PyPI)--Releases of the Python package `flights` are driven by a manual GitHub-Actions workflow. There is no auto-publish on push to `main`; cutting a-release is always an explicit, one-click action.--For the TypeScript / JavaScript package (`fli-js` on npm), see-[`release-npm.md`](release-npm.md) — the same shape, different manifest,-different tag prefix (`fli-js-vX.Y.Z`).--## Overview--The release pipeline is two independent workflows:--| Workflow | File | Trigger |-| --- | --- | --- |-| **Release** | `.github/workflows/release.yml` | `workflow_dispatch` only |-| **Upload Python Package** | `.github/workflows/publish.yml` | `release: published`, `workflow_dispatch` |--`release.yml` is the end-to-end release pipeline: it bumps the version in-`pyproject.toml`, refreshes `uv.lock`, commits to `main`, creates an annotated-tag and GitHub Release, runs the full test matrix against the new tag, and-builds + uploads to PyPI via Trusted Publishing — all inline, no chained-workflow.--`publish.yml` is a standalone publish workflow used for:-- **Manual recovery** — if `release.yml`'s publish step ever fails, dispatch- `publish.yml` on the failed tag (`environment: pypi`) to ship it.-- **Manual GitHub Release** — if you create a release in the UI from an- existing tag, the `release: published` trigger picks it up and publishes.-- **TestPyPI smoke tests** — `workflow_dispatch` with `environment: testpypi`.--> **Why two workflows instead of one reusable?** PyPI's Trusted Publishing-> attestations are incompatible with reusable workflow chains-> ([pypa/gh-action-pypi-publish#166](https://github.com/pypa/gh-action-pypi-publish/issues/166)).-> When `release.yml` calls `publish.yml` via `workflow_call`, the OIDC token's-> `job_workflow_ref` points at `publish.yml` while the Sigstore cert's-> `Build Config URI` points at `release.yml`; PyPI ties both to the same-> publisher and rejects the attestation. Inlining the publish step into-> `release.yml` sidesteps this entirely.--## Cutting a release--1. Go to **Actions → Release → Run workflow** on `main`.-2. Choose the bump:- * `patch` (default) — bugfixes, small changes- * `minor` — new features, additive changes- * `major` — breaking changes- * `explicit` — set an exact version (also fill in the `version` input)-3. Optional: set `dry_run: true` to preview the next version and release- notes without committing or publishing. The preview appears in the run- summary.-4. Run again with `dry_run: false` to actually release.--The workflow will:--1. Compute the next version from `pyproject.toml`.-2. Verify the tag doesn't already exist (locally and on the remote).-3. Generate release notes from the commits in the range- `<previous tag>..HEAD`. On the very first release with no prior tag, it- walks back to the last manual `Bump version` commit.-4. Update `pyproject.toml` and `uv.lock`.-5. Commit `chore(release): vX.Y.Z` to `main`, tag `vX.Y.Z`, push both.-6. Create a GitHub Release with the generated notes.-7. Trigger `publish.yml` (run tests, build with `uv build`, `twine check`,- upload to PyPI via OIDC Trusted Publishing).--## Previewing locally--Use the same script the workflow uses:--```bash-# What would a minor bump produce?-python scripts/bump_version.py --bump minor--# Show the commits that would land in the next release-git log --pretty=format:'- %s (%h)' "$(git describe --tags --abbrev=0)..HEAD"-```--`bump_version.py` only prints by default — pass `--write` to actually-modify `pyproject.toml`.--## Repository prerequisites--These need to be in place once on the GitHub side:--* **PyPI Trusted Publishers** for the `flights` project, both bound to this- repo and the `pypi` environment:- * `release.yml` — used by the automated end-to-end release flow- * `publish.yml` — used by manual recovery, `release: published`, and- TestPyPI dispatch-- Configure both at- [pypi.org/manage/project/flights/settings/publishing/](https://pypi.org/manage/project/flights/settings/publishing/).- Set Environment name to `pypi` on both.-* **Branch protection on `main`** must permit pushes from `github-actions[bot]`.- If protection blocks the bot, the release workflow's push will fail; switch- the checkout step's `token:` to a PAT secret instead.-* **Workflow permissions**: `release.yml` requires `contents: write` (already- declared at the workflow level) and `id-token: write` on the `publish`- job for OIDC.--## Troubleshooting--* **`Tag vX.Y.Z already exists`** — someone tagged the same version earlier- (locally or on origin). Bump again or use `bump=explicit` with a different- version.-* **Push to `main` rejected** — branch protection is blocking the bot. Either- add `github-actions[bot]` to the bypass list, or wire a PAT into the- checkout step's `token:`.-* **PyPI publish step fails with OIDC error** — the Trusted Publisher- config on PyPI doesn't match this repo/workflow/environment. Re-check the- project's *Publishing* settings on PyPI.-* **Release notes look wrong on first run** — the workflow walks back to the- last commit whose subject starts with `Bump version`. If you've changed- that convention, edit `release.yml`'s "Determine commit range" step.-* **PyPI returns 400 "Invalid attestations supplied"** with cert URI mismatch- — the publish job is running via a `workflow_call` chain (the original- bug). Make sure the publish job is defined inline in `release.yml`, not- invoked via `uses: ./.github/workflows/publish.yml`. As a one-time recovery- for the failed tag, dispatch `publish.yml` standalone on that tag.--## Manual fallback--If `release.yml`'s publish step fails after the tag and GitHub Release have-already been created (e.g. transient PyPI outage), recover with:--1. Actions → **Upload Python Package** → Run workflow-2. **Branch dropdown**: switch to the failed tag (e.g. `vX.Y.Z`)-3. `environment`: `pypi`-4. Run--This dispatches `publish.yml` standalone and uploads the same tag's artifact.--If the entire `release.yml` workflow is broken and a release is urgent, you-can also:--1. Bump the version in `pyproject.toml` and `uv.lock` on a branch, merge to- `main`.-2. Tag `vX.Y.Z` and push the tag.-3. Create a GitHub Release in the UI from that tag — `publish.yml`'s- `release: published` trigger will pick it up and publish.diff --git a/docs/index.md b/docs/index.mdindex 60b2e34..0e47228 100644--- a/docs/index.md+++ b/docs/index.md@@ -1,87 +1,41 @@-# Welcome to Fli Documentation+# Fli Documentation-Fli is a powerful Python library that provides direct access to Google Flights' API through reverse engineering. Unlike-other flight search libraries that rely on web scraping, Fli offers a clean, fast, and reliable way to search for-flights and analyze pricing data.+Fli provides direct, reverse-engineered access to Google Flights' API. Unlike+libraries that scrape HTML or drive a browser, Fli speaks the Flights API+directly — making it fast, reliable, and far less likely to break when the UI+changes.-## Key Features--### 🚀 Direct API Access--* No web scraping or browser automation-* Fast and reliable results-* Less prone to breaking from UI changes-* Clean, modular architecture--### 🤖 MCP Server Integration--* Model Context Protocol server for AI assistants-* Natural language flight search with Claude-* Two powerful tools: `search_flights` and `search_dates`-* Easy configuration with environment variables--### 🔍 Search Capabilities--* One-way and round-trip flight searches-* Flexible departure times-* Multi-airline support-* Various cabin classes-* Stop preferences-* Custom result sorting-* Experimental JSON CLI output for agents and tools like `jq`--### 💰 Price Analysis--* Search across date ranges-* Find cheapest dates to fly-* Price tracking and analysis-* Flexible date options--## Quick Start--### Installation--```bash-# Install using pip-pip install flights--# Or install using pipx (recommended for CLI usage)-pipx install flights-```--### MCP Server (for AI Assistants)--```bash-# Run the MCP server-fli-mcp+Fli ships in two flavors with a shared design:-# Or run over HTTP-fli-mcp-http-```--See the [MCP Guide](guides/mcp.md) for Claude Desktop configuration.+| | Package | Install | Docs |+|---|---|---|---|+| **Python** | [`flights`](https://pypi.org/project/flights/) (PyPI) | `pip install flights` | [Python Quick Start](python/quickstart.md) |+| **TypeScript** | [`fli-js`](https://www.npmjs.com/package/fli-js) (npm) | `bun add fli-js` | [TypeScript Quick Start](typescript/quickstart.md) |-### Basic Usage+The TypeScript package is a 1:1 port of the Python library — same models, same+filter encoding, same wire-format decoders.-### CLI JSON Output+## Key Features-!!! warning "Experimental"- The `--format json` CLI output is experimental. The schema is intended for agents and tools such as `jq`, but may evolve in future releases.+* **Direct API access** — no scraping, no browser automation, no HTML parsing.+* **Rich search** — one-way, round-trip, and multi-city; cabin classes; stop+ and layover limits; airline/alliance include & exclude; currency and locale.+* **Cheapest-date search** — scan a flexible date window for the best fares.+* **Built-in protection** — 10 req/s rate limiting, automatic retries with+ exponential backoff, typed errors, and input validation.+* **MCP server** (Python) — search flights from AI assistants like Claude via+ the Model Context Protocol.-```bash-fli flights JFK LHR 2026-06-01 --format json-fli dates JFK LHR --from 2026-06-01 --to 2026-06-30 --format json-```+## Python in 30 seconds```pythonfrom datetime import datetime, timedeltafrom fli.models import (- Airport, PassengerInfo, SeatType, MaxStops, SortBy,- FlightSearchFilters, FlightSegment+ Airport, FlightSearchFilters, FlightSegment,+ MaxStops, PassengerInfo, SeatType, SortBy,)from fli.search import SearchFlights-# Create search filtersfilters = FlightSearchFilters(passenger_info=PassengerInfo(adults=1),flight_segments=[@@ -96,75 +50,52 @@ filters = FlightSearchFilters(sort_by=SortBy.CHEAPEST,)-# Search flights-search = SearchFlights()-flights = search.search(filters)--# Process results-for flight in flights:- print(f"💰 Price: ${flight.price}")- print(f"⏱️ Duration: {flight.duration} minutes")- print(f"✈️ Stops: {flight.stops}")+for flight in SearchFlights().search(filters) or []:+ print(f"${flight.price} — {flight.duration} min — {flight.stops} stop(s)")```-### Running Examples+## TypeScript in 30 seconds++```ts+import {+ Airport, FlightSearchFilters, FlightSegment,+ MaxStops, SearchFlights, SeatType, SortBy,+} from "fli-js";++const filters = new FlightSearchFilters({+ passenger_info: { adults: 1, children: 0, infants_in_seat: 0, infants_on_lap: 0 },+ flight_segments: [+ new FlightSegment({+ departure_airport: [[[Airport.JFK, 0]]],+ arrival_airport: [[[Airport.LAX, 0]]],+ travel_date: "2026-12-25",+ }),+ ],+ seat_type: SeatType.ECONOMY,+ stops: MaxStops.NON_STOP,+ sort_by: SortBy.CHEAPEST,+});++for (const flight of (await new SearchFlights().search(filters, { currency: "USD" })) ?? []) {+ console.log(`$${flight.price} — ${flight.duration} min — ${flight.stops} stop(s)`);+}+```-Complete, runnable examples are available in the `examples/` directory:+## Command line (Python)```bash-# Run with uv (recommended - handles dependencies)-uv run python examples/basic_one_way_search.py+pipx install flights-# Or install dependencies first, then run-pip install pydantic curl_cffi httpx-python examples/basic_one_way_search.py+fli flights JFK LHR 2026-06-01 --class BUSINESS --stops NON_STOP+fli dates JFK LHR --from 2026-06-01 --to 2026-06-30```-**Available Examples:**--* Basic one-way and round-trip searches-* Date range analysis and cheapest date finding-* Advanced filtering with time restrictions-* Error handling and retry logic-* Data analysis with pandas integration--> 💡 All examples include automatic dependency checking and helpful error messages.--## Project Structure--The library is organized into several key modules:--* `core/`: Shared utilities- * `parsers.py`: Parameter parsing (airports, airlines, stops, etc.)- * `builders.py`: Filter building utilities--* `models/`: Data models and enums- * `google_flights`: Core data models specific to Google Flights- * `airline.py`: Airline enums and data- * `airport.py`: Airport enums and data--* `search/`: Search functionality- * `flights.py`: Flight search implementation- * `dates.py`: Date-based price search- * `client.py`: HTTP client with rate limiting--* `mcp/`: MCP server- * `server.py`: FastMCP server with `search_flights` and `search_dates` tools--* `cli/`: Command-line interface- * `commands/`: CLI commands (`flights`, `dates`)- * `utils.py`: Display and validation utilities--## Contributing--We welcome contributions! Here's how you can help:+## Where to next-1. Fork the repository-2. Create a feature branch-3. Make your changes-4. Run tests: `uv run pytest`-5. Submit a pull request+* [Python Quick Start](python/quickstart.md) · [Python Examples](python/examples.md) · [Python API Reference](python/api/models.md)+* [TypeScript Quick Start](typescript/quickstart.md) · [TypeScript Examples](typescript/examples.md)+* [MCP Server Guide](guides/mcp.md) — flight search for AI assistants## License-This project is licensed under the MIT License. See the LICENSE file for details.+Fli is released under the MIT License. See the `LICENSE` file for details.diff --git a/docs/api/models.md b/docs/python/api/models.mdsimilarity index 100%rename from docs/api/models.mdrename to docs/python/api/models.mddiff --git a/docs/api/search.md b/docs/python/api/search.mdsimilarity index 81%rename from docs/api/search.mdrename to docs/python/api/search.mdindex 9aafce6..6153467 100644--- a/docs/api/search.md+++ b/docs/python/api/search.md@@ -79,25 +79,23 @@ results = search.search(filters)### Running These Examples-You can find complete, runnable versions of these examples in the `examples/` directory:+You can find complete, runnable versions of these examples in the [`examples/python/`](https://github.com/punitarani/fli/tree/main/examples/python) directory:```bash# Run with uv (recommended)-uv run python examples/basic_one_way_search.py-uv run python examples/date_range_search.py+uv run python examples/python/basic_one_way_search.py+uv run python examples/python/date_range_search.py# Or install dependencies and run directlypip install pydantic curl_cffi httpx-python examples/basic_one_way_search.py+python examples/python/basic_one_way_search.py```For more advanced examples, see:-* `examples/complex_flight_search.py` - Advanced filtering-* `examples/result_processing.py` - Data analysis-* `examples/error_handling_with_retries.py` - Robust error handling--> 💡 All examples include automatic dependency checking and helpful error messages.+* `examples/python/complex_flight_search.py` - Advanced filtering+* `examples/python/result_processing.py` - Data analysis+* `examples/python/error_handling_with_retries.py` - Robust error handling## HTTP Clientdiff --git a/docs/examples/advanced.md b/docs/python/examples.mdsimilarity index 96%rename from docs/examples/advanced.mdrename to docs/python/examples.mdindex cc26acf..996bc90 100644--- a/docs/examples/advanced.md+++ b/docs/python/examples.md@@ -1,21 +1,21 @@# Advanced Examples-This document contains advanced code examples demonstrating complex flight search scenarios. All examples are available as runnable scripts in the `examples/` directory.+This document contains advanced code examples demonstrating complex flight search scenarios. All examples are available as runnable scripts in the [`examples/python/`](https://github.com/punitarani/fli/tree/main/examples/python) directory.## Running Examples```bash# Run with uv (recommended - handles dependencies automatically)-uv run python examples/complex_flight_search.py-uv run python examples/time_restrictions_search.py-uv run python examples/price_tracking.py+uv run python examples/python/complex_flight_search.py+uv run python examples/python/time_restrictions_search.py+uv run python examples/python/price_tracking.py# Or install dependencies first, then run directlypip install pydantic curl_cffi httpx pandas tenacity-python examples/complex_flight_search.py+python examples/python/complex_flight_search.py```-> 💡 **Tip**: All example files include automatic dependency checking and will show helpful installation instructions if dependencies are missing.+> 💡 **Tip**: Each example is self-contained — change the airports, dates, and filters at the top of the script to fit your search.## Complex Flight Searchdiff --git a/docs/guides/quickstart.md b/docs/python/quickstart.mdsimilarity index 86%rename from docs/guides/quickstart.mdrename to docs/python/quickstart.mdindex c4755dd..359b621 100644--- a/docs/guides/quickstart.md+++ b/docs/python/quickstart.md@@ -81,7 +81,7 @@ fli-mcpfli-mcp-http```-See the [MCP Guide](mcp.md) for detailed configuration.+See the [MCP Guide](../guides/mcp.md) for detailed configuration.### Python API@@ -203,17 +203,18 @@ for date_price in results:### Running Complete Examples-All the above code snippets are available as complete, runnable examples in the `examples/` directory:+All the above code snippets are available as complete, runnable examples in the+[`examples/python/`](https://github.com/punitarani/fli/tree/main/examples/python) directory:```bash# Run examples with uv (recommended)-uv run python examples/basic_one_way_search.py-uv run python examples/round_trip_search.py-uv run python examples/date_range_search.py+uv run python examples/python/basic_one_way_search.py+uv run python examples/python/round_trip_search.py+uv run python examples/python/date_range_search.py# Or install dependencies firstpip install pydantic curl_cffi httpx-python examples/basic_one_way_search.py+python examples/python/basic_one_way_search.py```**Available Example Files:**@@ -230,11 +231,13 @@ python examples/basic_one_way_search.py* `error_handling_with_retries.py` - Robust error handling example* `result_processing.py` - Data analysis with pandas-> 💡 **Tip**: Examples include automatic dependency checking and will guide you through installation if dependencies are missing.+> 💡 **Tip**: Each example is self-contained — change the airports, dates, and+> filters at the top of the script to fit your search.## Next Steps-* Check out the [API Reference](../api/models.md) for detailed documentation-* See [Advanced Examples](../examples/advanced.md) for more complex use cases-* Read the [MCP Guide](mcp.md) for AI assistant integration-* Read about [Rate Limiting and Error Handling](../api/search.md#http-client)+* Check out the [API Reference](api/models.md) for detailed documentation+* See [Advanced Examples](examples.md) for more complex use cases+* Read the [MCP Guide](../guides/mcp.md) for AI assistant integration+* Read about [Rate Limiting and Error Handling](api/search.md#http-client)+* Using TypeScript? See the [TypeScript Quick Start](../typescript/quickstart.md)diff --git a/docs/typescript/examples.md b/docs/typescript/examples.mdnew file mode 100644index 0000000..6909398--- /dev/null+++ b/docs/typescript/examples.md@@ -0,0 +1,101 @@+# TypeScript Examples++Complete, runnable TypeScript examples live in+[`examples/typescript/`](https://github.com/punitarani/fli/tree/main/examples/typescript).+Each file mirrors its Python counterpart so you can compare the two APIs.++## Running++```bash+cd examples/typescript+bun install # or: npm install++bun run basic_one_way_search.ts+# ...or use the package scripts:+bun run basic # one-way+bun run round-trip # round trip+bun run dates # cheapest dates in a range+bun run multi-city # 3-leg itinerary+bun run advanced # alliances + exclusions + locale+bun run errors # client tuning + typed error handling+```++On Node, run through a TypeScript loader: `npx tsx basic_one_way_search.ts`.++## Files++| File | What it shows |+|------|---------------|+| `basic_one_way_search.ts` | Minimal one-way search and result printing |+| `round_trip_search.ts` | Round trip; itineraries returned as `[outbound, return]` |+| `date_range_search.ts` | Cheapest dates across a flexible window |+| `multi_city_search.ts` | Three-leg multi-city itinerary |+| `advanced_filters_search.ts` | Alliances, airline exclusions, layover bounds, currency/locale |+| `error_handling_with_retries.ts` | Custom `Client` config and typed `Search*Error` handling |++## Multi-city++```ts+import {+ Airport,+ type FlightResult,+ FlightSearchFilters,+ FlightSegment,+ SearchFlights,+ TripType,+} from "fli-js";++const inDays = (n: number) => new Date(Date.now() + n * 86_400_000).toISOString().slice(0, 10);++const leg = (from: Airport, to: Airport, date: string) =>+ new FlightSegment({+ departure_airport: [[[from, 0]]],+ arrival_airport: [[[to, 0]]],+ travel_date: date,+ });++const filters = new FlightSearchFilters({+ trip_type: TripType.MULTI_CITY,+ passenger_info: { adults: 1, children: 0, infants_in_seat: 0, infants_on_lap: 0 },+ flight_segments: [+ leg(Airport.JFK, Airport.LHR, inDays(30)),+ leg(Airport.LHR, Airport.CDG, inDays(34)),+ leg(Airport.CDG, Airport.JFK, inDays(38)),+ ],+});++const itineraries = (await new SearchFlights().search(filters, { topN: 3 })) as+ | FlightResult[][]+ | null;++for (const legs of itineraries ?? []) {+ const total = legs.reduce((sum, l) => sum + (l.price ?? 0), 0);+ console.log(`Itinerary total: $${total}`);+}+```++## Error handling++```ts+import {+ SearchConnectionError,+ SearchHTTPError,+ SearchTimeoutError,+} from "fli-js";++try {+ await new SearchFlights().search(filters);+} catch (err) {+ if (err instanceof SearchTimeoutError) {+ // raise the client timeout and retry+ } else if (err instanceof SearchConnectionError) {+ // network/proxy problem+ } else if (err instanceof SearchHTTPError) {+ // non-2xx from Google+ } else {+ throw err;+ }+}+```++See the [Python examples](../python/examples.md) for the equivalent scripts.diff --git a/docs/typescript/quickstart.md b/docs/typescript/quickstart.mdnew file mode 100644index 0000000..00f7077--- /dev/null+++ b/docs/typescript/quickstart.md@@ -0,0 +1,204 @@+# TypeScript Quick Start++`fli` is a 1:1 TypeScript / JavaScript port of the Python library, published+to npm as [`fli-js`](https://www.npmjs.com/package/fli-js). It mirrors the Python+package — same models, same filter encoding, same wire-format decoders — and+talks directly to Google Flights (no scraping).++## Installation++```bash+bun add fli-js # or: npm install fli-js / pnpm add fli-js+```++The package ships ESM type definitions. It runs on Bun and on Node via a+TypeScript loader such as [`tsx`](https://github.com/privatenumber/tsx).++## One-way search++```ts+import {+ Airport,+ FlightSearchFilters,+ FlightSegment,+ MaxStops,+ SearchFlights,+ SeatType,+ SortBy,+} from "fli-js";++// travel_date must be in the future, so compute it dynamically.+const inDays = (n: number) => new Date(Date.now() + n * 86_400_000).toISOString().slice(0, 10);++const filters = new FlightSearchFilters({+ passenger_info: { adults: 1, children: 0, infants_in_seat: 0, infants_on_lap: 0 },+ flight_segments: [+ new FlightSegment({+ departure_airport: [[[Airport.JFK, 0]]],+ arrival_airport: [[[Airport.LAX, 0]]],+ travel_date: inDays(30),+ }),+ ],+ seat_type: SeatType.ECONOMY,+ stops: MaxStops.NON_STOP,+ sort_by: SortBy.CHEAPEST,+});++const results = await new SearchFlights().search(filters, { currency: "USD" });+for (const flight of results ?? []) {+ console.log(`$${flight.price ?? "N/A"} — ${flight.duration} min — ${flight.stops} stop(s)`);+}+```++!!! note "Airport nesting"+ `departure_airport` / `arrival_airport` are **triple-nested**:+ `[[[Airport.JFK, 0]]]`. The inner pair is `[airport, 0]`; the extra+ levels mirror the Google Flights wire format.++!!! note "Plain objects, not classes"+ `PassengerInfo`, `TimeRestrictions`, and `LayoverRestrictions` are+ object types (Zod schemas), not classes — pass object literals.+ `FlightSearchFilters`, `DateSearchFilters`, and `FlightSegment` are+ classes constructed with `new`.++## Round-trip search++Round-trip and multi-city searches return an array of itineraries, where each+itinerary is an array of `FlightResult` — one per leg, in order.++```ts+import {+ Airport,+ type FlightResult,+ FlightSearchFilters,+ FlightSegment,+ SearchFlights,+ TripType,+} from "fli-js";++const inDays = (n: number) => new Date(Date.now() + n * 86_400_000).toISOString().slice(0, 10);++const filters = new FlightSearchFilters({+ trip_type: TripType.ROUND_TRIP,+ passenger_info: { adults: 1, children: 0, infants_in_seat: 0, infants_on_lap: 0 },+ flight_segments: [+ new FlightSegment({+ departure_airport: [[[Airport.JFK, 0]]],+ arrival_airport: [[[Airport.LAX, 0]]],+ travel_date: inDays(30),+ }),+ new FlightSegment({+ departure_airport: [[[Airport.LAX, 0]]],+ arrival_airport: [[[Airport.JFK, 0]]],+ travel_date: inDays(37),+ }),+ ],+});++const itineraries = (await new SearchFlights().search(filters, { topN: 5 })) as+ | FlightResult[][]+ | null;++for (const [outbound, ret] of itineraries ?? []) {+ console.log(`Total $${outbound.price ?? "N/A"} (return ${ret.legs[0].flight_number})`);+}+```++## Cheapest dates++```ts+import { Airport, DateSearchFilters, FlightSegment, SearchDates } from "fli-js";++const inDays = (n: number) => new Date(Date.now() + n * 86_400_000).toISOString().slice(0, 10);++const filters = new DateSearchFilters({+ passenger_info: { adults: 1, children: 0, infants_in_seat: 0, infants_on_lap: 0 },+ flight_segments: [+ new FlightSegment({+ departure_airport: [[[Airport.JFK, 0]]],+ arrival_airport: [[[Airport.LAX, 0]]],+ travel_date: inDays(30),+ }),+ ],+ from_date: inDays(30),+ to_date: inDays(60),+});++const dates = await new SearchDates().search(filters);+for (const { date, price } of dates ?? []) {+ console.log(`${date[0].toISOString().slice(0, 10)} — $${price}`);+}+```++`DatePrice.date` is a tuple of `Date` objects: `[outbound]` for one-way,+`[outbound, return]` for round trips. Ranges larger than 61 days are split+into multiple calls automatically.++## Filters, alliances, and locale++```ts+import {+ Airline,+ Airport,+ Alliance,+ FlightSearchFilters,+ FlightSegment,+ MaxStops,+ SearchFlights,+ SeatType,+} from "fli-js";++const inDays = (n: number) => new Date(Date.now() + n * 86_400_000).toISOString().slice(0, 10);++const filters = new FlightSearchFilters({+ passenger_info: { adults: 1, children: 0, infants_in_seat: 0, infants_on_lap: 0 },+ flight_segments: [+ new FlightSegment({+ departure_airport: [[[Airport.JFK, 0]]],+ arrival_airport: [[[Airport.NRT, 0]]],+ travel_date: inDays(30),+ }),+ ],+ seat_type: SeatType.BUSINESS,+ stops: MaxStops.ONE_STOP_OR_FEWER,+ alliances: [Alliance.ONEWORLD],+ airlines_exclude: [Airline.AA],+ layover_restrictions: { airports: null, min_duration: 60, max_duration: 240 },+ max_duration: 1200, // minutes+});++// curr / hl / gl map to the search() options, not the filter object.+const flights = await new SearchFlights().search(filters, {+ currency: "EUR",+ language: "en-GB",+ country: "GB",+});+```++## Configuring the HTTP client++The `Client` rate-limits to 10 req/s and retries transient failures with+exponential backoff. Tune it or point it at a proxy:++```ts+import { Client, SearchFlights } from "fli-js";++const client = new Client({+ timeoutMs: 30_000,+ retries: 5,+ proxy: "http://user:[email protected]:8080", // or HTTPS_PROXY / HTTP_PROXY env+});++const search = new SearchFlights(client);+```++Typed errors — `SearchTimeoutError`, `SearchConnectionError`,+`SearchHTTPError`, all extending `SearchClientError` — let you branch on+failure mode.++## Next steps++* Browse the [TypeScript examples](examples.md)+* Compare with the [Python Quick Start](../python/quickstart.md)+* The full TypeScript source lives in+ [`fli-js/`](https://github.com/punitarani/fli/tree/main/fli-js)diff --git a/examples/README.md b/examples/README.mdindex a8bb6ba..d54787f 100644--- a/examples/README.md+++ b/examples/README.md@@ -1,232 +1,34 @@# Fli Examples-This directory contains practical examples demonstrating various features of the Fli flight search library. Each example is a standalone Python script that you can run directly.--## Basic Examples--### [basic\_one\_way\_search.py](basic_one_way_search.py)--**Simple one-way flight search**--* Basic flight search between two airports-* Demonstrates core API usage-* Shows result processing and display--### [round\_trip\_search.py](round_trip_search.py)--**Round trip flight search**--* Search for outbound and return flights-* Process round trip results-* Handle flight combinations--### [date\_range\_search.py](date_range_search.py)--**Search across date ranges**--* Find cheapest dates to fly-* Date-based price comparison-* Flexible departure dates--## Advanced Examples--### [complex\_flight\_search.py](complex_flight_search.py)--**Multi-filter flight search**--* Multiple passengers (adults, children, infants)-* Airline preferences-* Layover restrictions-* Duration limits-* Business class search--### [time\_restrictions\_search.py](time_restrictions_search.py)--**Time-constrained searches**--* Departure time preferences-* Arrival time constraints-* Morning vs evening flights--### [date\_search\_with\_preferences.py](date_search_with_preferences.py)--**Advanced date filtering**--* Weekend-only flights-* Day-of-week filtering-* Custom date preferences--### [complex\_round\_trip\_validation.py](complex_round_trip_validation.py)--**Enterprise-level round trip search**--* Comprehensive date validation-* Complex passenger configurations-* Multi-airline preferences-* Layover optimization-* Time restrictions for both directions--### [advanced\_date\_search\_validation.py](advanced_date_search_validation.py)--**Validated date range searching**--* Date range validation-* Stay duration constraints-* Weekend trip optimization-* Round trip date searches--## Utility Examples--### [price\_tracking.py](price_tracking.py)--**Monitor price changes**--* Track prices over time-* Price history analysis-* Trend identification-* Deal alerting concepts--### [error\_handling\_with\_retries.py](error_handling_with_retries.py)--**Robust error handling**--* Retry logic implementation-* Rate limit handling-* Exponential backoff (with tenacity)-* Fallback strategies--### [result\_processing.py](result_processing.py)--**Advanced result analysis**--* Data format conversion-* Statistical analysis-* Pandas integration (optional)-* CSV export capabilities--## Running the Examples--### Prerequisites--```bash-# Install the main library-pip install flights--# For advanced examples with optional dependencies-pip install pandas tenacity-```--### Running Examples--**Recommended approach (using uv):**--```bash-# Run any example with uv (automatically handles dependencies)-uv run python examples/basic_one_way_search.py--# Or from the project root-uv run python -m examples.basic_one_way_search-```--**Alternative approaches:**--```bash-# Option 1: Install the package first-pip install flights-python examples/basic_one_way_search.py--# Option 2: Install dependencies manually-pip install pydantic curl_cffi httpx-python examples/basic_one_way_search.py--# Option 3: Use virtual environment-python -m venv venv-source venv/bin/activate # On Windows: venv\Scripts\activate-pip install pydantic curl_cffi httpx-python examples/basic_one_way_search.py-```--**Dependency checking:**-All examples now include automatic dependency checking. If you're missing required packages, you'll see a helpful error message with installation instructions.--### Customizing Examples--Each example includes:--* Clear documentation and comments-* Configurable parameters (airports, dates, etc.)-* Error handling-* Result formatting--Feel free to modify the examples for your specific use cases:--1. **Change airports**: Replace `Airport.JFK` and `Airport.LAX` with your preferred airports-2. **Adjust dates**: Update travel dates to your desired timeframe-3. **Modify filters**: Change passenger counts, seat types, airlines, etc.-4. **Customize output**: Modify the result processing to match your needs--## Example Categories--| Category | Examples | Key Features |-|----------|----------|--------------|-| **Basic** | `basic_one_way_search`, `round_trip_search`, `date_range_search` | Core functionality, simple usage |-| **Advanced** | `complex_flight_search`, `time_restrictions_search`, `date_search_with_preferences` | Multiple filters, constraints |-| **Enterprise** | `complex_round_trip_validation`, `advanced_date_search_validation` | Validation, complex requirements |-| **Utilities** | `price_tracking`, `error_handling_with_retries`, `result_processing` | Robust implementation, analysis |--## Common Patterns--### Airport Selection--```python-from fli.models import Airport--# Major US airports-Airport.JFK, Airport.LAX, Airport.ORD, Airport.DFW-Airport.SFO, Airport.BOS, Airport.MIA, Airport.SEA--# International airports-Airport.LHR, Airport.CDG, Airport.NRT, Airport.SYD-```--### Date Handling--```python-from datetime import datetime, timedelta--# Future dates (required)-future_date = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")--# Date ranges-from_date = "2026-06-01"-to_date = "2026-06-30"-```--### Passenger Configuration--```python-from fli.models import PassengerInfo--# Single traveler-PassengerInfo(adults=1)--# Family with children-PassengerInfo(adults=2, children=2, infants_on_lap=1)-```--## Support--For questions about the examples or the Fli library:--* Check the [main documentation](../docs/)-* Review the [API reference](../docs/api/)-* See [advanced usage patterns](../docs/examples/advanced.md)--## Contributing--Found an issue or want to add an example? Contributions are welcome!--* Ensure examples are well-documented-* Include error handling-* Test with various configurations-* Follow the existing code style+Practical, runnable examples for the Fli flight-search library, organized by+language. Both sets mirror each other so you can compare the Python and+TypeScript APIs side by side.++| Language | Directory | Run with |+|----------|-----------|----------|+| Python | [`python/`](python) | `uv run python examples/python/<file>.py` |+| TypeScript | [`typescript/`](typescript) | `bun run examples/typescript/<file>.ts` |++> All examples hit the live Google Flights API. Requests are rate-limited+> (10 req/s) and results reflect real-time availability and pricing.++## What's covered++| Example | Python | TypeScript |+|---------|:------:|:----------:|+| One-way search | ✅ | ✅ |+| Round-trip search | ✅ | ✅ |+| Cheapest dates in a range | ✅ | ✅ |+| Multi-city itinerary | ✅ | ✅ |+| Advanced filters (alliances, exclusions, layovers, locale) | ✅ | ✅ |+| Error handling & client tuning | ✅ | ✅ |+| Time-restricted search | ✅ | — |+| Day-of-week / weekend date preferences | ✅ | — |+| Validation-heavy round trips & date ranges | ✅ | — |+| Price tracking over time | ✅ | — |+| Result processing (pandas) | ✅ | — |++See each directory's README for setup and the full file list:++- [Python examples →](python/README.md)+- [TypeScript examples →](typescript/README.md)diff --git a/examples/python/README.md b/examples/python/README.mdnew file mode 100644index 0000000..77db876--- /dev/null+++ b/examples/python/README.md@@ -0,0 +1,59 @@+# Fli Python Examples++Runnable Python examples for the [`flights`](https://pypi.org/project/flights/)+library. Each file is standalone and mirrors its TypeScript counterpart in+[`../typescript`](../typescript) where one exists.++> These examples talk to the live Google Flights API. They are rate-limited+> (10 req/s) and results vary with real availability and pricing.++## Setup++```bash+# From the repo root, with uv (recommended — handles dependencies):+uv run python examples/python/basic_one_way_search.py++# Or install the package and run directly:+pip install flights+python examples/python/basic_one_way_search.py+```++`result_processing.py` additionally uses `pandas`, and+`error_handling_with_retries.py` uses `tenacity`:++```bash+pip install pandas tenacity+```++## Examples++### Core++| File | What it shows |+|------|---------------|+| `basic_one_way_search.py` | Minimal one-way search and result printing |+| `round_trip_search.py` | Round trip; results returned as `(outbound, return)` tuples |+| `date_range_search.py` | Cheapest dates across a flexible window |+| `multi_city_search.py` | Three-leg multi-city itinerary |+| `advanced_filters_search.py` | Alliances, airline exclusions, layover bounds, currency/locale |+| `error_handling_with_retries.py` | Retry logic with exponential backoff |++### Going further++| File | What it shows |+|------|---------------|+| `complex_flight_search.py` | Multiple passengers, airlines, layover restrictions, business class |+| `time_restrictions_search.py` | Departure/arrival time windows |+| `date_search_with_preferences.py` | Day-of-week / weekend-only date filtering |+| `complex_round_trip_validation.py` | Validation-heavy round trip with time + layover rules |+| `advanced_date_search_validation.py` | Validated date-range search with stay-length constraints |+| `price_tracking.py` | Monitoring prices across repeated searches |+| `result_processing.py` | Converting results to a pandas DataFrame for analysis |++## Notes++- `FlightSegment` airports are double-nested: `[[Airport.JFK, 0]]`.+- `currency` / `language` / `country` are passed to `search()`, not to the+ filter object.+- Round-trip and multi-city searches return a list of tuples of+ `FlightResult` (one per leg). One-way returns a flat `list[FlightResult]`.diff --git a/examples/advanced_date_search_validation.py b/examples/python/advanced_date_search_validation.pysimilarity index 100%rename from examples/advanced_date_search_validation.pyrename to examples/python/advanced_date_search_validation.pydiff --git a/examples/python/advanced_filters_search.py b/examples/python/advanced_filters_search.pynew file mode 100644index 0000000..ddd8dc1--- /dev/null+++ b/examples/python/advanced_filters_search.py@@ -0,0 +1,67 @@+#!/usr/bin/env python3+"""Advanced filtering: alliances, exclusions, layovers, and locale.++This example pulls together the filters that are easy to miss:++* restrict to an airline **alliance** while **excluding** a specific carrier,+* bound layover duration and total trip duration,+* return prices in a non-USD currency for a specific language/country.++Currency, language, and country are passed to ``search()`` (they map to+Google's ``curr`` / ``hl`` / ``gl`` URL params), not to the filter object.+"""++from datetime import datetime, timedelta++from fli.models import (+ Airline,+ Airport,+ Alliance,+ FlightSearchFilters,+ FlightSegment,+ LayoverRestrictions,+ MaxStops,+ PassengerInfo,+ SeatType,+ SortBy,+)+from fli.search import SearchFlights+++def main():+ filters = FlightSearchFilters(+ passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ FlightSegment(+ departure_airport=[[Airport.JFK, 0]],+ arrival_airport=[[Airport.NRT, 0]],+ travel_date=(datetime.now() + timedelta(days=45)).strftime("%Y-%m-%d"),+ )+ ],+ seat_type=SeatType.BUSINESS,+ stops=MaxStops.ONE_STOP_OR_FEWER,+ alliances=[Alliance.ONEWORLD], # only Oneworld carriers...+ airlines_exclude=[Airline.AA], # ...but skip American+ layover_restrictions=LayoverRestrictions(min_duration=60, max_duration=240),+ max_duration=1200, # 20 hours door-to-door, in minutes+ sort_by=SortBy.DURATION,+ )++ search = SearchFlights()+ flights = search.search(filters, currency="EUR", language="en-GB", country="GB")++ if not flights:+ print("No flights matched the filters.")+ return++ print(f"Found {len(flights)} flights (prices in EUR):\n")+ for flight in flights[:10]:+ carriers = " / ".join(sorted({leg.airline.value for leg in flight.legs}))+ print(+ f" €{flight.price:<7.0f} {flight.duration:>4} min "+ f"{flight.stops} stop(s) via {carriers}"+ )+++if __name__ == "__main__":+ main()diff --git a/examples/basic_one_way_search.py b/examples/python/basic_one_way_search.pysimilarity index 100%rename from examples/basic_one_way_search.pyrename to examples/python/basic_one_way_search.pydiff --git a/examples/complex_flight_search.py b/examples/python/complex_flight_search.pysimilarity index 100%rename from examples/complex_flight_search.pyrename to examples/python/complex_flight_search.pydiff --git a/examples/complex_round_trip_validation.py b/examples/python/complex_round_trip_validation.pysimilarity index 100%rename from examples/complex_round_trip_validation.pyrename to examples/python/complex_round_trip_validation.pydiff --git a/examples/date_range_search.py b/examples/python/date_range_search.pysimilarity index 100%rename from examples/date_range_search.pyrename to examples/python/date_range_search.pydiff --git a/examples/date_search_with_preferences.py b/examples/python/date_search_with_preferences.pysimilarity index 100%rename from examples/date_search_with_preferences.pyrename to examples/python/date_search_with_preferences.pydiff --git a/examples/error_handling_with_retries.py b/examples/python/error_handling_with_retries.pysimilarity index 100%rename from examples/error_handling_with_retries.pyrename to examples/python/error_handling_with_retries.pydiff --git a/examples/python/multi_city_search.py b/examples/python/multi_city_search.pynew file mode 100644index 0000000..5a3926c--- /dev/null+++ b/examples/python/multi_city_search.py@@ -0,0 +1,67 @@+#!/usr/bin/env python3+"""Multi-city flight search example.++This example demonstrates how to search a multi-city itinerary (three or+more one-way legs on different dates) in a single request. Multi-city+results come back as tuples of ``FlightResult`` — one entry per leg, in+the order the legs were supplied.+"""++from datetime import datetime, timedelta++from fli.models import (+ Airport,+ FlightSearchFilters,+ FlightSegment,+ PassengerInfo,+ SeatType,+ TripType,+)+from fli.search import SearchFlights+++def main():+ base = datetime.now() + timedelta(days=30)++ def leg(origin: Airport, destination: Airport, day_offset: int) -> FlightSegment:+ return FlightSegment(+ departure_airport=[[origin, 0]],+ arrival_airport=[[destination, 0]],+ travel_date=(base + timedelta(days=day_offset)).strftime("%Y-%m-%d"),+ )++ # JFK -> LHR, a few days in London, LHR -> CDG, then CDG -> JFK home.+ filters = FlightSearchFilters(+ trip_type=TripType.MULTI_CITY,+ passenger_info=PassengerInfo(adults=1),+ flight_segments=[+ leg(Airport.JFK, Airport.LHR, 0),+ leg(Airport.LHR, Airport.CDG, 4),+ leg(Airport.CDG, Airport.JFK, 7),+ ],+ seat_type=SeatType.ECONOMY,+ )++ search = SearchFlights()+ # top_n controls how many outbound options each leg is expanded against.+ itineraries = search.search(filters, top_n=3)++ if not itineraries:+ print("No itineraries found.")+ return++ print(f"Found {len(itineraries)} multi-city itineraries:\n")+ for i, legs in enumerate(itineraries, 1):+ total = sum(segment.price for segment in legs)+ print(f"--- Itinerary {i} — total ${total:.0f} ---")+ for segment in legs:+ first, last = segment.legs[0], segment.legs[-1]+ print(+ f" {first.departure_airport.value} -> {last.arrival_airport.value}"+ f" ${segment.price:.0f} {segment.duration} min {segment.stops} stop(s)"+ )+ print()+++if __name__ == "__main__":+ main()diff --git a/examples/price_tracking.py b/examples/python/price_tracking.pysimilarity index 100%rename from examples/price_tracking.pyrename to examples/python/price_tracking.pydiff --git a/examples/result_processing.py b/examples/python/result_processing.pysimilarity index 100%rename from examples/result_processing.pyrename to examples/python/result_processing.pydiff --git a/examples/round_trip_search.py b/examples/python/round_trip_search.pysimilarity index 100%rename from examples/round_trip_search.pyrename to examples/python/round_trip_search.pydiff --git a/examples/time_restrictions_search.py b/examples/python/time_restrictions_search.pysimilarity index 100%rename from examples/time_restrictions_search.pyrename to examples/python/time_restrictions_search.pydiff --git a/examples/typescript/README.md b/examples/typescript/README.mdnew file mode 100644index 0000000..ac04d54--- /dev/null+++ b/examples/typescript/README.md@@ -0,0 +1,58 @@+# Fli TypeScript Examples++Runnable TypeScript examples for the [`fli-js`](https://www.npmjs.com/package/fli-js)+library. Each file is standalone and mirrors its Python counterpart in+[`../python`](../python).++> These examples talk to the live Google Flights API. They are rate-limited+> (10 req/s) and results vary with real availability and pricing.++## Setup++```bash+cd examples/typescript+bun install # or: npm install / pnpm install+```++## Run++With [Bun](https://bun.sh) (recommended — runs `.ts` directly):++```bash+bun run basic_one_way_search.ts+# or via the package scripts:+bun run basic # one-way+bun run round-trip # round trip+bun run dates # cheapest dates in a range+bun run multi-city # 3-leg itinerary+bun run advanced # alliances + exclusions + locale+bun run errors # client tuning + typed error handling+```++With Node, run them through a TS loader such as [`tsx`](https://github.com/privatenumber/tsx):++```bash+npx tsx basic_one_way_search.ts+```++## Examples++| File | What it shows |+|------|---------------|+| `basic_one_way_search.ts` | Minimal one-way search and result printing |+| `round_trip_search.ts` | Round trip; itineraries returned as `[outbound, return]` |+| `date_range_search.ts` | Cheapest dates across a flexible window |+| `multi_city_search.ts` | Three-leg multi-city itinerary |+| `advanced_filters_search.ts` | Alliances, airline exclusions, layover bounds, currency/locale |+| `error_handling_with_retries.ts` | Custom `Client` config and typed `Search*Error` handling |++## Notes++- `FlightSegment` airports are triple-nested: `[[[Airport.JFK, 0]]]`.+- `PassengerInfo`, `TimeRestrictions`, and `LayoverRestrictions` are plain+ objects (not classes) — pass object literals.+- `currency` / `language` / `country` are passed to `search()`, not to the+ filter object.+- Round-trip and multi-city searches return an array of itineraries, each an+ array of `FlightResult` (one per leg). One-way returns a flat+ `FlightResult[]`.diff --git a/examples/typescript/advanced_filters_search.ts b/examples/typescript/advanced_filters_search.tsnew file mode 100644index 0000000..cbdd9dc--- /dev/null+++ b/examples/typescript/advanced_filters_search.ts@@ -0,0 +1,70 @@+/**+ * Advanced filtering: alliances, exclusions, layovers, and locale.+ *+ * Mirrors examples/python/advanced_filters_search.py. Currency, language,+ * and country are passed to search() (Google's curr / hl / gl params), not+ * to the filter object. Run with:+ * bun run advanced_filters_search.ts+ */+import {+ Airline,+ Airport,+ Alliance,+ type FlightResult,+ FlightSearchFilters,+ FlightSegment,+ MaxStops,+ SearchFlights,+ SeatType,+ SortBy,+} from "fli-js";++function inDays(days: number): string {+ const d = new Date();+ d.setDate(d.getDate() + days);+ return d.toISOString().slice(0, 10);+}++async function main(): Promise<void> {+ const filters = new FlightSearchFilters({+ passenger_info: { adults: 1, children: 0, infants_in_seat: 0, infants_on_lap: 0 },+ flight_segments: [+ new FlightSegment({+ departure_airport: [[[Airport.JFK, 0]]],+ arrival_airport: [[[Airport.NRT, 0]]],+ travel_date: inDays(45),+ }),+ ],+ seat_type: SeatType.BUSINESS,+ stops: MaxStops.ONE_STOP_OR_FEWER,+ alliances: [Alliance.ONEWORLD], // only Oneworld carriers...+ airlines_exclude: [Airline.AA], // ...but skip American+ layover_restrictions: { airports: null, min_duration: 60, max_duration: 240 },+ max_duration: 1200, // 20 hours, in minutes+ sort_by: SortBy.DURATION,+ });++ const flights = (await new SearchFlights().search(filters, {+ currency: "EUR",+ language: "en-GB",+ country: "GB",+ })) as FlightResult[] | null;++ if (!flights?.length) {+ console.log("No flights matched the filters.");+ return;+ }++ console.log(`Found ${flights.length} flights (prices in EUR):`);+ for (const flight of flights.slice(0, 10)) {+ const carriers = [...new Set(flight.legs.map((l) => l.airline))].sort().join(" / ");+ console.log(+ ` EUR ${flight.price ?? "N/A"} ${flight.duration} min ${flight.stops} stop(s) via ${carriers}`,+ );+ }+}++main().catch((err) => {+ console.error(err);+ process.exit(1);+});diff --git a/examples/typescript/basic_one_way_search.ts b/examples/typescript/basic_one_way_search.tsnew file mode 100644index 0000000..208f288--- /dev/null+++ b/examples/typescript/basic_one_way_search.ts@@ -0,0 +1,65 @@+/**+ * Basic one-way flight search.+ *+ * Mirrors examples/python/basic_one_way_search.py. Run with:+ * bun run basic_one_way_search.ts+ */+import {+ Airport,+ type FlightResult,+ FlightSearchFilters,+ FlightSegment,+ MaxStops,+ SearchFlights,+ SeatType,+ SortBy,+} from "fli-js";++function inDays(days: number): string {+ const d = new Date();+ d.setDate(d.getDate() + days);+ return d.toISOString().slice(0, 10);+}++async function main(): Promise<void> {+ const filters = new FlightSearchFilters({+ passenger_info: { adults: 1, children: 0, infants_in_seat: 0, infants_on_lap: 0 },+ flight_segments: [+ new FlightSegment({+ departure_airport: [[[Airport.JFK, 0]]],+ arrival_airport: [[[Airport.LAX, 0]]],+ travel_date: inDays(30),+ }),+ ],+ seat_type: SeatType.ECONOMY,+ stops: MaxStops.NON_STOP,+ sort_by: SortBy.CHEAPEST,+ });++ const results = (await new SearchFlights().search(filters, { currency: "USD" })) as+ | FlightResult[]+ | null;++ if (!results?.length) {+ console.log("No flights found.");+ return;+ }++ for (const flight of results) {+ console.log(+ `Price: $${flight.price ?? "N/A"} Duration: ${flight.duration} min Stops: ${flight.stops}`,+ );+ for (const leg of flight.legs) {+ console.log(+ ` ${leg.airline} ${leg.flight_number}: ` ++ `${leg.departure_airport} ${leg.departure_datetime.toISOString()} -> ` ++ `${leg.arrival_airport} ${leg.arrival_datetime.toISOString()}`,+ );+ }+ }+}++main().catch((err) => {+ console.error(err);+ process.exit(1);+});diff --git a/examples/typescript/date_range_search.ts b/examples/typescript/date_range_search.tsnew file mode 100644index 0000000..df1da9a--- /dev/null+++ b/examples/typescript/date_range_search.ts@@ -0,0 +1,48 @@+/**+ * Find the cheapest dates to fly within a range.+ *+ * Mirrors examples/python/date_range_search.py. SearchDates returns a+ * DatePrice[] where `date` is a tuple of Date objects ([outbound] for+ * one-way, [outbound, return] for round trips). Run with:+ * bun run date_range_search.ts+ */+import { Airport, DateSearchFilters, FlightSegment, SearchDates } from "fli-js";++function inDays(days: number): string {+ const d = new Date();+ d.setDate(d.getDate() + days);+ return d.toISOString().slice(0, 10);+}++async function main(): Promise<void> {+ const filters = new DateSearchFilters({+ passenger_info: { adults: 1, children: 0, infants_in_seat: 0, infants_on_lap: 0 },+ flight_segments: [+ new FlightSegment({+ departure_airport: [[[Airport.JFK, 0]]],+ arrival_airport: [[[Airport.LAX, 0]]],+ travel_date: inDays(30),+ }),+ ],+ from_date: inDays(30),+ to_date: inDays(60),+ });++ const dates = await new SearchDates().search(filters, { currency: "USD" });++ if (!dates?.length) {+ console.log("No priced dates found.");+ return;+ }++ const cheapest = [...dates].sort((a, b) => a.price - b.price).slice(0, 10);+ console.log("Cheapest dates:");+ for (const { date, price } of cheapest) {+ console.log(` ${date[0].toISOString().slice(0, 10)} $${price}`);+ }+}++main().catch((err) => {+ console.error(err);+ process.exit(1);+});diff --git a/examples/typescript/error_handling_with_retries.ts b/examples/typescript/error_handling_with_retries.tsnew file mode 100644index 0000000..b6e8911--- /dev/null+++ b/examples/typescript/error_handling_with_retries.ts@@ -0,0 +1,65 @@+/**+ * Error handling and custom client configuration.+ *+ * The Client already retries transient failures (3 attempts, exponential+ * backoff) and rate-limits to 10 req/s. This shows how to tune it and how+ * to distinguish the typed search errors. Run with:+ * bun run error_handling_with_retries.ts+ */+import {+ Airport,+ Client,+ type FlightResult,+ FlightSearchFilters,+ FlightSegment,+ SearchClientError,+ SearchConnectionError,+ SearchFlights,+ SearchHTTPError,+ SearchTimeoutError,+} from "fli-js";++function inDays(days: number): string {+ const d = new Date();+ d.setDate(d.getDate() + days);+ return d.toISOString().slice(0, 10);+}++async function main(): Promise<void> {+ // Tune the client: longer timeout, more retries, optional proxy via env.+ const client = new Client({ timeoutMs: 30_000, retries: 5, backoffMs: 1_000 });++ const filters = new FlightSearchFilters({+ passenger_info: { adults: 1, children: 0, infants_in_seat: 0, infants_on_lap: 0 },+ flight_segments: [+ new FlightSegment({+ departure_airport: [[[Airport.JFK, 0]]],+ arrival_airport: [[[Airport.LAX, 0]]],+ travel_date: inDays(30),+ }),+ ],+ });++ try {+ const results = (await new SearchFlights(client).search(filters)) as FlightResult[] | null;+ console.log(`Found ${results?.length ?? 0} flights.`);+ } catch (err) {+ if (err instanceof SearchTimeoutError) {+ console.error("Request timed out — try raising timeoutMs.");+ } else if (err instanceof SearchConnectionError) {+ console.error("Network/connection problem — check connectivity or proxy.");+ } else if (err instanceof SearchHTTPError) {+ console.error(`Google returned an HTTP error: ${err.message}`);+ } else if (err instanceof SearchClientError) {+ console.error(`Client error: ${err.message}`);+ } else {+ throw err;+ }+ process.exit(1);+ }+}++main().catch((err) => {+ console.error(err);+ process.exit(1);+});diff --git a/examples/typescript/multi_city_search.ts b/examples/typescript/multi_city_search.tsnew file mode 100644index 0000000..0441d56--- /dev/null+++ b/examples/typescript/multi_city_search.ts@@ -0,0 +1,71 @@+/**+ * Multi-city itinerary search (three legs on different dates).+ *+ * Mirrors examples/python/multi_city_search.py. Results come back as an+ * array of itineraries, each itinerary an array of FlightResult — one per+ * leg, in order. Run with:+ * bun run multi_city_search.ts+ */+import {+ Airport,+ type FlightResult,+ FlightSearchFilters,+ FlightSegment,+ SeatType,+ SearchFlights,+ TripType,+} from "fli-js";++function inDays(days: number): string {+ const d = new Date();+ d.setDate(d.getDate() + days);+ return d.toISOString().slice(0, 10);+}++function leg(from: Airport, to: Airport, dayOffset: number): FlightSegment {+ return new FlightSegment({+ departure_airport: [[[from, 0]]],+ arrival_airport: [[[to, 0]]],+ travel_date: inDays(30 + dayOffset),+ });+}++async function main(): Promise<void> {+ const filters = new FlightSearchFilters({+ trip_type: TripType.MULTI_CITY,+ passenger_info: { adults: 1, children: 0, infants_in_seat: 0, infants_on_lap: 0 },+ flight_segments: [+ leg(Airport.JFK, Airport.LHR, 0),+ leg(Airport.LHR, Airport.CDG, 4),+ leg(Airport.CDG, Airport.JFK, 7),+ ],+ seat_type: SeatType.ECONOMY,+ });++ const itineraries = (await new SearchFlights().search(filters, { topN: 3 })) as+ | FlightResult[][]+ | null;++ if (!itineraries?.length) {+ console.log("No itineraries found.");+ return;+ }++ itineraries.forEach((legs, i) => {+ const total = legs.reduce((sum, l) => sum + (l.price ?? 0), 0);+ console.log(`Itinerary ${i + 1} — total $${total.toFixed(0)}`);+ for (const segment of legs) {+ const first = segment.legs[0];+ const last = segment.legs[segment.legs.length - 1];+ console.log(+ ` ${first.departure_airport} -> ${last.arrival_airport} ` ++ `$${segment.price ?? "N/A"} ${segment.duration} min ${segment.stops} stop(s)`,+ );+ }+ });+}++main().catch((err) => {+ console.error(err);+ process.exit(1);+});diff --git a/examples/typescript/package.json b/examples/typescript/package.jsonnew file mode 100644index 0000000..42b3dfd--- /dev/null+++ b/examples/typescript/package.json@@ -0,0 +1,17 @@+{+ "name": "fli-typescript-examples",+ "private": true,+ "type": "module",+ "description": "Runnable TypeScript examples for the fli library.",+ "scripts": {+ "basic": "bun run basic_one_way_search.ts",+ "round-trip": "bun run round_trip_search.ts",+ "dates": "bun run date_range_search.ts",+ "multi-city": "bun run multi_city_search.ts",+ "advanced": "bun run advanced_filters_search.ts",+ "errors": "bun run error_handling_with_retries.ts"+ },+ "dependencies": {+ "fli-js": "^0.0.4"+ }+}diff --git a/examples/typescript/round_trip_search.ts b/examples/typescript/round_trip_search.tsnew file mode 100644index 0000000..129043b--- /dev/null+++ b/examples/typescript/round_trip_search.ts@@ -0,0 +1,71 @@+/**+ * Round-trip flight search.+ *+ * Mirrors examples/python/round_trip_search.py. Round-trip and multi-city+ * searches return an array of itineraries, each itinerary being an array of+ * FlightResult — one per leg, in order. Run with:+ * bun run round_trip_search.ts+ */+import {+ Airport,+ type FlightResult,+ FlightSearchFilters,+ FlightSegment,+ SearchFlights,+ TripType,+} from "fli-js";++function inDays(days: number): string {+ const d = new Date();+ d.setDate(d.getDate() + days);+ return d.toISOString().slice(0, 10);+}++async function main(): Promise<void> {+ const filters = new FlightSearchFilters({+ trip_type: TripType.ROUND_TRIP,+ passenger_info: { adults: 1, children: 0, infants_in_seat: 0, infants_on_lap: 0 },+ flight_segments: [+ new FlightSegment({+ departure_airport: [[[Airport.JFK, 0]]],+ arrival_airport: [[[Airport.LAX, 0]]],+ travel_date: inDays(30),+ }),+ new FlightSegment({+ departure_airport: [[[Airport.LAX, 0]]],+ arrival_airport: [[[Airport.JFK, 0]]],+ travel_date: inDays(37),+ }),+ ],+ });++ const itineraries = (await new SearchFlights().search(filters, { topN: 5 })) as+ | FlightResult[][]+ | null;++ if (!itineraries?.length) {+ console.log("No itineraries found.");+ return;+ }++ for (const [outbound, ret] of itineraries) {+ console.log(`Total: $${outbound.price ?? "N/A"}`);+ for (const [label, flight] of [+ ["Outbound", outbound],+ ["Return", ret],+ ] as const) {+ console.log(` ${label}:`);+ for (const leg of flight.legs) {+ console.log(+ ` ${leg.airline} ${leg.flight_number} ` ++ `${leg.departure_datetime.toISOString()} -> ${leg.arrival_datetime.toISOString()}`,+ );+ }+ }+ }+}++main().catch((err) => {+ console.error(err);+ process.exit(1);+});diff --git a/examples/typescript/tsconfig.json b/examples/typescript/tsconfig.jsonnew file mode 100644index 0000000..bd6601a--- /dev/null+++ b/examples/typescript/tsconfig.json@@ -0,0 +1,12 @@+{+ "compilerOptions": {+ "target": "ESNext",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "noEmit": true,+ "skipLibCheck": true,+ "types": ["bun-types"]+ },+ "include": ["*.ts"]+}diff --git a/mkdocs.yml b/mkdocs.ymlindex 9ca5104..5ee284a 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -98,13 +98,13 @@ extra:nav:- Home: index.md- - Getting Started:- - Quick Start: guides/quickstart.md- - Examples: examples/advanced.md- - MCP Server: guides/mcp.md- - API Reference:- - Models: api/models.md- - Search: api/search.md- - Contributing:- - Releasing (PyPI): guides/release.md- - Releasing (npm): guides/release-npm.md+ - Python:+ - Quick Start: python/quickstart.md+ - Examples: python/examples.md+ - API Reference:+ - Models: python/api/models.md+ - Search: python/api/search.md+ - TypeScript:+ - Quick Start: typescript/quickstart.md+ - Examples: typescript/examples.md+ - MCP Server: guides/mcp.md