|
| 1 | +import { createCommand } from "../core/create-command"; |
| 2 | +import { logger } from "../logger"; |
| 3 | +import { search } from "./client"; |
| 4 | + |
| 5 | +export const webSearchSearchCommand = createCommand({ |
| 6 | + metadata: { |
| 7 | + description: "Run a query against Cloudflare Web Search", |
| 8 | + status: "open beta", |
| 9 | + owner: "Product: Web Search", |
| 10 | + }, |
| 11 | + behaviour: { |
| 12 | + printBanner: (args) => !args.json, |
| 13 | + }, |
| 14 | + args: { |
| 15 | + query: { |
| 16 | + type: "string", |
| 17 | + demandOption: true, |
| 18 | + description: "The search query text.", |
| 19 | + }, |
| 20 | + limit: { |
| 21 | + type: "number", |
| 22 | + description: |
| 23 | + "Maximum number of results to return (defaults to 10, capped at 20).", |
| 24 | + }, |
| 25 | + json: { |
| 26 | + type: "boolean", |
| 27 | + default: false, |
| 28 | + description: "Return output as clean JSON", |
| 29 | + }, |
| 30 | + }, |
| 31 | + positionalArgs: ["query"], |
| 32 | + async handler(args, { config }) { |
| 33 | + const body: { query: string; limit?: number } = { query: args.query }; |
| 34 | + if (args.limit !== undefined) { |
| 35 | + body.limit = args.limit; |
| 36 | + } |
| 37 | + |
| 38 | + const result = await search(config, body); |
| 39 | + |
| 40 | + if (args.json) { |
| 41 | + logger.log(JSON.stringify(result, null, 2)); |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + logger.log( |
| 46 | + `Search query: "${result.metadata.query}" (${result.items.length} results, ${result.metadata.latencyMs}ms, request ${result.metadata.requestId})\n` |
| 47 | + ); |
| 48 | + |
| 49 | + if (result.items.length === 0) { |
| 50 | + logger.log("No results found."); |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + logger.table( |
| 55 | + result.items.map((item, i) => ({ |
| 56 | + "#": String(i + 1), |
| 57 | + title: |
| 58 | + item.title.length > 60 ? item.title.slice(0, 60) + "..." : item.title, |
| 59 | + url: item.url.length > 80 ? item.url.slice(0, 80) + "..." : item.url, |
| 60 | + description: item.description |
| 61 | + ? item.description.length > 80 |
| 62 | + ? item.description.slice(0, 80) + "..." |
| 63 | + : item.description |
| 64 | + : "", |
| 65 | + lastModified: item.lastModifiedDate ?? "", |
| 66 | + })) |
| 67 | + ); |
| 68 | + }, |
| 69 | +}); |
0 commit comments