@tks/wayfinder 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +48 -0
- package/bin/wayfinder +5 -0
- package/package.json +26 -0
- package/src/cli.ts +95 -0
- package/src/config.ts +46 -0
- package/src/errors.ts +9 -0
- package/src/format.ts +102 -0
- package/src/parse.ts +228 -0
- package/src/serpapi.ts +208 -0
- package/src/types.ts +36 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Takeshi Ohishi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# wayfinder
|
|
2
|
+
|
|
3
|
+
CLI for one way flight search with SerpApi Google Flights.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
bun install
|
|
9
|
+
bun link
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
`bun link` makes the `wayfinder` command available in your shell.
|
|
13
|
+
|
|
14
|
+
## Setup
|
|
15
|
+
|
|
16
|
+
Set API key by environment variable (preferred):
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
export SERPAPI_API_KEY="your_key"
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Or store it in `~/.config/wayfinder/config.json`:
|
|
23
|
+
|
|
24
|
+
```json
|
|
25
|
+
{
|
|
26
|
+
"serpApiKey": "your_key"
|
|
27
|
+
}
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Usage examples
|
|
31
|
+
|
|
32
|
+
Search one way flights:
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
wayfinder --from SFO --to JFK --date 2026-04-10
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Search with filters:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
wayfinder --from LAX --to SEA --date 2026-04-10 --airline AS --max-stops 0 --max-price 250 --depart-after 06:00 --depart-before 12:00
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Structured output for scripting:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
wayfinder --from SFO --to JFK --date 2026-04-10 --json | jq '.results[] | {price,airline,stops}'
|
|
48
|
+
```
|
package/bin/wayfinder
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tks/wayfinder",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"private": false,
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"wayfinder": "./bin/wayfinder"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"bin",
|
|
12
|
+
"src",
|
|
13
|
+
"README.md",
|
|
14
|
+
"package.json"
|
|
15
|
+
],
|
|
16
|
+
"engines": {
|
|
17
|
+
"bun": ">=1.3.0"
|
|
18
|
+
},
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"wayfinder": "bun run src/cli.ts",
|
|
24
|
+
"test": "bun test"
|
|
25
|
+
}
|
|
26
|
+
}
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { resolveApiKey } from "./config";
|
|
2
|
+
import { CliError } from "./errors";
|
|
3
|
+
import { renderTable } from "./format";
|
|
4
|
+
import { parseCliArgs } from "./parse";
|
|
5
|
+
import { searchFlights } from "./serpapi";
|
|
6
|
+
import { ExitCode } from "./types";
|
|
7
|
+
|
|
8
|
+
interface Output {
|
|
9
|
+
stdout: (message: string) => void;
|
|
10
|
+
stderr: (message: string) => void;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface RunOptions {
|
|
14
|
+
env?: NodeJS.ProcessEnv;
|
|
15
|
+
homeDir?: string;
|
|
16
|
+
fetchImpl?: typeof fetch;
|
|
17
|
+
output?: Output;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const HELP_TEXT = `wayfinder v1 flight search
|
|
21
|
+
|
|
22
|
+
Usage:
|
|
23
|
+
wayfinder --from SFO --to JFK --date 2026-03-21 [filters]
|
|
24
|
+
wayfinder flights one-way --from SFO --to JFK --date 2026-03-21 [filters]
|
|
25
|
+
|
|
26
|
+
Required:
|
|
27
|
+
--from <IATA> Origin airport code
|
|
28
|
+
--to <IATA> Destination airport code
|
|
29
|
+
--date <YYYY-MM-DD> Departure date
|
|
30
|
+
|
|
31
|
+
Optional filters:
|
|
32
|
+
--airline <IATA> Airline code, example UA
|
|
33
|
+
--max-stops <0|1|2> Maximum number of stops
|
|
34
|
+
--max-price <USD> Max price in USD
|
|
35
|
+
--depart-after <HH:MM> Start of departure window
|
|
36
|
+
--depart-before <HH:MM> End of departure window
|
|
37
|
+
|
|
38
|
+
Output:
|
|
39
|
+
--json Print structured JSON output`;
|
|
40
|
+
|
|
41
|
+
export async function runWayfinder(
|
|
42
|
+
argv: string[] = process.argv.slice(2),
|
|
43
|
+
options: RunOptions = {},
|
|
44
|
+
): Promise<number> {
|
|
45
|
+
const output = options.output ?? {
|
|
46
|
+
stdout: (message: string) => console.log(message),
|
|
47
|
+
stderr: (message: string) => console.error(message),
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
try {
|
|
51
|
+
const parsed = parseCliArgs(argv);
|
|
52
|
+
|
|
53
|
+
if (parsed.help) {
|
|
54
|
+
output.stdout(HELP_TEXT);
|
|
55
|
+
return ExitCode.Success;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const apiKey = resolveApiKey(options.env ?? process.env, options.homeDir);
|
|
59
|
+
const flights = await searchFlights(parsed.query!, apiKey, options.fetchImpl ?? fetch);
|
|
60
|
+
|
|
61
|
+
if (flights.length === 0) {
|
|
62
|
+
throw new CliError("No flights found for the selected query", ExitCode.NoResults);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (parsed.outputJson) {
|
|
66
|
+
output.stdout(
|
|
67
|
+
JSON.stringify(
|
|
68
|
+
{
|
|
69
|
+
query: parsed.query,
|
|
70
|
+
results: flights,
|
|
71
|
+
},
|
|
72
|
+
null,
|
|
73
|
+
2,
|
|
74
|
+
),
|
|
75
|
+
);
|
|
76
|
+
} else {
|
|
77
|
+
output.stdout(renderTable(flights));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return ExitCode.Success;
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (error instanceof CliError) {
|
|
83
|
+
output.stderr(error.message);
|
|
84
|
+
return error.exitCode;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
output.stderr("Unexpected internal error");
|
|
88
|
+
return ExitCode.InternalError;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (import.meta.main) {
|
|
93
|
+
const code = await runWayfinder(process.argv.slice(2));
|
|
94
|
+
process.exitCode = code;
|
|
95
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { CliError } from "./errors";
|
|
5
|
+
import { ExitCode } from "./types";
|
|
6
|
+
|
|
7
|
+
interface ConfigFile {
|
|
8
|
+
serpApiKey?: unknown;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function resolveApiKey(env: NodeJS.ProcessEnv = process.env, homeDir = os.homedir()): string {
|
|
12
|
+
const envKey = env.SERPAPI_API_KEY?.trim();
|
|
13
|
+
if (envKey) {
|
|
14
|
+
return envKey;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const configPath = path.join(homeDir, ".config", "wayfinder", "config.json");
|
|
18
|
+
|
|
19
|
+
if (!existsSync(configPath)) {
|
|
20
|
+
throw missingKeyError();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
let parsed: ConfigFile;
|
|
24
|
+
try {
|
|
25
|
+
const raw = readFileSync(configPath, "utf8");
|
|
26
|
+
parsed = JSON.parse(raw) as ConfigFile;
|
|
27
|
+
} catch {
|
|
28
|
+
throw new CliError(
|
|
29
|
+
"Could not read ~/.config/wayfinder/config.json. Ensure it is valid JSON.",
|
|
30
|
+
ExitCode.MissingApiKey,
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (typeof parsed.serpApiKey !== "string" || parsed.serpApiKey.trim() === "") {
|
|
35
|
+
throw missingKeyError();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return parsed.serpApiKey.trim();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function missingKeyError(): CliError {
|
|
42
|
+
return new CliError(
|
|
43
|
+
"Missing SerpApi key. Set SERPAPI_API_KEY or add ~/.config/wayfinder/config.json with {\"serpApiKey\":\"...\"}.",
|
|
44
|
+
ExitCode.MissingApiKey,
|
|
45
|
+
);
|
|
46
|
+
}
|
package/src/errors.ts
ADDED
package/src/format.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { FlightOption } from "./types";
|
|
2
|
+
|
|
3
|
+
const currencyFormatter = new Intl.NumberFormat("en-US", {
|
|
4
|
+
style: "currency",
|
|
5
|
+
currency: "USD",
|
|
6
|
+
maximumFractionDigits: 0,
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
export function renderTable(options: FlightOption[]): string {
|
|
10
|
+
const rows = options.map((option) => ({
|
|
11
|
+
price: currencyFormatter.format(option.price),
|
|
12
|
+
airline: option.airline,
|
|
13
|
+
depart: option.departureTime,
|
|
14
|
+
arrive: option.arrivalTime,
|
|
15
|
+
duration: formatDuration(option.durationMinutes),
|
|
16
|
+
stops: String(option.stops),
|
|
17
|
+
}));
|
|
18
|
+
|
|
19
|
+
const headers = {
|
|
20
|
+
price: "PRICE",
|
|
21
|
+
airline: "AIRLINE",
|
|
22
|
+
depart: "DEPART",
|
|
23
|
+
arrive: "ARRIVE",
|
|
24
|
+
duration: "DURATION",
|
|
25
|
+
stops: "STOPS",
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const widths = {
|
|
29
|
+
price: maxWidth(rows, "price", headers.price),
|
|
30
|
+
airline: maxWidth(rows, "airline", headers.airline),
|
|
31
|
+
depart: maxWidth(rows, "depart", headers.depart),
|
|
32
|
+
arrive: maxWidth(rows, "arrive", headers.arrive),
|
|
33
|
+
duration: maxWidth(rows, "duration", headers.duration),
|
|
34
|
+
stops: maxWidth(rows, "stops", headers.stops),
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const lines: string[] = [];
|
|
38
|
+
|
|
39
|
+
lines.push(
|
|
40
|
+
[
|
|
41
|
+
headers.price.padEnd(widths.price),
|
|
42
|
+
headers.airline.padEnd(widths.airline),
|
|
43
|
+
headers.depart.padEnd(widths.depart),
|
|
44
|
+
headers.arrive.padEnd(widths.arrive),
|
|
45
|
+
headers.duration.padEnd(widths.duration),
|
|
46
|
+
headers.stops.padEnd(widths.stops),
|
|
47
|
+
].join(" "),
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
lines.push(
|
|
51
|
+
[
|
|
52
|
+
"-".repeat(widths.price),
|
|
53
|
+
"-".repeat(widths.airline),
|
|
54
|
+
"-".repeat(widths.depart),
|
|
55
|
+
"-".repeat(widths.arrive),
|
|
56
|
+
"-".repeat(widths.duration),
|
|
57
|
+
"-".repeat(widths.stops),
|
|
58
|
+
].join(" "),
|
|
59
|
+
);
|
|
60
|
+
|
|
61
|
+
for (const row of rows) {
|
|
62
|
+
lines.push(
|
|
63
|
+
[
|
|
64
|
+
row.price.padEnd(widths.price),
|
|
65
|
+
row.airline.padEnd(widths.airline),
|
|
66
|
+
row.depart.padEnd(widths.depart),
|
|
67
|
+
row.arrive.padEnd(widths.arrive),
|
|
68
|
+
row.duration.padEnd(widths.duration),
|
|
69
|
+
row.stops.padEnd(widths.stops),
|
|
70
|
+
].join(" "),
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return lines.join("\n");
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function maxWidth(
|
|
78
|
+
rows: Array<Record<string, string>>,
|
|
79
|
+
key: string,
|
|
80
|
+
header: string,
|
|
81
|
+
): number {
|
|
82
|
+
return rows.reduce((width, row) => Math.max(width, row[key].length), header.length);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function formatDuration(totalMinutes: number): string {
|
|
86
|
+
if (!Number.isFinite(totalMinutes) || totalMinutes <= 0) {
|
|
87
|
+
return "n/a";
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const hours = Math.floor(totalMinutes / 60);
|
|
91
|
+
const minutes = totalMinutes % 60;
|
|
92
|
+
|
|
93
|
+
if (hours === 0) {
|
|
94
|
+
return `${minutes}m`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (minutes === 0) {
|
|
98
|
+
return `${hours}h`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return `${hours}h ${minutes}m`;
|
|
102
|
+
}
|
package/src/parse.ts
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { CliError } from "./errors";
|
|
2
|
+
import { ExitCode, ParsedArgs } from "./types";
|
|
3
|
+
|
|
4
|
+
interface RawOptions {
|
|
5
|
+
from?: string;
|
|
6
|
+
to?: string;
|
|
7
|
+
date?: string;
|
|
8
|
+
airline?: string;
|
|
9
|
+
maxStops?: string;
|
|
10
|
+
maxPrice?: string;
|
|
11
|
+
departAfter?: string;
|
|
12
|
+
departBefore?: string;
|
|
13
|
+
outputJson: boolean;
|
|
14
|
+
help: boolean;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const HELP_FLAGS = new Set(["-h", "--help"]);
|
|
18
|
+
|
|
19
|
+
export function parseCliArgs(argv: string[]): ParsedArgs {
|
|
20
|
+
const args = stripSubcommands(argv);
|
|
21
|
+
const raw: RawOptions = {
|
|
22
|
+
outputJson: false,
|
|
23
|
+
help: false,
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
27
|
+
const token = args[i];
|
|
28
|
+
|
|
29
|
+
if (HELP_FLAGS.has(token)) {
|
|
30
|
+
raw.help = true;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (token === "--json") {
|
|
35
|
+
raw.outputJson = true;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if (!token.startsWith("--")) {
|
|
40
|
+
throw new CliError(`Unexpected argument: ${token}`, ExitCode.InvalidInput);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const value = args[i + 1];
|
|
44
|
+
if (!value || value.startsWith("--")) {
|
|
45
|
+
throw new CliError(`Missing value for ${token}`, ExitCode.InvalidInput);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
switch (token) {
|
|
49
|
+
case "--from":
|
|
50
|
+
raw.from = value;
|
|
51
|
+
break;
|
|
52
|
+
case "--to":
|
|
53
|
+
raw.to = value;
|
|
54
|
+
break;
|
|
55
|
+
case "--date":
|
|
56
|
+
raw.date = value;
|
|
57
|
+
break;
|
|
58
|
+
case "--airline":
|
|
59
|
+
raw.airline = value;
|
|
60
|
+
break;
|
|
61
|
+
case "--max-stops":
|
|
62
|
+
raw.maxStops = value;
|
|
63
|
+
break;
|
|
64
|
+
case "--max-price":
|
|
65
|
+
raw.maxPrice = value;
|
|
66
|
+
break;
|
|
67
|
+
case "--depart-after":
|
|
68
|
+
raw.departAfter = value;
|
|
69
|
+
break;
|
|
70
|
+
case "--depart-before":
|
|
71
|
+
raw.departBefore = value;
|
|
72
|
+
break;
|
|
73
|
+
default:
|
|
74
|
+
throw new CliError(`Unknown flag: ${token}`, ExitCode.InvalidInput);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
i += 1;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (raw.help) {
|
|
81
|
+
return {
|
|
82
|
+
help: true,
|
|
83
|
+
outputJson: raw.outputJson,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (!raw.from || !raw.to || !raw.date) {
|
|
88
|
+
throw new CliError("Missing required flags: --from, --to, --date", ExitCode.InvalidInput);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const origin = normalizeAirport(raw.from, "origin");
|
|
92
|
+
const destination = normalizeAirport(raw.to, "destination");
|
|
93
|
+
|
|
94
|
+
if (origin === destination) {
|
|
95
|
+
throw new CliError("Origin and destination must be different airports", ExitCode.InvalidInput);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const departureDate = normalizeDate(raw.date);
|
|
99
|
+
const airlineCode = raw.airline ? normalizeAirlineCode(raw.airline) : undefined;
|
|
100
|
+
const maxStops = raw.maxStops ? normalizeMaxStops(raw.maxStops) : undefined;
|
|
101
|
+
const maxPrice = raw.maxPrice ? normalizeMaxPrice(raw.maxPrice) : undefined;
|
|
102
|
+
|
|
103
|
+
const hasDepartAfter = typeof raw.departAfter === "string";
|
|
104
|
+
const hasDepartBefore = typeof raw.departBefore === "string";
|
|
105
|
+
|
|
106
|
+
if (hasDepartAfter !== hasDepartBefore) {
|
|
107
|
+
throw new CliError(
|
|
108
|
+
"Departure window requires both --depart-after and --depart-before",
|
|
109
|
+
ExitCode.InvalidInput,
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
let departureAfterMinutes: number | undefined;
|
|
114
|
+
let departureBeforeMinutes: number | undefined;
|
|
115
|
+
|
|
116
|
+
if (hasDepartAfter && hasDepartBefore) {
|
|
117
|
+
departureAfterMinutes = normalizeTime(raw.departAfter as string, "--depart-after");
|
|
118
|
+
departureBeforeMinutes = normalizeTime(raw.departBefore as string, "--depart-before");
|
|
119
|
+
|
|
120
|
+
if (departureAfterMinutes >= departureBeforeMinutes) {
|
|
121
|
+
throw new CliError(
|
|
122
|
+
"Departure window must be on the same day and --depart-after must be earlier than --depart-before",
|
|
123
|
+
ExitCode.InvalidInput,
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return {
|
|
129
|
+
help: false,
|
|
130
|
+
outputJson: raw.outputJson,
|
|
131
|
+
query: {
|
|
132
|
+
origin,
|
|
133
|
+
destination,
|
|
134
|
+
departureDate,
|
|
135
|
+
airlineCode,
|
|
136
|
+
maxStops,
|
|
137
|
+
maxPrice,
|
|
138
|
+
departureAfterMinutes,
|
|
139
|
+
departureBeforeMinutes,
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function stripSubcommands(argv: string[]): string[] {
|
|
145
|
+
const args = [...argv];
|
|
146
|
+
|
|
147
|
+
if (args[0] === "flights") {
|
|
148
|
+
args.shift();
|
|
149
|
+
if (args[0] === "one-way") {
|
|
150
|
+
args.shift();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return args;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function normalizeAirport(value: string, fieldName: "origin" | "destination"): string {
|
|
158
|
+
const upper = value.trim().toUpperCase();
|
|
159
|
+
if (!/^[A-Z]{3}$/.test(upper)) {
|
|
160
|
+
throw new CliError(
|
|
161
|
+
`Invalid ${fieldName} airport code: ${value}. Expected a 3 letter IATA code.`,
|
|
162
|
+
ExitCode.InvalidInput,
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
return upper;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function normalizeAirlineCode(value: string): string {
|
|
169
|
+
const upper = value.trim().toUpperCase();
|
|
170
|
+
if (!/^[A-Z0-9]{2}$/.test(upper)) {
|
|
171
|
+
throw new CliError(
|
|
172
|
+
`Invalid airline code: ${value}. Expected a 2 character IATA airline code.`,
|
|
173
|
+
ExitCode.InvalidInput,
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
return upper;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function normalizeDate(value: string): string {
|
|
180
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
|
181
|
+
if (!match) {
|
|
182
|
+
throw new CliError("Invalid date. Expected YYYY-MM-DD", ExitCode.InvalidInput);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const year = Number(match[1]);
|
|
186
|
+
const month = Number(match[2]);
|
|
187
|
+
const day = Number(match[3]);
|
|
188
|
+
|
|
189
|
+
const date = new Date(year, month - 1, day);
|
|
190
|
+
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
|
|
191
|
+
throw new CliError("Invalid departure date", ExitCode.InvalidInput);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const today = new Date();
|
|
195
|
+
today.setHours(0, 0, 0, 0);
|
|
196
|
+
date.setHours(0, 0, 0, 0);
|
|
197
|
+
|
|
198
|
+
if (date < today) {
|
|
199
|
+
throw new CliError("Departure date cannot be in the past", ExitCode.InvalidInput);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return value;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function normalizeMaxStops(value: string): number {
|
|
206
|
+
const numeric = Number.parseInt(value, 10);
|
|
207
|
+
if (!Number.isInteger(numeric) || numeric < 0 || numeric > 2) {
|
|
208
|
+
throw new CliError("--max-stops must be an integer between 0 and 2", ExitCode.InvalidInput);
|
|
209
|
+
}
|
|
210
|
+
return numeric;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function normalizeMaxPrice(value: string): number {
|
|
214
|
+
const numeric = Number.parseInt(value, 10);
|
|
215
|
+
if (!Number.isInteger(numeric) || numeric <= 0) {
|
|
216
|
+
throw new CliError("--max-price must be a positive integer", ExitCode.InvalidInput);
|
|
217
|
+
}
|
|
218
|
+
return numeric;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function normalizeTime(value: string, flagName: string): number {
|
|
222
|
+
const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(value);
|
|
223
|
+
if (!match) {
|
|
224
|
+
throw new CliError(`${flagName} must be in HH:MM 24 hour format`, ExitCode.InvalidInput);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
return Number(match[1]) * 60 + Number(match[2]);
|
|
228
|
+
}
|
package/src/serpapi.ts
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { CliError } from "./errors";
|
|
2
|
+
import { ExitCode, FlightOption, FlightQuery } from "./types";
|
|
3
|
+
|
|
4
|
+
interface SerpApiAirport {
|
|
5
|
+
time?: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
interface SerpApiSegment {
|
|
9
|
+
airline?: string;
|
|
10
|
+
duration?: number;
|
|
11
|
+
departure_airport?: SerpApiAirport;
|
|
12
|
+
arrival_airport?: SerpApiAirport;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
interface SerpApiItinerary {
|
|
16
|
+
price?: number;
|
|
17
|
+
total_duration?: number;
|
|
18
|
+
flights?: SerpApiSegment[];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface SerpApiResponse {
|
|
22
|
+
error?: string;
|
|
23
|
+
best_flights?: SerpApiItinerary[];
|
|
24
|
+
other_flights?: SerpApiItinerary[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function searchFlights(
|
|
28
|
+
query: FlightQuery,
|
|
29
|
+
apiKey: string,
|
|
30
|
+
fetchImpl: typeof fetch = fetch,
|
|
31
|
+
): Promise<FlightOption[]> {
|
|
32
|
+
const requestUrl = buildRequestUrl(query, apiKey);
|
|
33
|
+
|
|
34
|
+
let response: Response;
|
|
35
|
+
try {
|
|
36
|
+
response = await fetchImpl(requestUrl, {
|
|
37
|
+
signal: AbortSignal.timeout(15_000),
|
|
38
|
+
});
|
|
39
|
+
} catch (error) {
|
|
40
|
+
if (error instanceof Error && error.name === "TimeoutError") {
|
|
41
|
+
throw new CliError("SerpApi request timed out", ExitCode.ApiFailure);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
throw new CliError("Failed to reach SerpApi", ExitCode.ApiFailure);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (!response.ok) {
|
|
48
|
+
throw new CliError(`SerpApi request failed with status ${response.status}`, ExitCode.ApiFailure);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
let payload: SerpApiResponse;
|
|
52
|
+
try {
|
|
53
|
+
payload = (await response.json()) as SerpApiResponse;
|
|
54
|
+
} catch {
|
|
55
|
+
throw new CliError("SerpApi returned invalid JSON", ExitCode.ApiFailure);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (typeof payload.error === "string" && payload.error.trim() !== "") {
|
|
59
|
+
throw new CliError(`SerpApi error: ${payload.error}`, ExitCode.ApiFailure);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
let flights = shapeSerpApiResponse(payload);
|
|
63
|
+
|
|
64
|
+
if (
|
|
65
|
+
typeof query.departureAfterMinutes === "number" &&
|
|
66
|
+
typeof query.departureBeforeMinutes === "number"
|
|
67
|
+
) {
|
|
68
|
+
flights = filterByDepartureWindow(
|
|
69
|
+
flights,
|
|
70
|
+
query.departureAfterMinutes,
|
|
71
|
+
query.departureBeforeMinutes,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
flights.sort((a, b) => a.price - b.price);
|
|
76
|
+
return flights;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function shapeSerpApiResponse(payload: SerpApiResponse): FlightOption[] {
|
|
80
|
+
const merged = [...(payload.best_flights ?? []), ...(payload.other_flights ?? [])];
|
|
81
|
+
|
|
82
|
+
return merged
|
|
83
|
+
.map((itinerary) => shapeItinerary(itinerary))
|
|
84
|
+
.filter((option): option is FlightOption => option !== null);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function filterByDepartureWindow(
|
|
88
|
+
options: FlightOption[],
|
|
89
|
+
minMinutes: number,
|
|
90
|
+
maxMinutes: number,
|
|
91
|
+
): FlightOption[] {
|
|
92
|
+
return options.filter((option) => {
|
|
93
|
+
const minutes = extractMinutes(option.departureTime);
|
|
94
|
+
if (minutes === null) {
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return minutes >= minMinutes && minutes <= maxMinutes;
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function shapeItinerary(itinerary: SerpApiItinerary): FlightOption | null {
|
|
103
|
+
if (!Number.isFinite(itinerary.price)) {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const segments = Array.isArray(itinerary.flights) ? itinerary.flights : [];
|
|
108
|
+
if (segments.length === 0) {
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const first = segments[0];
|
|
113
|
+
const last = segments[segments.length - 1];
|
|
114
|
+
|
|
115
|
+
const departureTime = first.departure_airport?.time;
|
|
116
|
+
const arrivalTime = last.arrival_airport?.time;
|
|
117
|
+
|
|
118
|
+
if (!departureTime || !arrivalTime) {
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const uniqueAirlines = [...new Set(segments.map((segment) => segment.airline).filter(Boolean))];
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
price: itinerary.price as number,
|
|
126
|
+
airline: uniqueAirlines.length > 0 ? uniqueAirlines.join(", ") : "Unknown",
|
|
127
|
+
departureTime,
|
|
128
|
+
arrivalTime,
|
|
129
|
+
durationMinutes: inferDurationMinutes(itinerary, segments),
|
|
130
|
+
stops: Math.max(0, segments.length - 1),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function inferDurationMinutes(itinerary: SerpApiItinerary, segments: SerpApiSegment[]): number {
|
|
135
|
+
if (Number.isFinite(itinerary.total_duration)) {
|
|
136
|
+
return itinerary.total_duration as number;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const segmentDuration = segments.reduce((total, segment) => {
|
|
140
|
+
if (!Number.isFinite(segment.duration)) {
|
|
141
|
+
return total;
|
|
142
|
+
}
|
|
143
|
+
return total + (segment.duration as number);
|
|
144
|
+
}, 0);
|
|
145
|
+
|
|
146
|
+
return segmentDuration;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function buildRequestUrl(query: FlightQuery, apiKey: string): string {
|
|
150
|
+
const url = new URL("https://serpapi.com/search.json");
|
|
151
|
+
|
|
152
|
+
url.searchParams.set("engine", "google_flights");
|
|
153
|
+
url.searchParams.set("type", "2");
|
|
154
|
+
url.searchParams.set("departure_id", query.origin);
|
|
155
|
+
url.searchParams.set("arrival_id", query.destination);
|
|
156
|
+
url.searchParams.set("outbound_date", query.departureDate);
|
|
157
|
+
url.searchParams.set("sort_by", "2");
|
|
158
|
+
url.searchParams.set("currency", "USD");
|
|
159
|
+
url.searchParams.set("api_key", apiKey);
|
|
160
|
+
|
|
161
|
+
if (query.airlineCode) {
|
|
162
|
+
url.searchParams.set("include_airlines", query.airlineCode);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
if (typeof query.maxStops === "number") {
|
|
166
|
+
url.searchParams.set("stops", toSerpApiStopsFilter(query.maxStops));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (typeof query.maxPrice === "number") {
|
|
170
|
+
url.searchParams.set("max_price", String(query.maxPrice));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (
|
|
174
|
+
typeof query.departureAfterMinutes === "number" &&
|
|
175
|
+
typeof query.departureBeforeMinutes === "number"
|
|
176
|
+
) {
|
|
177
|
+
const minHour = Math.floor(query.departureAfterMinutes / 60);
|
|
178
|
+
const maxHour = Math.max(
|
|
179
|
+
minHour,
|
|
180
|
+
Math.floor(Math.max(0, query.departureBeforeMinutes - 1) / 60),
|
|
181
|
+
);
|
|
182
|
+
|
|
183
|
+
url.searchParams.set("outbound_times", `${minHour},${maxHour}`);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
return url.toString();
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function toSerpApiStopsFilter(maxStops: number): string {
|
|
190
|
+
if (maxStops === 0) {
|
|
191
|
+
return "1";
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (maxStops === 1) {
|
|
195
|
+
return "2";
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
return "3";
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function extractMinutes(value: string): number | null {
|
|
202
|
+
const match = /\b([01]?\d|2[0-3]):([0-5]\d)\b/.exec(value);
|
|
203
|
+
if (!match) {
|
|
204
|
+
return null;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
return Number(match[1]) * 60 + Number(match[2]);
|
|
208
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export const ExitCode = {
|
|
2
|
+
Success: 0,
|
|
3
|
+
InternalError: 1,
|
|
4
|
+
InvalidInput: 2,
|
|
5
|
+
MissingApiKey: 3,
|
|
6
|
+
ApiFailure: 4,
|
|
7
|
+
NoResults: 5,
|
|
8
|
+
} as const;
|
|
9
|
+
|
|
10
|
+
export type ExitCodeValue = (typeof ExitCode)[keyof typeof ExitCode];
|
|
11
|
+
|
|
12
|
+
export interface FlightQuery {
|
|
13
|
+
origin: string;
|
|
14
|
+
destination: string;
|
|
15
|
+
departureDate: string;
|
|
16
|
+
airlineCode?: string;
|
|
17
|
+
maxStops?: number;
|
|
18
|
+
maxPrice?: number;
|
|
19
|
+
departureAfterMinutes?: number;
|
|
20
|
+
departureBeforeMinutes?: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ParsedArgs {
|
|
24
|
+
query?: FlightQuery;
|
|
25
|
+
outputJson: boolean;
|
|
26
|
+
help: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface FlightOption {
|
|
30
|
+
price: number;
|
|
31
|
+
airline: string;
|
|
32
|
+
departureTime: string;
|
|
33
|
+
arrivalTime: string;
|
|
34
|
+
durationMinutes: number;
|
|
35
|
+
stops: number;
|
|
36
|
+
}
|