diff --git a/CHANGELOG.md b/CHANGELOG.md index 106d0ac..e6aa15e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 2.3.0 - 2026-11-05 + +Adds `s1 deepcrawl ` and `deepcrawl()` / `deepcrawlStatus()` SDK helpers for `POST /deepcrawl` and `GET /deepcrawl/status/{taskId}`: crawl a whole site or section in one task and get every page as Markdown. The command starts the task, waits for it (`--timeout`, default 300 s, polling every 2 s), then prints the stats, one line per page, failed URLs and the result URL. Options: `--type sitemap|all`, `-n/--max-pages` (1-1000), repeatable `--include`/`--exclude` path rules (up to 20 each), `--format json|zip` (the CLI defaults to `json`), `-o/--output` (pages JSON or the ZIP), `--no-wait`, `--json`. `s1 deepcrawl status ` checks a task for free. 20 credits per task, any page count. Options after a subcommand now belong to that subcommand, so a global `-V` must come before it. The agent skill routes "crawl this whole site" requests to it. + ## 2.2.0 - 2026-11-03 Adds `s1 maps ""` and a `maps()` SDK helper for `POST /maps`: one Google Maps page of up to 20 places with category, rating, address, phone, website, open state and Maps link. Options: `-n/--max-results`, `--near `, `--zoom`, `-p/--page` (page 2+ needs `--near`), `--country`, `-l/--lang`, `--json`. 3 credits per completed page. The agent skill routes "where is / nearby / list of businesses" requests to it. diff --git a/README.md b/README.md index 8ff86d6..3d8e1df 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,41 @@ Extract content from a URL. s1 crawl https://example.com/article ``` +### deepcrawl + +Crawl a whole site, or one section of it, in a single task and get every page +as Markdown. Each task costs 20 credits, however many pages it crawls. The +command starts the task, waits for it (usually 10-20 seconds for 20 pages, +longer for big sites), then lists each page with its title, URL and length. + +```bash +s1 deepcrawl https://hono.dev/docs/ -n 20 --include /docs --exclude /docs/changelog +s1 deepcrawl https://example.com --type all -o pages.json # save every page's Markdown +s1 deepcrawl https://example.com --format zip -o site.zip # one Markdown file per page +s1 deepcrawl https://example.com --no-wait # print the task id and exit +s1 deepcrawl status # check it later (free) +s1 deepcrawl status -o pages.json --json +``` + +| Option | Description | Default | +|---|---|---| +| `--type ` | `sitemap` reads the site's sitemap.xml; `all` follows the links on the page | `sitemap` | +| `-n, --max-pages ` | Pages to crawl (1-1000), taken after the path rules in discovery order | 1000 | +| `--include ` | Only crawl URL paths matching this rule; repeat for more (up to 20) | | +| `--exclude ` | Skip URL paths matching this rule; repeat for more (up to 20); wins over `--include` | | +| `--format ` | `json` returns the pages inline; `zip` packs them as Markdown files behind a download URL | `json` | +| `--no-wait` | Start the task, print its id and exit | | +| `--timeout ` | How long to wait for the result; the task keeps running after that | 300 | +| `-o, --output ` | Save the result: `{ pages, failed }` as JSON, or the ZIP | | +| `--json` | Output the raw status response | | + +Path rules match the URL path. A rule without `*` is a prefix on segment +boundaries: `/docs` matches `/docs` and `/docs/api`, not `/docsearch`. A rule +with `*` must match the whole path, and `*` also matches `/`, e.g. `/blog/*`. + +`s1 deepcrawl status ` takes `-o` and `--json` too. When a large JSON +result is not returned inline, `-o` downloads it from the result URL. + ### sitemap Get related links from a website. diff --git a/package-lock.json b/package-lock.json index cc60e5f..a7e18f6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "search1api-cli", - "version": "2.2.0", + "version": "2.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "search1api-cli", - "version": "2.2.0", + "version": "2.3.0", "hasInstallScript": true, "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index 7b0f7ae..e4db4d3 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "search1api-cli", - "version": "2.2.0", - "description": "CLI tool for Search1API - web search, maps, news, crawl, sitemap, and trending", + "version": "2.3.0", + "description": "CLI tool for Search1API - web search, maps, news, crawl, deepcrawl, sitemap, and trending", "type": "module", "exports": { ".": { diff --git a/skills/search1api/SKILL.md b/skills/search1api/SKILL.md index cb7271d..7345ac1 100644 --- a/skills/search1api/SKILL.md +++ b/skills/search1api/SKILL.md @@ -1,7 +1,7 @@ --- name: search1api description: > - Live web search, agentic search, Google Maps place search, page retrieval, news, sitemap discovery, trending topics, and turning a URL into a reusable Agent Skill — all through the Search1API CLI (`s1`). Use this skill whenever the user wants to search the web, look something up, research a topic, read or summarize a URL, check current news, find businesses or places on a map, explore a site's links, see trending topics, check API balance, or teach an agent a URL so it can be used later. Trigger on phrases like "search for", "look up", "find out about", "what's happening with", "any news on", "coffee shops near", "restaurants in", "what does this link say", "read this page", "summarize this URL", "trending on GitHub", "learn this URL", "learn this site", "turn these docs into a skill", "记住这个链接", "学会这个文档", or when the user shares a bare URL. + Live web search, agentic search, Google Maps place search, page retrieval, whole-site crawling, news, sitemap discovery, trending topics, and turning a URL into a reusable Agent Skill — all through the Search1API CLI (`s1`). Use this skill whenever the user wants to search the web, look something up, research a topic, read or summarize a URL, pull every page of a site or docs section, check current news, find businesses or places on a map, explore a site's links, see trending topics, check API balance, or teach an agent a URL so it can be used later. Trigger on phrases like "search for", "look up", "find out about", "what's happening with", "any news on", "coffee shops near", "restaurants in", "what does this link say", "read this page", "summarize this URL", "crawl this whole site", "get all the pages under /docs", "trending on GitHub", "learn this URL", "learn this site", "turn these docs into a skill", "记住这个链接", "学会这个文档", or when the user shares a bare URL. --- # Search1API @@ -69,6 +69,7 @@ error. | Wants to search the web | `s1 search ""` | | Asks a question that spans sources, unsure where to look | `s1 ask ""` | | Wants the full page behind a search result | `s1 crawl ` | +| Wants every page of a site or section as Markdown, now | `s1 deepcrawl ` | | Wants news | `s1 news ""` | | Wants businesses or places on a map (where is, nearby, a list of shops) | `s1 maps ""` | | Wants to explore a site's links | `s1 sitemap ` | @@ -82,6 +83,9 @@ These look similar and are not: - "What does this page say?", "summarize this link", "read these docs and answer X" → **`s1 crawl`**. One page, answer now, nothing written to disk. +- "Crawl this whole site", "get every page under /blog", "export these docs as + Markdown" → **`s1 deepcrawl`**. Many pages in one task, returned now or saved + to a file; nothing installed. - "Learn this URL", "make a skill out of these docs", "记住这个文档" → **`s1 learn`**. Produces an installable skill directory the user's agent can load later. - **Scope follows the request.** A single link is one page; a documentation set @@ -184,6 +188,32 @@ s1 crawl Extracts clean content from a URL. Use this whenever the user shares a link. +### deepcrawl + +```bash +s1 deepcrawl [--type sitemap|all] [-n 1-1000] [--include ]... [--exclude ]... [--format json|zip] [-o ] [--timeout ] [--no-wait] [--json] +s1 deepcrawl status [-o ] [--json] +``` + +Crawls many pages of one site in a single task. Costs 20 credits per task +however many pages it crawls, so scope it once instead of re-running: `-n` +caps the pages (default 1000), `--include`/`--exclude` take URL-path rules and +can be repeated (up to 20 each). A rule without `*` is a path prefix on segment +boundaries (`/docs` matches `/docs/api`, not `/docsearch`); with `*` it matches +the whole path (`/blog/*`); exclude wins. `--type all` follows the page's links +when the site has no sitemap. + +It waits for the task (about 10-20 s for 20 pages, longer for big sites) and +prints the stats, one line per page (title, URL, length), failed URLs, and the +result URL. Page Markdown is not printed: save it with `-o pages.json`, which +writes `{ pages: [{ url, title, content }], failed }`, or read it with `--json`. +If the wait times out, the task keeps running — run `s1 deepcrawl status +` (free) instead of starting a new task. A completed task that found +nothing explains why in its message; adjust the path rules or `--type`. + +Use `crawl` for one page and `sitemap` to see a site's URLs before choosing +path rules. + ### sitemap ```bash diff --git a/skills/search1api/reference/examples.md b/skills/search1api/reference/examples.md index d126649..a978ea0 100644 --- a/skills/search1api/reference/examples.md +++ b/skills/search1api/reference/examples.md @@ -112,6 +112,22 @@ s1 search "test" --json s1 balance --json ``` +## Crawling a whole site + +Check which URLs the site lists, then crawl one section in a single task +(20 credits) and save every page's Markdown: + +```bash +s1 sitemap https://hono.dev/docs/ +s1 deepcrawl https://hono.dev/docs/ -n 50 --include /docs/api --exclude /docs/api/presets -o hono-api.json +``` + +If the wait times out, check the same task instead of starting another: + +```bash +s1 deepcrawl status -o hono-api.json +``` + ## Learning a URL into a skill One page, staged but not installed: diff --git a/src/api.ts b/src/api.ts index 3e81c14..8f4cf09 100644 --- a/src/api.ts +++ b/src/api.ts @@ -6,29 +6,41 @@ export interface RequestOptions { signal?: AbortSignal; } -export async function request( +/** Sends an authenticated request and returns the response, whatever its status. */ +export async function send( path: string, - body: unknown, + init: RequestInit, options: RequestOptions = {} -): Promise { +): Promise { const url = `${API_BASE}${path}`; - const init: RequestInit = { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify(body), - signal: options.signal, - }; - const res = options.apiKey - ? await fetch(url, { - ...init, + const withSignal: RequestInit = { ...init, signal: options.signal }; + return options.apiKey + ? fetch(url, { + ...withSignal, headers: { ...Object.fromEntries(new Headers(init.headers).entries()), Authorization: `Bearer ${options.apiKey}`, }, }) - : await fetchWithAuth(url, init); + : fetchWithAuth(url, withSignal); +} + +export async function request( + path: string, + body: unknown, + options: RequestOptions = {} +): Promise { + const res = await send( + path, + { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(body), + }, + options + ); if (!res.ok) { const text = await res.text(); diff --git a/src/commands/deepcrawl.ts b/src/commands/deepcrawl.ts new file mode 100644 index 0000000..f91b85d --- /dev/null +++ b/src/commands/deepcrawl.ts @@ -0,0 +1,211 @@ +import chalk from "chalk"; +import { Command } from "commander"; +import { writeFileSync } from "node:fs"; +import { + deepcrawl, + deepcrawlStatus, + type DeepcrawlFormat, + type DeepcrawlOptions, + type DeepcrawlStatusResponse, + type SitemapType, +} from "../sdk.js"; +import { printDeepcrawlResult, printJson } from "../output.js"; + +// Limits the API enforces; checked here so a bad option costs no credits. +const MAX_PAGES_LIMIT = 1000; +const MAX_PATH_RULES = 20; +const MAX_PATH_RULE_LENGTH = 200; +const TYPES: SitemapType[] = ["sitemap", "all"]; +const FORMATS: DeepcrawlFormat[] = ["json", "zip"]; +const POLL_INTERVAL_MS = 2000; +const FINISHED = new Set(["completed", "failed", "not_found"]); + +function collect(value: string, previous: string[] = []): string[] { + return [...previous, value]; +} + +function parseMaxPages(value: string): number { + const parsed = Number(value); + if (!Number.isInteger(parsed) || parsed < 1 || parsed > MAX_PAGES_LIMIT) { + throw new Error(`--max-pages must be an integer between 1 and ${MAX_PAGES_LIMIT}`); + } + return parsed; +} + +function parsePathRules(rules: string[] | undefined, flag: string): string[] | undefined { + if (!rules?.length) return undefined; + if (rules.length > MAX_PATH_RULES) { + throw new Error(`${flag} accepts at most ${MAX_PATH_RULES} rules`); + } + return rules.map((rule) => { + const trimmed = rule.trim(); + if (!trimmed || rule.length > MAX_PATH_RULE_LENGTH) { + throw new Error(`Each ${flag} rule must be a non-empty path of at most ${MAX_PATH_RULE_LENGTH} characters`); + } + return trimmed; + }); +} + +function parseTimeout(value: string): number { + const parsed = Number(value); + if (!Number.isFinite(parsed) || parsed <= 0) { + throw new Error("--timeout must be a positive number of seconds"); + } + return parsed; +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function download(url: string, file: string): Promise { + const res = await fetch(url); + if (!res.ok) throw new Error(`Download failed (${res.status}) from ${url}`); + writeFileSync(file, Buffer.from(await res.arrayBuffer())); +} + +/** Writes the finished result to `file`; returns what was saved, or undefined if there was nothing. */ +async function saveResult( + status: DeepcrawlStatusResponse, + file: string +): Promise { + if (status.pages) { + const body = { pages: status.pages, failed: status.failed ?? [] }; + writeFileSync(file, `${JSON.stringify(body, null, 2)}\n`); + return `Saved ${status.pages.length} pages to ${file}`; + } + // Results over 5 MB are not inlined; resultUrl holds the same { pages, failed } file. + const url = status.zipUrl ?? status.resultUrl; + if (url) { + await download(url, file); + return `Saved ${status.zipUrl ? "the ZIP" : "the result"} to ${file}`; + } + console.error(chalk.yellow(`Nothing to save to ${file}: the task produced no result.`)); + return undefined; +} + +/** Prints a finished or in-progress status. A failed task exits non-zero. */ +async function report( + status: DeepcrawlStatusResponse, + opts: { json?: boolean; output?: string } +): Promise { + if (status.status === "failed") { + if (opts.json) printJson(status); + throw new Error( + `Deepcrawl task ${status.taskId} failed: ${status.error || status.message || "no reason given"}` + ); + } + + if (status.status !== "completed") { + if (opts.json) { + printJson(status); + } else { + console.log(`Task ${status.taskId} is ${status.status ?? "pending"}.${status.message ? ` ${status.message}` : ""}`); + } + if (opts.output) { + console.error(chalk.yellow(`Not saved to ${opts.output}: the task has not finished.`)); + } + return; + } + + const saved = opts.output ? await saveResult(status, opts.output) : undefined; + if (opts.json) { + printJson(status); + if (saved) console.error(saved); + } else { + printDeepcrawlResult(status, saved); + } +} + +export function registerDeepcrawlCommand(program: Command): void { + const command = program + .command("deepcrawl ") + .description("Crawl a whole site into Markdown pages (20 credits per task, any page count)") + .option("--type ", "sitemap reads sitemap.xml; all follows the links on the page", "sitemap") + .option("-n, --max-pages ", `pages to crawl (1-${MAX_PAGES_LIMIT}, default ${MAX_PAGES_LIMIT})`) + .option( + "--include ", + `only crawl URL paths matching this rule; repeatable, up to ${MAX_PATH_RULES}. ` + + "/docs matches /docs/api, not /docsearch; * matches anything, e.g. /blog/*", + collect + ) + .option("--exclude ", `skip URL paths matching this rule; repeatable, up to ${MAX_PATH_RULES}; wins over --include`, collect) + .option("--format ", "json lists the pages inline; zip packs them as Markdown files", "json") + .option("--no-wait", "start the task, print its id and exit") + .option("--timeout ", "how long to wait for the result", "300") + .option("-o, --output ", "save the result: the pages as JSON (json) or the ZIP (zip)") + .option("--json", "output the raw status JSON") + // With the program's positional options, `status --json` reaches the subcommand. + .enablePositionalOptions() + .helpCommand(false) + .action(async (url: string, opts) => { + if (!/^https?:\/\//i.test(url)) { + throw new Error("The URL must start with http:// or https://"); + } + if (!TYPES.includes(opts.type)) { + throw new Error(`--type must be one of: ${TYPES.join(", ")}`); + } + if (!FORMATS.includes(opts.format)) { + throw new Error(`--format must be one of: ${FORMATS.join(", ")}`); + } + const options: DeepcrawlOptions = { type: opts.type, format: opts.format }; + if (opts.maxPages !== undefined) options.maxPages = parseMaxPages(opts.maxPages); + options.includePaths = parsePathRules(opts.include, "--include"); + options.excludePaths = parsePathRules(opts.exclude, "--exclude"); + const timeoutMs = parseTimeout(opts.timeout) * 1000; + if (!opts.wait && opts.output) { + throw new Error("--output needs the result; drop --no-wait, or save it later with s1 deepcrawl status -o "); + } + + const task = await deepcrawl(url, options); + const later = `s1 deepcrawl status ${task.taskId}`; + + if (!opts.wait) { + if (opts.json) { + printJson(task); + } else { + console.log(`Started deepcrawl task ${task.taskId} (20 credits).`); + console.log(chalk.dim(`Check it with: ${later}`)); + } + return; + } + + const log = (message: string) => { + if (!opts.json) console.error(chalk.dim(message)); + }; + log(`Started deepcrawl task ${task.taskId} (20 credits); waiting up to ${opts.timeout}s.`); + + const deadline = Date.now() + timeoutMs; + let status: DeepcrawlStatusResponse; + let last: string | undefined; + for (;;) { + status = await deepcrawlStatus(task.taskId); + if (status.status && FINISHED.has(status.status)) break; + if (status.status !== last) { + log(`Task is ${status.status ?? "pending"}...`); + last = status.status; + } + if (Date.now() + POLL_INTERVAL_MS > deadline) { + if (opts.json) printJson(status); + console.error( + `Task ${task.taskId} is still ${status.status ?? "pending"} after ${opts.timeout}s. ` + + `It keeps running; check it with: ${later}` + ); + process.exitCode = 1; + return; + } + await sleep(POLL_INTERVAL_MS); + } + + await report(status, opts); + }); + + command + .command("status ") + .description("Check a deepcrawl task and show its result once it has finished (free)") + .option("-o, --output ", "save the result: the pages as JSON (json) or the ZIP (zip)") + .option("--json", "output the raw status JSON") + .action(async (taskId: string, opts) => { + await report(await deepcrawlStatus(taskId), opts); + }); +} diff --git a/src/index.ts b/src/index.ts index fa0b626..0d3aeca 100644 --- a/src/index.ts +++ b/src/index.ts @@ -33,6 +33,7 @@ import { registerNewsCommand } from "./commands/news.js"; import { registerAskCommand } from "./commands/ask.js"; import { registerMapsCommand } from "./commands/maps.js"; import { registerCrawlCommand } from "./commands/crawl.js"; +import { registerDeepcrawlCommand } from "./commands/deepcrawl.js"; import { registerSitemapCommand } from "./commands/sitemap.js"; import { registerLearnCommand } from "./commands/learn.js"; import { registerTrendingCommand } from "./commands/trending.js"; @@ -46,14 +47,18 @@ const program = new Command(); program .name("search1api") - .description("CLI for Search1API - search, ask, maps, news, crawl, sitemap, learn & trending") - .version(pkg.version); + .description("CLI for Search1API - search, ask, maps, news, crawl, deepcrawl, sitemap, learn & trending") + .version(pkg.version) + // Options after a subcommand belong to it, so `s1 deepcrawl status --json` + // reaches `status` rather than `deepcrawl`. + .enablePositionalOptions(); registerSearchCommand(program); registerNewsCommand(program); registerAskCommand(program); registerMapsCommand(program); registerCrawlCommand(program); +registerDeepcrawlCommand(program); registerSitemapCommand(program); registerLearnCommand(program); registerTrendingCommand(program); @@ -74,6 +79,7 @@ if (process.argv.length <= 2) { ${chalk.blue("s1 maps")} ${chalk.dim('"coffee shops"')} Find places on Google Maps ${chalk.blue("s1 news")} ${chalk.dim('"your query"')} Search for news ${chalk.blue("s1 crawl")} ${chalk.dim("")} Extract content from a URL + ${chalk.blue("s1 deepcrawl")} ${chalk.dim("")} Crawl a whole site into Markdown pages ${chalk.blue("s1 learn")} ${chalk.dim("")} Turn a URL into an Agent Skill ${chalk.blue("s1 trending")} ${chalk.dim("")} Trending on GitHub / HackerNews ${chalk.blue("s1 balance")} Check remaining credits diff --git a/src/output.ts b/src/output.ts index a402f6c..32aa9ca 100644 --- a/src/output.ts +++ b/src/output.ts @@ -140,6 +140,58 @@ export function printSitemapLinks(links: string[]): void { console.log(chalk.dim(`\nTotal: ${links.length} links`)); } +interface DeepcrawlResult { + taskId: string; + message?: string; + stats?: { discovered: number; matched: number; skipped: number; crawled: number; failed: number }; + failed?: Array<{ url: string; error: string }>; + zipUrl?: string | null; + resultUrl?: string | null; + pages?: Array<{ url: string; title: string | null; content: string }>; +} + +export function printDeepcrawlResult(result: DeepcrawlResult, savedTo?: string): void { + if (result.message) console.log(result.message); + const { stats } = result; + if (stats) { + console.log( + chalk.dim( + `${stats.discovered} discovered · ${stats.matched} matched · ${stats.skipped} over max-pages · ` + + `${stats.crawled} crawled · ${stats.failed} failed` + ) + ); + } + + const pages = result.pages ?? []; + if (pages.length) console.log(); + for (let i = 0; i < pages.length; i++) { + const page = pages[i]; + const chars = `${page.content.length.toLocaleString("en-US")} chars`; + const title = page.title?.trim(); + console.log( + `${chalk.bold.blue(`${i + 1}.`)} ${title ? `${chalk.bold(title)} ` : ""}${chalk.dim(`${page.url} · ${chars}`)}` + ); + } + + const failed = result.failed ?? []; + if (failed.length) { + console.log(); + console.log(chalk.yellow(`Failed (${failed.length}):`)); + for (const item of failed) console.log(chalk.yellow(` ${item.url} — ${item.error}`)); + } + + if (result.zipUrl || result.resultUrl || savedTo) console.log(); + if (result.zipUrl) console.log(`ZIP: ${result.zipUrl}`); + if (result.resultUrl) console.log(`Result: ${result.resultUrl}`); + if (savedTo) { + console.log(chalk.green(savedTo)); + } else if (pages.length) { + console.log( + chalk.dim(`Page Markdown: s1 deepcrawl status ${result.taskId} -o pages.json (free)`) + ); + } +} + export function printJson(data: unknown): void { console.log(JSON.stringify(data, null, 2)); } diff --git a/src/sdk.ts b/src/sdk.ts index 5ce885d..5e99a05 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -1,4 +1,4 @@ -import { request } from "./api.js"; +import { request, send } from "./api.js"; export type TimeRange = "day" | "week" | "month" | "year"; @@ -180,6 +180,71 @@ export interface MapsResponse { results: MapsPlace[]; } +export type DeepcrawlFormat = "zip" | "json"; + +export interface DeepcrawlOptions extends RequestOptions { + /** `sitemap` (the API default) reads sitemap.xml; `all` follows the links found on the page. */ + type?: SitemapType; + /** Pages to crawl, 1-1000. The API defaults to 1000. */ + maxPages?: number; + /** + * Only crawl URLs whose path matches one of these rules (up to 20). Without + * `*` a rule is a path prefix on segment boundaries (`/docs` matches + * `/docs/api`, not `/docsearch`); with `*` it must match the whole path. + */ + includePaths?: string[]; + /** Skip URLs whose path matches one of these rules (up to 20). Exclusion wins. */ + excludePaths?: string[]; + /** `zip` (the API default) or `json`, which returns the pages in the status response. */ + format?: DeepcrawlFormat; +} + +export interface DeepcrawlTask { + taskId: string; + status: "queued"; +} + +export type DeepcrawlState = + | "queued" + | "waiting" + | "processing" + | "completed" + | "failed" + | "not_found"; + +export interface DeepcrawlStats { + discovered: number; + matched: number; + /** Matched pages left out by max_pages. */ + skipped: number; + crawled: number; + failed: number; +} + +export interface DeepcrawlPage { + url: string; + title: string | null; + /** Page body as Markdown. */ + content: string; +} + +export interface DeepcrawlStatusResponse { + taskId: string; + status?: DeepcrawlState; + message?: string; + error?: string | null; + format?: DeepcrawlFormat; + stats?: DeepcrawlStats; + failed?: Array<{ url: string; error: string }>; + /** format=zip: the Markdown files as one ZIP. */ + zipUrl?: string | null; + /** format=json: the JSON result file, `{ pages, failed }`. */ + resultUrl?: string | null; + /** format=json: the pages inline; omitted when the result is over 5 MB. */ + pages?: DeepcrawlPage[]; + [key: string]: unknown; +} + export interface TrendingOptions extends RequestOptions { maxResults?: number; } @@ -284,6 +349,53 @@ export async function crawlBatch( ); } +/** + * Start a whole-site crawl. Returns a task id right away; poll + * `deepcrawlStatus` until it reports `completed` or `failed`. + * 20 credits per task, however many pages it crawls. + */ +export async function deepcrawl( + url: string, + options: DeepcrawlOptions = {} +): Promise { + const body: Record = { url }; + if (options.type) body.type = options.type; + if (options.maxPages !== undefined) body.max_pages = options.maxPages; + if (options.includePaths?.length) body.include_paths = options.includePaths; + if (options.excludePaths?.length) body.exclude_paths = options.excludePaths; + if (options.format) body.format = options.format; + return request("/deepcrawl", body, options); +} + +/** + * Check a deepcrawl task. Free. A task that failed is returned with + * `status: "failed"` rather than thrown; an unknown task id throws. + */ +export async function deepcrawlStatus( + taskId: string, + options: RequestOptions = {} +): Promise { + const res = await send( + `/deepcrawl/status/${encodeURIComponent(taskId)}`, + { method: "GET" }, + options + ); + const text = await res.text(); + if (res.ok) return JSON.parse(text) as DeepcrawlStatusResponse; + + // A failed task comes back as a 500 that still describes the task. + let body: Partial | undefined; + try { + body = JSON.parse(text); + } catch { + body = undefined; + } + if (body?.taskId && body.status === "failed") { + return body as DeepcrawlStatusResponse; + } + throw new Error(`API error (${res.status}): ${text}`); +} + export async function trending( service: TrendingService, options: TrendingOptions = {} diff --git a/tests/commands.test.mjs b/tests/commands.test.mjs index 41cbe43..dea2c68 100644 --- a/tests/commands.test.mjs +++ b/tests/commands.test.mjs @@ -61,6 +61,25 @@ test("maps rejects a malformed --near before calling the API", () => { assert.match(result.stderr, /--near must be "latitude,longitude"/); }); +test("exposes deepcrawl with its status subcommand", () => { + const help = runCli("--help"); + assert.equal(help.status, 0, help.stderr); + assert.match(help.stdout, /deepcrawl \[options\] /); + + const deepcrawlHelp = runCli("deepcrawl", "--help"); + assert.equal(deepcrawlHelp.status, 0, deepcrawlHelp.stderr); + assert.match(deepcrawlHelp.stdout, /20 credits per\s+task/); + for (const flag of ["--type ", "--max-pages ", "--include ", "--exclude ", + "--format ", "--no-wait", "--timeout ", "--output ", "--json"]) { + assert.ok(deepcrawlHelp.stdout.includes(flag), `missing ${flag}`); + } + assert.match(deepcrawlHelp.stdout, /status \[options\] /); + + const statusHelp = runCli("deepcrawl", "status", "--help"); + assert.equal(statusHelp.status, 0, statusHelp.stderr); + assert.match(statusHelp.stdout, /--output /); +}); + test("points agents at s1 feedback when a command fails", () => { const configDir = mkdtempSync(join(tmpdir(), "s1-config-")); const { SEARCH1API_KEY: _key, ...env } = process.env; diff --git a/tests/deepcrawl.test.mjs b/tests/deepcrawl.test.mjs new file mode 100644 index 0000000..ef8a450 --- /dev/null +++ b/tests/deepcrawl.test.mjs @@ -0,0 +1,286 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { mkdtempSync, readFileSync } from "node:fs"; +import { createServer } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import test from "node:test"; + +const cliPath = fileURLToPath(new URL("../dist/index.js", import.meta.url)); + +const TASK_ID = "0b6e1d2c-task"; +const PAGES = [ + { url: "https://hono.dev/docs/", title: "Hono", content: "# Hono\n\nUltrafast web framework." }, + { url: "https://hono.dev/docs/api/routing", title: "Routing", content: "# Routing\n\napp.get()" }, +]; +const COMPLETED_JSON = { + taskId: TASK_ID, + status: "completed", + message: "Successfully crawled 2 URLs and created JSON.", + format: "json", + stats: { discovered: 120, matched: 40, skipped: 37, crawled: 2, failed: 1 }, + failed: [{ url: "https://hono.dev/docs/broken", error: "404 Not Found" }], + resultUrl: "https://files.example.test/result.json", + pages: PAGES, +}; + +/** + * A stand-in Search1API: POST /deepcrawl starts a task, each status call + * returns the next scripted [httpStatus, body] (or a function of the base URL + * that returns one), and /files/site.zip serves a download. + */ +async function startApi(statuses) { + const calls = []; + const queue = [...statuses]; + let base; + const server = createServer((req, res) => { + let raw = ""; + req.on("data", (chunk) => (raw += chunk)); + req.on("end", () => { + calls.push({ + method: req.method, + url: req.url, + auth: req.headers.authorization, + body: raw ? JSON.parse(raw) : undefined, + }); + const reply = (code, body) => { + res.writeHead(code, { "Content-Type": "application/json" }); + res.end(JSON.stringify(body)); + }; + if (req.method === "POST" && req.url === "/deepcrawl") { + return reply(202, { taskId: TASK_ID, status: "queued" }); + } + if (req.method === "GET" && req.url.startsWith("/deepcrawl/status/")) { + const next = queue.length > 1 ? queue.shift() : queue[0]; + return reply(...(typeof next === "function" ? next(base) : next)); + } + if (req.method === "GET" && req.url === "/files/site.zip") { + res.writeHead(200, { "Content-Type": "application/zip" }); + return res.end(Buffer.from("PK-fake-zip")); + } + reply(404, { error: "Not Found" }); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + base = `http://127.0.0.1:${server.address().port}`; + return { base, calls, close: () => new Promise((resolve) => server.close(resolve)) }; +} + +function runCli(base, ...args) { + return new Promise((resolve) => { + const child = spawn(process.execPath, [cliPath, ...args], { + env: { + ...process.env, + NO_UPDATE_NOTIFIER: "1", + FORCE_COLOR: "0", + SEARCH1API_KEY: "test-key", + SEARCH1API_API_BASE: base, + SEARCH1API_CONFIG_DIR: mkdtempSync(join(tmpdir(), "s1-config-")), + }, + }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (chunk) => (stdout += chunk)); + child.stderr.on("data", (chunk) => (stderr += chunk)); + child.on("close", (status) => resolve({ status, stdout, stderr })); + }); +} + +test("deepcrawl sends the options, waits, and lists the pages", async () => { + const api = await startApi([[200, COMPLETED_JSON]]); + try { + const result = await runCli( + api.base, + "deepcrawl", "https://hono.dev/docs/", + "--type", "all", "-n", "20", + "--include", "/docs", "--include", "/blog/*", "--exclude", "/docs/changelog" + ); + assert.equal(result.status, 0, result.stderr); + + const [start, poll] = api.calls; + assert.equal(start.method, "POST"); + assert.equal(start.auth, "Bearer test-key"); + assert.deepEqual(start.body, { + url: "https://hono.dev/docs/", + type: "all", + max_pages: 20, + include_paths: ["/docs", "/blog/*"], + exclude_paths: ["/docs/changelog"], + format: "json", + }); + assert.equal(poll.method, "GET"); + assert.equal(poll.url, `/deepcrawl/status/${TASK_ID}`); + + assert.match(result.stderr, /Started deepcrawl task 0b6e1d2c-task \(20 credits\)/); + assert.match(result.stdout, /^Successfully crawled 2 URLs and created JSON\./); + assert.match(result.stdout, /120 discovered · 40 matched · 37 over max-pages · 2 crawled · 1 failed/); + assert.match(result.stdout, /1\. Hono https:\/\/hono\.dev\/docs\/ · 32 chars/); + assert.match(result.stdout, /2\. Routing https:\/\/hono\.dev\/docs\/api\/routing/); + assert.match(result.stdout, /https:\/\/hono\.dev\/docs\/broken — 404 Not Found/); + assert.match(result.stdout, /Result: https:\/\/files\.example\.test\/result\.json/); + assert.match(result.stdout, /s1 deepcrawl status 0b6e1d2c-task -o pages\.json/); + } finally { + await api.close(); + } +}); + +test("deepcrawl polls until the task completes and --json prints the status", async () => { + const api = await startApi([ + [200, { taskId: TASK_ID, status: "processing", message: "Workflow is currently running." }], + [200, COMPLETED_JSON], + ]); + try { + const result = await runCli(api.base, "deepcrawl", "https://hono.dev/docs/", "--json"); + assert.equal(result.status, 0, result.stderr); + assert.equal(api.calls.filter((call) => call.method === "GET").length, 2); + assert.deepEqual(JSON.parse(result.stdout), COMPLETED_JSON); + assert.deepEqual(api.calls[0].body, { url: "https://hono.dev/docs/", type: "sitemap", format: "json" }); + } finally { + await api.close(); + } +}); + +test("deepcrawl -o writes the pages and failures as JSON", async () => { + const api = await startApi([[200, COMPLETED_JSON]]); + const file = join(mkdtempSync(join(tmpdir(), "s1-deepcrawl-")), "pages.json"); + try { + const result = await runCli(api.base, "deepcrawl", "https://hono.dev/docs/", "-o", file); + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(JSON.parse(readFileSync(file, "utf8")), { + pages: PAGES, + failed: COMPLETED_JSON.failed, + }); + assert.match(result.stdout, /Saved 2 pages to .*pages\.json/); + } finally { + await api.close(); + } +}); + +test("deepcrawl status -o downloads the ZIP", async () => { + const api = await startApi([ + (base) => [200, { + taskId: TASK_ID, + status: "completed", + message: "Successfully crawled 2 URLs and created ZIP.", + format: "zip", + stats: { discovered: 2, matched: 2, skipped: 0, crawled: 2, failed: 0 }, + failed: [], + zipUrl: `${base}/files/site.zip`, + }], + ]); + const file = join(mkdtempSync(join(tmpdir(), "s1-deepcrawl-")), "site.zip"); + try { + const result = await runCli(api.base, "deepcrawl", "status", TASK_ID, "-o", file); + assert.equal(result.status, 0, result.stderr); + assert.equal(readFileSync(file, "utf8"), "PK-fake-zip"); + assert.match(result.stdout, /ZIP: http:\/\/127\.0\.0\.1:\d+\/files\/site\.zip/); + assert.match(result.stdout, /Saved the ZIP to .*site\.zip/); + assert.equal(api.calls.some((call) => call.method === "POST"), false); + } finally { + await api.close(); + } +}); + +test("deepcrawl status passes --json to the subcommand", async () => { + const processing = { taskId: TASK_ID, status: "processing", message: "Workflow is currently running." }; + const api = await startApi([[200, processing]]); + try { + const json = await runCli(api.base, "deepcrawl", "status", TASK_ID, "--json"); + assert.equal(json.status, 0, json.stderr); + assert.deepEqual(JSON.parse(json.stdout), processing); + + const human = await runCli(api.base, "deepcrawl", "status", TASK_ID); + assert.equal(human.status, 0, human.stderr); + assert.match(human.stdout, /Task 0b6e1d2c-task is processing\. Workflow is currently running\./); + } finally { + await api.close(); + } +}); + +test("deepcrawl --no-wait prints the task id without polling", async () => { + const api = await startApi([]); + try { + const result = await runCli(api.base, "deepcrawl", "https://example.com", "--no-wait"); + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /Started deepcrawl task 0b6e1d2c-task \(20 credits\)\./); + assert.match(result.stdout, /s1 deepcrawl status 0b6e1d2c-task/); + assert.deepEqual(api.calls.map((call) => call.method), ["POST"]); + + const json = await runCli(api.base, "deepcrawl", "https://example.com", "--no-wait", "--json"); + assert.deepEqual(JSON.parse(json.stdout), { taskId: TASK_ID, status: "queued" }); + } finally { + await api.close(); + } +}); + +test("deepcrawl reports a failed task and exits non-zero", async () => { + const api = await startApi([ + [500, { taskId: TASK_ID, status: "failed", message: "Workflow errored.", error: "sitemap fetch timed out" }], + ]); + try { + const result = await runCli(api.base, "deepcrawl", "https://example.com"); + assert.equal(result.status, 1); + assert.match(result.stderr, /Deepcrawl task 0b6e1d2c-task failed: sitemap fetch timed out/); + } finally { + await api.close(); + } +}); + +test("deepcrawl stops waiting at --timeout and says how to check later", async () => { + const api = await startApi([[200, { taskId: TASK_ID, status: "processing" }]]); + try { + const result = await runCli(api.base, "deepcrawl", "https://example.com", "--timeout", "1"); + assert.equal(result.status, 1); + assert.match(result.stderr, /still processing after 1s\. It keeps running; check it with: s1 deepcrawl status 0b6e1d2c-task/); + } finally { + await api.close(); + } +}); + +test("deepcrawl shows a completed task that found nothing", async () => { + const empty = { + taskId: TASK_ID, + status: "completed", + message: "None of the 12 discovered URLs matched the path rules.", + format: "json", + stats: { discovered: 12, matched: 0, skipped: 0, crawled: 0, failed: 0 }, + }; + const api = await startApi([[200, empty]]); + try { + const result = await runCli(api.base, "deepcrawl", "https://example.com", "--include", "/nothing"); + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /None of the 12 discovered URLs matched the path rules\./); + assert.doesNotMatch(result.stdout, /Result:|ZIP:/); + } finally { + await api.close(); + } +}); + +test("deepcrawl rejects bad options before starting a task", async () => { + const api = await startApi([]); + const tooMany = Array.from({ length: 21 }, (_, i) => ["--exclude", `/p${i}`]).flat(); + const cases = [ + [["ftp://example.com"], /must start with http/], + [["https://example.com", "-n", "0"], /--max-pages must be an integer between 1 and 1000/], + [["https://example.com", "-n", "1001"], /--max-pages must be an integer between 1 and 1000/], + [["https://example.com", "-n", "2.5"], /--max-pages must be an integer/], + [["https://example.com", "--type", "links"], /--type must be one of: sitemap, all/], + [["https://example.com", "--format", "csv"], /--format must be one of: json, zip/], + [["https://example.com", ...tooMany], /--exclude accepts at most 20 rules/], + [["https://example.com", "--include", "/" + "a".repeat(200)], /at most 200 characters/], + [["https://example.com", "--include", " "], /non-empty path/], + [["https://example.com", "--timeout", "0"], /--timeout must be a positive number/], + [["https://example.com", "--no-wait", "-o", "x.json"], /--output needs the result/], + ]; + try { + for (const [args, message] of cases) { + const result = await runCli(api.base, "deepcrawl", ...args); + assert.equal(result.status, 1, `expected failure for ${args.join(" ")}`); + assert.match(result.stderr, message); + } + assert.equal(api.calls.length, 0); + } finally { + await api.close(); + } +}); diff --git a/tests/sdk.test.mjs b/tests/sdk.test.mjs index 13b87a9..e400553 100644 --- a/tests/sdk.test.mjs +++ b/tests/sdk.test.mjs @@ -4,15 +4,17 @@ import test from "node:test"; process.env.SEARCH1API_KEY = "test-key"; process.env.SEARCH1API_API_BASE = "https://api.example.test"; -const { ask, crawl, maps, news, search, sitemap, trending } = await import("../dist/sdk.js"); +const { ask, crawl, deepcrawl, deepcrawlStatus, maps, news, search, sitemap, trending } = await import( + "../dist/sdk.js" +); -async function captureRequest(run, response) { +async function captureRequest(run, response, status = 200) { const originalFetch = globalThis.fetch; let captured; globalThis.fetch = async (input, init) => { captured = { input: String(input), init }; return new Response(JSON.stringify(response), { - status: 200, + status, headers: { "Content-Type": "application/json" }, }); }; @@ -157,3 +159,64 @@ test("maps sends only the options that were set to /maps", async () => { const minimal = await captureRequest(() => maps("ramen in Shibuya"), response); assert.deepEqual(JSON.parse(minimal.captured.init.body), { query: "ramen in Shibuya" }); }); + +test("deepcrawl sends only the options that were set to /deepcrawl", async () => { + const response = { taskId: "task-1", status: "queued" }; + const { captured, result } = await captureRequest( + () => + deepcrawl("https://hono.dev/docs/", { + type: "all", + maxPages: 20, + includePaths: ["/docs"], + excludePaths: ["/docs/changelog"], + format: "json", + }), + response, + 202 + ); + assert.deepEqual(result, response); + assert.equal(captured.input, "https://api.example.test/deepcrawl"); + assert.equal(captured.init.method, "POST"); + assert.deepEqual(JSON.parse(captured.init.body), { + url: "https://hono.dev/docs/", + type: "all", + max_pages: 20, + include_paths: ["/docs"], + exclude_paths: ["/docs/changelog"], + format: "json", + }); + + const minimal = await captureRequest( + () => deepcrawl("https://example.com", { includePaths: [] }), + response, + 202 + ); + assert.deepEqual(JSON.parse(minimal.captured.init.body), { url: "https://example.com" }); +}); + +test("deepcrawlStatus GETs the task and returns a failed task instead of throwing", async () => { + const completed = { taskId: "a/b", status: "completed", format: "json", pages: [] }; + const { captured, result } = await captureRequest(() => deepcrawlStatus("a/b"), completed); + assert.deepEqual(result, completed); + assert.equal(captured.input, "https://api.example.test/deepcrawl/status/a%2Fb"); + assert.equal(captured.init.method, "GET"); + assert.equal(captured.init.body, undefined); + assert.equal(new Headers(captured.init.headers).get("Authorization"), "Bearer test-key"); + + const failed = { taskId: "t", status: "failed", message: "Workflow errored.", error: "boom" }; + const failure = await captureRequest(() => deepcrawlStatus("t"), failed, 500); + assert.deepEqual(failure.result, failed); + + await assert.rejects( + captureRequest( + () => deepcrawlStatus("missing"), + { taskId: "missing", status: "not_found", message: "Task not found: missing" }, + 404 + ), + /API error \(404\): .*Task not found: missing/ + ); + await assert.rejects( + captureRequest(() => deepcrawlStatus("t"), { error: "Upstream failed" }, 502), + /API error \(502\)/ + ); +});