diff --git a/apps/sim/connectors/website/crawl.ts b/apps/sim/connectors/website/crawl.ts new file mode 100644 index 00000000000..9175f95baa4 --- /dev/null +++ b/apps/sim/connectors/website/crawl.ts @@ -0,0 +1,106 @@ +import { mapSettledWithConcurrency } from '@sim/utils/concurrency' +import { + scopedPage, + type WebsiteDiscovery, + type WebsitePage, + type WebsiteScope, +} from '@/connectors/website/sitemap' + +/** Pages read at once while crawling, bounding the load a sync puts on one site. */ +const CRAWL_CONCURRENCY = 4 + +/** + * What reading one page told the crawl: whether the page belongs in the listing (with the hash of + * its text, the listing's change indicator), and the links it offers. A page the site no longer + * serves, or that is not an HTML page, is not listed. + */ +export interface CrawledPage { + listed: boolean + contentHash?: string + links: string[] + /** Where the page's relative links resolve: its final URL after redirects, or its ``. */ + base?: string + /** The page exists but could not be read, so the links it holds are unknown. */ + unreadable?: boolean +} + +interface CrawlLimits { + maxPages: number + maxDepth: number + /** + * Ends the crawl: reads in flight are cancelled and none start after it, and what the crawl found + * by then is a truncated listing. + */ + signal: AbortSignal + /** Stops the crawl once this many pages are listed, when only some are needed. */ + maxListed?: number +} + +/** + * Discovers a site's pages by following links breadth-first from the configured URL: each + * in-scope page is read once, never deeper than `maxDepth` links from the start, and no more pages + * are queued than `maxPages`. A crawl cut by the page cap or its signal is truncated, and one + * where a page could not be read is incomplete, so neither lets an unlisted page read as removed. + * A configured URL outside the include paths is still read for its links, but not listed: `read` + * receives the scope a page and its redirects must stay within. + */ +export async function crawlSitePages( + scope: WebsiteScope, + read: (page: WebsitePage, signal: AbortSignal, within: WebsiteScope) => Promise, + limits: CrawlLimits +): Promise { + // Relative links resolve against the URL a page is finally served at, as a browser's would. + const seed = (within: WebsiteScope) => + scopedPage(scope.site.baseUrl, within) ?? scopedPage(`${scope.site.baseUrl}/`, within) + const listedStart = seed(scope) + const startScope = listedStart ? scope : { ...scope, include: [] } + const start = listedStart ?? seed(startScope) + if (!start) + throw new Error( + 'The website URL is excluded by the configured paths or disallowed by robots.txt' + ) + const pages: WebsitePage[] = [] + const seen = new Set([start.url]) + let level = [start] + let truncated = false + let incomplete = false + for (let depth = 0; level.length; depth++) { + const next: WebsitePage[] = [] + for (let offset = 0; offset < level.length; offset += CRAWL_CONCURRENCY) { + if (limits.signal.aborted) return { pages, truncated: true, incomplete } + const batch = level.slice(offset, offset + CRAWL_CONCURRENCY) + const results = await mapSettledWithConcurrency(batch, CRAWL_CONCURRENCY, (page) => + read(page, limits.signal, depth === 0 ? startScope : scope) + ) + for (const [index, result] of results.entries()) { + const page = batch[index] + if (!page) continue + if (result.status === 'rejected' || result.value.unreadable) { + incomplete = true + continue + } + if (result.value.listed && (depth > 0 || listedStart)) + pages.push({ ...page, contentHash: result.value.contentHash }) + if (limits.maxListed && pages.length >= limits.maxListed) + return { pages, truncated: true, incomplete } + if (depth >= limits.maxDepth) continue + const before = seen.size + for (const link of result.value.links) { + const found = scopedPage(link, scope, result.value.base ?? page.url) + if (!found || seen.has(found.url)) continue + if (seen.size >= limits.maxPages) { + truncated = true + break + } + seen.add(found.url) + next.push(found) + } + // A start page that leads nowhere is more likely unread (a client-rendered site) than a + // site of one page, so it does not prove the site's other pages are gone. + if (depth === 0 && seen.size === before && !truncated) incomplete = true + } + } + level = next + } + return { pages, truncated, incomplete } +} diff --git a/apps/sim/connectors/website/meta.ts b/apps/sim/connectors/website/meta.ts index 614013f14f1..4749eb71afb 100644 --- a/apps/sim/connectors/website/meta.ts +++ b/apps/sim/connectors/website/meta.ts @@ -7,11 +7,17 @@ export const WEBSITE_DEFAULT_MAX_PAGES = 500 /** Hard ceiling on the configurable `maxPages` value. */ export const WEBSITE_MAX_PAGES_LIMIT = 5000 +/** Links followed from the website URL when crawling, unless `maxDepth` says otherwise. */ +export const WEBSITE_DEFAULT_MAX_DEPTH = 3 + +/** Hard ceiling on the configurable `maxDepth` value. */ +export const WEBSITE_MAX_DEPTH_LIMIT = 10 + /** Client-safe metadata for the website connector: its setup fields, auth and tags. */ export const websiteConnectorMeta: ConnectorMeta = { id: 'website', name: 'Website', - description: 'Sync the pages of a website from its sitemap', + description: 'Sync the pages of a website from its sitemap or by following its links', version: '1.0.0', icon: WebsiteIcon, @@ -36,7 +42,21 @@ export const websiteConnectorMeta: ConnectorMeta = { placeholder: 'https://www.example.com', required: true, description: - 'Pages are discovered from the sitemaps the site lists in robots.txt, or its sitemap.xml. Only pages on this host and under this path are synced, and robots.txt rules are honored.', + 'Only pages on this host and under this path are synced, and robots.txt rules (including Crawl-delay) are honored.', + }, + { + id: 'discovery', + title: 'Page Discovery', + type: 'dropdown', + required: false, + options: [ + { label: 'Sitemap, or follow links when there is none', id: 'auto' }, + { label: 'Sitemap only', id: 'sitemap' }, + { label: 'Follow links from the website URL', id: 'links' }, + ], + placeholder: 'Sitemap, or follow links when there is none', + description: + 'Sitemaps come from robots.txt or sitemap.xml. Following links starts at the website URL and reads each page once, up to the link depth.', }, { id: 'sitemapUrl', @@ -63,6 +83,14 @@ export const websiteConnectorMeta: ConnectorMeta = { required: false, description: 'Comma-separated path prefixes never to sync; * matches any characters.', }, + { + id: 'maxDepth', + title: 'Max Link Depth', + type: 'short-input', + placeholder: `e.g. 2 (default: ${WEBSITE_DEFAULT_MAX_DEPTH}, max: ${WEBSITE_MAX_DEPTH_LIMIT})`, + required: false, + description: 'How many links away from the website URL a crawl reads pages', + }, { id: 'maxPages', title: 'Max Pages', diff --git a/apps/sim/connectors/website/page.test.ts b/apps/sim/connectors/website/page.test.ts index c8d216c8abf..b119135b496 100644 --- a/apps/sim/connectors/website/page.test.ts +++ b/apps/sim/connectors/website/page.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { decodePage, robotsHeaderNoindex } from '@/connectors/website/page' +import { decodePage, extractPageText, robotsDirectives } from '@/connectors/website/page' const html = (head: string, text: string) => `${head}${text}` @@ -44,7 +44,36 @@ describe('website page decoding', () => { describe('X-Robots-Tag', () => { it('honors an unqualified noindex after another crawler’s directive in a repeated header', () => { - expect(robotsHeaderNoindex('otherbot: noindex, noindex')).toBe(true) - expect(robotsHeaderNoindex('otherbot: noindex')).toBe(false) + expect(robotsDirectives('otherbot: noindex, noindex').noindex).toBe(true) + expect(robotsDirectives('otherbot: noindex').noindex).toBe(false) + }) + + it('reads nofollow and none as forbidding links, for this crawler only', () => { + expect(robotsDirectives('simbot: nofollow')).toEqual({ noindex: false, nofollow: true }) + expect(robotsDirectives('none')).toEqual({ noindex: true, nofollow: true }) + expect(robotsDirectives('otherbot: none').nofollow).toBe(false) + expect(robotsDirectives('simbot: noindex nofollow')).toEqual({ noindex: true, nofollow: true }) + }) +}) + +describe('robots meta tag', () => { + const links = (content: string) => + extractPageText(html(``, 'Next')) + it('never reads a valued directive’s value as a directive', () => { + expect(links('max-image-preview:none')).toMatchObject({ noindex: false, links: ['/next'] }) + }) + + it('skips only links whose rel holds the nofollow token', () => { + const page = extractPageText( + html( + '', + 'KeptDropped' + ) + ) + expect(page.links).toEqual(['/kept']) + }) + + it('reads directives separated by spaces as well as commas', () => { + expect(links('noindex nofollow')).toMatchObject({ noindex: true, links: [] }) }) }) diff --git a/apps/sim/connectors/website/page.ts b/apps/sim/connectors/website/page.ts index 60a4624fa99..725baa3b959 100644 --- a/apps/sim/connectors/website/page.ts +++ b/apps/sim/connectors/website/page.ts @@ -16,6 +16,13 @@ export interface WebsitePageText { text: string /** The page asks not to be indexed (`noindex` or `none` in its robots meta tag). */ noindex: boolean + /** + * The links a crawl may follow from the page, as written (relative or absolute): none when the + * page asks not to be followed, and never a link marked `rel="nofollow"`. + */ + links: string[] + /** The page's first ``, as written, which relative links resolve against. */ + baseHref?: string } /** @@ -26,20 +33,40 @@ export interface WebsitePageText { export function extractPageText(html: string): WebsitePageText { assertHtmlStringWithinLimits(html) const $ = cheerio.load(html) - const directives = $(`meta[name="robots" i], meta[name="${WEBSITE_CRAWLER_TOKEN}" i]`) - .map((_, element) => $(element).attr('content') ?? '') - .get() - .join(',') + const directives = robotsDirectives( + $(`meta[name="robots" i], meta[name="${WEBSITE_CRAWLER_TOKEN}" i]`) + .map((_, element) => $(element).attr('content') ?? '') + .get() + .join(',') + ) const title = $('meta[property="og:title"]').attr('content')?.trim() || $('title').first().text().trim() || $('h1').first().text().trim() + // Read before page chrome is dropped: navigation is where most of a site's links live. + const links = directives.nofollow + ? [] + : $('a[href], area[href]') + .filter( + (_, element) => + !($(element).attr('rel') ?? '').toLowerCase().split(/\s+/).includes('nofollow') + ) + .map((_, element) => $(element).attr('href') ?? '') + .get() + .filter(Boolean) $(CHROME_SELECTOR).remove() const region = ['main', 'article'].find((selector) => $(selector).length > 0) ?? 'body' const regionText = loadedHtmlToStructuredText($, region) // A client-rendered page leaves
/
empty; fall back to the body. const text = regionText || region === 'body' ? regionText : loadedHtmlToStructuredText($) - return { title, text, noindex: /\b(noindex|none)\b/i.test(directives) } + const baseHref = $('base[href]').first().attr('href')?.trim() + return { + title, + text, + noindex: directives.noindex, + links, + ...(baseHref ? { baseHref } : {}), + } } const META_TAG = /]*>/gi @@ -105,23 +132,35 @@ const VALUED_DIRECTIVES = new Set([ 'max-video-preview', ]) +/** What a page's robots directives ask of this crawler. */ +export interface RobotsDirectives { + /** `noindex` or `none`: leave the page out of the index. */ + noindex: boolean + /** `nofollow` or `none`: do not follow the page's links. */ + nofollow: boolean +} + /** - * Whether an `X-Robots-Tag` header asks this crawler not to index the page: `noindex` or `none`, - * either unqualified or after this crawler's name (`SimBot: noindex`). Only a directive right - * after another crawler's name is left to that crawler. Repeated headers arrive joined by commas, - * which hides where one ends, so a crawler name never carries over to the directives after it: - * an unqualified `noindex` is never mistaken for another crawler's. + * The directives a robots `` tag's content or an `X-Robots-Tag` header gives this crawler: + * each directive, either unqualified or after this crawler's name + * (`SimBot: noindex`). Only a directive right after another crawler's name is left to that + * crawler, and a valued directive (`max-image-preview: none`) is never read as its value. + * Repeated headers arrive joined by commas, which hides where one ends, so a crawler name never + * carries over to the directives after it: an unqualified `noindex` is never mistaken for another + * crawler's. */ -export function robotsHeaderNoindex(value: string | null): boolean { - if (!value) return false +export function robotsDirectives(value: string | null | undefined): RobotsDirectives { const token = WEBSITE_CRAWLER_TOKEN.toLowerCase() - return value.split(',').some((part) => { - let directive = part.trim().toLowerCase() + const directives = (value ?? '').split(',').flatMap((part) => { + const directive = part.trim().toLowerCase() const named = /^([\w-]+)\s*:\s*(.*)$/.exec(directive) - if (named && !VALUED_DIRECTIVES.has(named[1])) { - if (named[1] !== token) return false - directive = named[2] - } - return directive === 'noindex' || directive === 'none' + // Some pages separate directives with spaces (`noindex nofollow`) rather than commas. + if (!named) return directive.split(/\s+/) + if (VALUED_DIRECTIVES.has(named[1])) return [] + return named[1] === token ? named[2].split(/\s+/) : [] }) + return { + noindex: directives.some((directive) => directive === 'noindex' || directive === 'none'), + nofollow: directives.some((directive) => directive === 'nofollow' || directive === 'none'), + } } diff --git a/apps/sim/connectors/website/robots.test.ts b/apps/sim/connectors/website/robots.test.ts index 7614e81af46..1d599bebb40 100644 --- a/apps/sim/connectors/website/robots.test.ts +++ b/apps/sim/connectors/website/robots.test.ts @@ -77,4 +77,13 @@ describe('robots.txt rules for the website connector', () => { const rules = Array.from({ length: 1001 }, (_, index) => `Disallow: /p${index}`) expect(() => parseRobots(['User-agent: *', ...rules].join('\n'))).toThrow('more than') }) + + it('takes the Crawl-delay of the applied group, capped so a site cannot stall a sync', () => { + expect(parseRobots('User-agent: *\nCrawl-delay: 1.5\nDisallow: /x').crawlDelayMs).toBe(1500) + expect(parseRobots('User-agent: *\nCrawl-delay: 3600').crawlDelayMs).toBe(10_000) + expect( + parseRobots('User-agent: *\nCrawl-delay: 5\n\nUser-agent: SimBot\nDisallow: /x').crawlDelayMs + ).toBe(0) + expect(parseRobots('User-agent: *\nCrawl-delay: soon').crawlDelayMs).toBe(0) + }) }) diff --git a/apps/sim/connectors/website/robots.ts b/apps/sim/connectors/website/robots.ts index ef1ac461f7c..eb691c50f30 100644 --- a/apps/sim/connectors/website/robots.ts +++ b/apps/sim/connectors/website/robots.ts @@ -11,8 +11,20 @@ interface RobotsRule { export interface RobotsPolicy { allows(path: string): boolean sitemaps: string[] + /** The pause the site asks for between requests, in milliseconds, capped; 0 when none. */ + crawlDelayMs: number } +/** One `User-agent` group: the crawlers it names, its rules, and its Crawl-delay in seconds. */ +interface RobotsGroup { + agents: string[] + rules: RobotsRule[] + delaySeconds?: number +} + +/** The longest pause between requests a site's Crawl-delay may impose. */ +const MAX_CRAWL_DELAY_MS = 10_000 + /** * A URL path in one canonical form, so `/%70rivate` and `/private`, or `/café` and `/caf%C3%A9`, * compare equal: escapes of unreserved characters are decoded, other escapes uppercased, and @@ -70,9 +82,9 @@ const MAX_ROBOTS_RULES = 1000 * groups when none does. The longest matching rule decides, and Allow wins a tie. */ export function parseRobots(body: string): RobotsPolicy { - const groups: { agents: string[]; rules: RobotsRule[] }[] = [] + const groups: RobotsGroup[] = [] const sitemaps: string[] = [] - let current: { agents: string[]; rules: RobotsRule[] } | undefined + let current: RobotsGroup | undefined let readingAgents = false for (const raw of body.split(/\r\n|\r|\n/)) { const line = raw.replace(/#.*$/, '').trim() @@ -95,6 +107,11 @@ export function parseRobots(body: string): RobotsPolicy { continue } readingAgents = false + if (current && field === 'crawl-delay') { + const seconds = Number(value) + if (Number.isFinite(seconds) && seconds > 0) current.delaySeconds = seconds + continue + } if (!current || (field !== 'allow' && field !== 'disallow')) continue if (!value) continue current.rules.push({ @@ -106,15 +123,16 @@ export function parseRobots(body: string): RobotsPolicy { } const token = WEBSITE_CRAWLER_TOKEN.toLowerCase() const named = groups.filter((group) => group.agents.includes(token)) - const rules = ( - named.length ? named : groups.filter((group) => group.agents.includes('*')) - ).flatMap((group) => group.rules) + const applied = named.length ? named : groups.filter((group) => group.agents.includes('*')) + const rules = applied.flatMap((group) => group.rules) + const delaySeconds = Math.max(0, ...applied.map((group) => group.delaySeconds ?? 0)) if (rules.length > MAX_ROBOTS_RULES) throw new Error( `robots.txt applies ${rules.length} rules to this crawler, more than the ${MAX_ROBOTS_RULES} it evaluates` ) return { sitemaps, + crawlDelayMs: Math.min(Math.round(delaySeconds * 1000), MAX_CRAWL_DELAY_MS), allows(rawPath) { const path = normalizePath(rawPath) let decision: RobotsRule | undefined @@ -133,4 +151,4 @@ export function parseRobots(body: string): RobotsPolicy { } /** A site without robots.txt allows everything and declares no sitemaps. */ -export const ALLOW_ALL_ROBOTS: RobotsPolicy = { sitemaps: [], allows: () => true } +export const ALLOW_ALL_ROBOTS: RobotsPolicy = { sitemaps: [], crawlDelayMs: 0, allows: () => true } diff --git a/apps/sim/connectors/website/sitemap.ts b/apps/sim/connectors/website/sitemap.ts index 7580b4bc8dc..f8fc715c2ff 100644 --- a/apps/sim/connectors/website/sitemap.ts +++ b/apps/sim/connectors/website/sitemap.ts @@ -47,6 +47,8 @@ export interface WebsitePage { path: string /** The sitemap's ``, as an ISO timestamp, when it gives a valid one. */ lastModified?: string + /** The hash of the text a crawl read from the page, its change indicator when it has no date. */ + contentHash?: string } /** The pages one discovery found, and why they may not be all the site has. */ @@ -166,9 +168,13 @@ function readSitemapEntries( return closed && !implied && isSitemap() ? 'complete' : 'invalid' } -/** The page a sitemap location names, when it is a page within the configured scope. */ -export function scopedPage(location: string, scope: WebsiteScope): WebsitePage | null { - const url = siteUrl(location, `${scope.site.origin}/`, scope.site) +/** The page a location names, resolved against `base`, when it is a page within the scope. */ +export function scopedPage( + location: string, + scope: WebsiteScope, + base = `${scope.site.origin}/` +): WebsitePage | null { + const url = siteUrl(location, base, scope.site) if (!url) return null url.hash = '' const path = normalizePath(url.pathname).replace(/\/+$/, '') || '/' diff --git a/apps/sim/connectors/website/website.integration.ts b/apps/sim/connectors/website/website.integration.ts index f798c255207..705ba73d561 100644 --- a/apps/sim/connectors/website/website.integration.ts +++ b/apps/sim/connectors/website/website.integration.ts @@ -29,6 +29,10 @@ let robotsToWww = false let hung: ServerResponse[] = [] let wwwRequests: IncomingMessage[] = [] let undeclared: 'html' | 'text' | undefined +let crawlDelay = '' +let lockedLink = false +let extraLinks = '' +const pageRequests: { path: string; at: number }[] = [] let faqBody = '

Original answer.

' /** More `` entries than one sitemap may list, all disallowed, between two listed pages. */ @@ -55,7 +59,37 @@ const siteServer = createServer((request, response) => { if (request.headers.host?.startsWith('www.')) wwwRequests.push(request) const path = new URL(request.url ?? '/', site).pathname if (/^\/child-\d+\.xml$/.test(path)) return send(200, 'application/xml', '') + if (!/\.(xml|gz|txt)$/.test(path)) pageRequests.push({ path, at: Date.now() }) switch (path) { + case '/': + return send( + 200, + 'text/html', + `Home

Welcome.

HiddenPlans${lockedLink ? 'Locked' : ''}${extraLinks}
` + ) + case '/guide': + response.writeHead(301, { Location: '/guide/' }).end() + return + case '/guide/': + return send(200, 'text/html', page('Guide', '

Guide home

Intro')) + case '/guide/intro': + return send(200, 'text/html', page('Intro', '

Start here

')) + case '/based': + return send( + 200, + 'text/html', + page('Based', '

Docs index

Setup', '') + ) + case '/docs/setup': + return send(200, 'text/html', page('Setup', '

Install steps

')) + case '/locked': + return send(403, 'text/plain', 'forbidden') + case '/secret': + return send(200, 'text/html', page('Secret', '

Not followed

')) + case '/deep': + return send(200, 'text/html', page('Deep', '

Two links away

More')) + case '/deeper': + return send(200, 'text/html', page('Deeper', '

Too far

')) case '/robots.txt': if (robotsHang) { hung.push(response) @@ -86,7 +120,7 @@ const siteServer = createServer((request, response) => { robotsOversized ? // Lines end in a bare CR, which robots.txt allows, so the cut must find one. `User-agent: *\rDisallow: /private\rSitemap: ${site}/sitemap-index.xml\r${'#'.repeat(600 * 1024)}\rDisallow: /benefits\r` - : `User-agent: *\nDisallow: /private\n${undeclared ? '' : `Sitemap: ${site}/sitemap-index.xml\n`}${staleDeclared ? `Sitemap: ${site}/stale.xml\n` : ''}` + : `User-agent: *\nDisallow: /private\n${crawlDelay ? `Crawl-delay: ${crawlDelay}\n` : ''}${undeclared ? '' : `Sitemap: ${site}/sitemap-index.xml\n`}${staleDeclared ? `Sitemap: ${site}/stale.xml\n` : ''}` ) case '/sitemap.xml': if (undeclared === 'html') return send(200, 'text/html', page('Not found', '

Nothing

')) @@ -154,6 +188,37 @@ const siteServer = createServer((request, response) => { }) .end(page('Tagged', '

Internal

')) return + case '/header-nofollow': + response + .writeHead(200, { 'Content-Type': 'text/html', 'X-Robots-Tag': 'simbot: nofollow' }) + .end(page('Header nofollow', '

Listed

Unfollowed')) + return + case '/image-policy': + return send( + 200, + 'text/html', + page( + 'Image policy', + '

Followed

Followed', + '' + ) + ) + case '/chain': + case '/chain/next': + return send( + 200, + 'text/html', + page( + 'Chain', + `

Draft

Next`, + '' + ) + ) + case '/chain/next/next': + return send(200, 'text/html', page('End', '

Published

')) + case '/stall': + hung.push(response) + return case '/other-bot': response .writeHead(200, { 'Content-Type': 'text/html', 'X-Robots-Tag': 'otherbot: noindex' }) @@ -174,7 +239,11 @@ const siteServer = createServer((request, response) => { return send( 200, 'text/html', - page('Hidden', '

Draft

', '') + page( + 'Hidden', + '

Draft

Deep', + '' + ) ) case '/dense': return send(200, 'text/html', page('Dense', `

${'<'.repeat(1_000_001)}

`)) @@ -233,6 +302,10 @@ beforeEach(() => { hung = [] undeclared = undefined faqBody = '

Original answer.

' + crawlDelay = '' + lockedLink = false + extraLinks = '' + pageRequests.length = 0 }) /** `www.localhost` stands in for a site's www host; it resolves where `localhost` does. */ @@ -535,7 +608,7 @@ describe('website connector over real HTTP', () => { it('skips a guessed sitemap location the site answers with a page, but not one that is invalid', async () => { undeclared = 'html' - await expect(listAll(config())).rejects.toThrow('No pages found') + await expect(listAll({ ...config(), discovery: 'sitemap' })).rejects.toThrow('No pages found') undeclared = 'text' await expect(listAll(config())).rejects.toThrow('not a valid sitemap') }) @@ -549,4 +622,164 @@ describe('website connector over real HTTP', () => { await websiteConnector.validateConfig(`X-Api-Key: ${KEY}`, { ...config(), maxPages: '0.5' }) ).toMatchObject({ valid: false }) }) + + it('crawls links breadth-first within scope, robots.txt, nofollow and depth, reading each page once', async () => { + const context: Record = {} + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '2' }, context) + expect([...urls].sort()).toEqual([ + `${site}/`, + `${site}/benefits`, + `${site}/deep`, + `${site}/faq`, + ]) + expect(foreignRequests).toHaveLength(0) + const paths = pageRequests.map((request) => request.path) + expect(paths).not.toContain('/secret') + expect(paths).not.toContain('/deeper') + expect(paths.filter((path) => path === '/benefits')).toHaveLength(1) + expect(paths).toContain('/hidden') + expect(context.listingCapped).toBeUndefined() + expect(context.reconciliationUnsafe).toBeUndefined() + }) + + it('lists crawled pages under the hash of their text, so unchanged pages are not read again', async () => { + const context: Record = {} + const listed = await websiteConnector.listDocuments( + `X-Api-Key: ${KEY}`, + { ...config(), discovery: 'links', maxDepth: '1' }, + undefined, + context + ) + const stub = listed.documents.find((document) => document.externalId === `${site}/faq`) + const document = await websiteConnector.getDocument( + `X-Api-Key: ${KEY}`, + { ...config(), discovery: 'links' }, + `${site}/faq`, + context + ) + expect(stub?.contentHash).toEqual(expect.any(String)) + expect(stub?.contentHash).toBe(document?.contentHash) + }) + + it('falls back to following links when the site has no sitemap', async () => { + undeclared = 'html' + const urls = await listAll({ ...config(), maxDepth: '1' }) + expect(urls).toContain(`${site}/benefits`) + expect( + await websiteConnector.validateConfig(`X-Api-Key: ${KEY}`, { + ...config(), + discovery: 'links', + }) + ).toEqual({ valid: true }) + }) + + it('marks a crawl cut by the page cap so absent pages are not reconciled away', async () => { + const context: Record = {} + expect(await listAll({ ...config(), discovery: 'links', maxPages: '2' }, context)).toHaveLength( + 2 + ) + expect(context.listingCapped).toBe(true) + }) + + it('keeps the pace robots.txt asks for between page requests', async () => { + crawlDelay = '0.2' + await listAll({ ...config(), discovery: 'links', maxDepth: '1' }) + const times = pageRequests.map((request) => request.at) + expect(times.length).toBeGreaterThanOrEqual(4) + for (let index = 1; index < times.length; index++) + expect((times[index] ?? 0) - (times[index - 1] ?? 0)).toBeGreaterThanOrEqual(150) + }) + + it('fails a crawl whose starting page cannot be read rather than listing an empty site', async () => { + await expect(listAll({ siteUrl: `${site}/gone`, discovery: 'links' })).rejects.toThrow( + 'No pages found' + ) + }) + + it('never lets a crawl that could not read a page reconcile pages away', async () => { + lockedLink = true + const context: Record = {} + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '1' }, context) + expect(urls).toContain(`${site}/benefits`) + expect(urls).not.toContain(`${site}/locked`) + expect(context.reconciliationUnsafe).toBe(true) + }) + + it('resolves a page’s relative links against its ', async () => { + extraLinks = 'Docs' + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '2' }) + expect(urls).toContain(`${site}/docs/setup`) + }) + + it('never lets a page it could not parse hide the pages it links to', async () => { + extraLinks = 'Dense' + const context: Record = {} + await listAll({ ...config(), discovery: 'links', maxDepth: '1' }, context) + expect(context.reconciliationUnsafe).toBe(true) + }) + + it('does not take a start page that links nowhere as proof the rest of the site is gone', async () => { + const context: Record = {} + expect(await listAll({ siteUrl: `${site}/secret`, discovery: 'links' }, context)).toEqual([ + `${site}/secret`, + ]) + expect(context.reconciliationUnsafe).toBe(true) + }) + + it('resolves relative links against the URL a redirect served the page from', async () => { + const urls = await listAll({ siteUrl: `${site}/guide`, discovery: 'links' }) + expect(urls).toContain(`${site}/guide/intro`) + }) + + it('follows no links from a page whose X-Robots-Tag forbids it, but still lists the page', async () => { + extraLinks = 'TaggedImages' + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '2' }) + expect(urls).toContain(`${site}/header-nofollow`) + const paths = pageRequests.map((request) => request.path) + expect(paths).not.toContain('/unfollowed') + expect(paths).toContain('/followed') + }) + + it('reads a start page outside the include paths for its links without listing it', async () => { + const urls = await listAll({ ...config(), discovery: 'links', includePaths: '/benefits' }) + expect(urls).toEqual([`${site}/benefits`]) + }) + + it('lets a start page outside the include paths redirect before its links are read', async () => { + const urls = await listAll({ + siteUrl: `${site}/guide`, + discovery: 'links', + includePaths: '/guide/intro', + }) + expect(urls).toEqual([`${site}/guide/intro`]) + }) + + it('validates a site whose first page with text is several links from the start', async () => { + expect( + await websiteConnector.validateConfig(`X-Api-Key: ${KEY}`, { + siteUrl: `${site}/chain`, + discovery: 'links', + }) + ).toEqual({ valid: true }) + }) + + it('holds link validation to its deadline when a page stalls', async () => { + const timeout = AbortSignal.timeout.bind(AbortSignal) + const spy = vi + .spyOn(AbortSignal, 'timeout') + // 20_000 is VALIDATE_DEADLINE_MS; every other deadline stays real. + .mockImplementation((ms) => timeout(ms === 20_000 ? 300 : ms)) + const started = Date.now() + try { + expect( + await websiteConnector.validateConfig(`X-Api-Key: ${KEY}`, { + siteUrl: `${site}/stall`, + discovery: 'links', + }) + ).toEqual({ valid: false, error: expect.stringContaining('did not answer') }) + } finally { + spy.mockRestore() + } + expect(Date.now() - started).toBeLessThan(5_000) + }) }) diff --git a/apps/sim/connectors/website/website.ts b/apps/sim/connectors/website/website.ts index de9c8d5ed3e..8ef1db00606 100644 --- a/apps/sim/connectors/website/website.ts +++ b/apps/sim/connectors/website/website.ts @@ -12,12 +12,15 @@ import { parseTagDate, sizeLimitSkipReason, } from '@/connectors/utils' +import { type CrawledPage, crawlSitePages } from '@/connectors/website/crawl' import { + WEBSITE_DEFAULT_MAX_DEPTH, WEBSITE_DEFAULT_MAX_PAGES, + WEBSITE_MAX_DEPTH_LIMIT, WEBSITE_MAX_PAGES_LIMIT, websiteConnectorMeta, } from '@/connectors/website/meta' -import { decodePage, extractPageText, robotsHeaderNoindex } from '@/connectors/website/page' +import { decodePage, extractPageText, robotsDirectives } from '@/connectors/website/page' import { ALLOW_ALL_ROBOTS, parseRobots } from '@/connectors/website/robots' import { fetchRobotsText, @@ -46,10 +49,50 @@ const PAGE_MAX_BYTES = 2 * 1024 * 1024 /** Whole-validation deadline: validation runs inside a request, which a slow site must not hold. */ const VALIDATE_DEADLINE_MS = 20_000 -/** What one sync reads once and every page read reuses: the scope and its request headers. */ +/** Wall-clock one crawl may spend discovering pages; what it found by then still syncs. */ +const CRAWL_DEADLINE_MS = 120_000 + +/** + * What one sync reads once and every page read reuses: the scope, its request headers, and the + * pace robots.txt asks page requests to keep. + */ interface WebsiteSession { scope: WebsiteScope headers: Record + pace: (signal?: AbortSignal) => Promise +} + +/** + * Spaces calls at least `delayMs` apart, in the order they ask, however many run at once: the + * Crawl-delay a site requests, applied to every page request of the sync. + */ +function pacer(delayMs: number): (signal?: AbortSignal) => Promise { + let nextSlot = 0 + return async (signal) => { + signal?.throwIfAborted() + if (!delayMs) return + const now = Date.now() + const slot = Math.max(now, nextSlot) + nextSlot = slot + delayMs + if (slot <= now) return + await new Promise((resolve, reject) => { + const abort = () => { + clearTimeout(timer) + reject(signal?.reason) + } + const timer = setTimeout(() => { + signal?.removeEventListener('abort', abort) + resolve() + }, slot - now) + signal?.addEventListener('abort', abort, { once: true }) + }) + } +} + +type DiscoveryMode = 'auto' | 'sitemap' | 'links' + +function discoveryMode(value: unknown): DiscoveryMode { + return value === 'sitemap' || value === 'links' ? value : 'auto' } interface WebsiteListing { @@ -72,6 +115,15 @@ function resolveMaxPages(value: unknown): number { return Math.min(parseMaxPages(value) ?? WEBSITE_DEFAULT_MAX_PAGES, WEBSITE_MAX_PAGES_LIMIT) } +/** How many links from the website URL a crawl reads; `null` when the setting is invalid. */ +function parseMaxDepth(value: unknown): number | null { + if (value === undefined || value === null || value === '') return WEBSITE_DEFAULT_MAX_DEPTH + const parsed = Number(value) + return Number.isSafeInteger(parsed) && parsed > 0 + ? Math.min(parsed, WEBSITE_MAX_DEPTH_LIMIT) + : null +} + /** * A listed page this read deliberately leaves out: recorded as skipped and replacing whatever was * indexed before, so a page that disappears or opts out of indexing stops being searchable. @@ -96,11 +148,13 @@ async function openSession( const site = resolveSite(sourceConfig.siteUrl) const headers = parseRequestHeader(accessToken ?? '') const robots = await fetchRobotsText({ site, headers, retryOptions }) + const policy = robots === null ? ALLOW_ALL_ROBOTS : parseRobots(robots) const session: WebsiteSession = { headers, + pace: pacer(policy.crawlDelayMs), scope: { site, - robots: robots === null ? ALLOW_ALL_ROBOTS : parseRobots(robots), + robots: policy, include: pathPatterns(sourceConfig.includePaths), exclude: pathPatterns(sourceConfig.excludePaths), }, @@ -134,7 +188,9 @@ function pageToStub(page: WebsitePage): ExternalDocument { sourceUrl: page.url, contentHash: page.lastModified ? `website:${page.url}:${page.lastModified}` - : `website:${page.url}`, + : page.contentHash + ? `website:${page.url}:${page.contentHash}` + : `website:${page.url}`, metadata: { section: page.path.split('/').filter(Boolean)[0], lastModified: page.lastModified, @@ -182,7 +238,115 @@ function listingPage(listing: WebsiteListing, cursor?: string): ExternalDocument } } -/** Discovers website pages from sitemaps and reads their text within the configured scope. */ +interface PageRead extends CrawledPage { + document: ExternalDocument +} + +/** + * Reads one page: its document (with text, or recorded as withdrawn or skipped), whether it + * belongs in a crawl's listing, and the links a crawl may follow from it. A redirect may not leave + * the scope, and requests keep the pace the site's robots.txt asks for. `retryOptions.signal`, + * when given, bounds the wait for that pace as well as the request. + */ +async function readPage( + session: WebsiteSession, + page: WebsitePage, + retryOptions?: SecureFetchRetryOptions, + scope = session.scope +): Promise { + const { headers } = session + const unlisted = (document: ExternalDocument): PageRead => ({ + document, + listed: false, + links: [], + }) + const unreadable = (document: ExternalDocument): PageRead => ({ + ...unlisted(document), + unreadable: true, + }) + let resource: Awaited> + let finalUrl = page.url + await session.pace(retryOptions?.signal) + try { + resource = await fetchSiteResource( + { + url: page.url, + site: scope.site, + headers, + accept: 'text/html, application/xhtml+xml;q=0.9', + retryOptions, + }, + PAGE_MAX_BYTES, + (target) => { + if (scopedPage(target.toString(), scope) === null) return false + finalUrl = target.toString() + return true + } + ) + } catch (error) { + if (!isPayloadSizeLimitError(error)) throw error + return unreadable(markSkipped(pageToStub(page), sizeLimitSkipReason(PAGE_MAX_BYTES))) + } + if (!resource) return unlisted(withdrawn(page, 'The page no longer exists on the site')) + const contentType = resource.headers.get('content-type') ?? '' + if (!/html/i.test(contentType)) + return unlisted(withdrawn(page, 'The URL serves a file, not an HTML page')) + const header = robotsDirectives(resource.headers.get('x-robots-tag')) + let extracted: ReturnType + try { + extracted = extractPageText(decodePage(resource.body, contentType)) + } catch (error) { + // Markup past the parser's limits, or nesting deep enough to exhaust the walk's stack. + if (!isHtmlComplexityError(error) && !(error instanceof RangeError)) throw error + return unreadable(withdrawn(page, 'The page is too complex to read')) + } + const { title, text, noindex, baseHref } = extracted + const links = header.nofollow ? [] : extracted.links + let base = finalUrl + try { + if (baseHref) base = new URL(baseHref, finalUrl).toString() + } catch {} + // A page that opts out of indexing is not listed, but a crawl may still follow its links. + if (noindex || header.noindex) + return { + document: withdrawn(page, 'The page asks not to be indexed'), + listed: false, + links, + base, + } + if (!text.trim()) + return { document: withdrawn(page, 'The page has no text content'), listed: false, links, base } + const contentHash = await computeContentHash(text) + const stub = pageToStub(page) + return { + listed: true, + contentHash, + links, + base, + document: { + ...stub, + title: title || stub.title, + content: text, + contentDeferred: false, + contentHash: page.lastModified ? stub.contentHash : `website:${page.url}:${contentHash}`, + }, + } +} + +/** Discovers a site's pages by following its links, each page read once and in scope. */ +function crawlDiscovery(session: WebsiteSession, sourceConfig: Record) { + return crawlSitePages( + session.scope, + (page, signal, within) => readPage(session, page, { signal }, within), + { + maxPages: resolveMaxPages(sourceConfig.maxPages), + maxDepth: parseMaxDepth(sourceConfig.maxDepth) ?? WEBSITE_DEFAULT_MAX_DEPTH, + signal: AbortSignal.timeout(CRAWL_DEADLINE_MS), + } + ) +} + +/** Discovers website pages and reads their text within the configured scope. */ export const websiteConnector: ConnectorConfig = { ...websiteConnectorMeta, @@ -194,14 +358,25 @@ export const websiteConnector: ConnectorConfig = { ): Promise => { let listing = syncContext?.[LISTING_KEY] as WebsiteListing | undefined if (!listing) { - const { scope, headers } = await openSession(accessToken, sourceConfig, syncContext) - const discovery = await discoverSitemapPages(scope, headers, { - configuredSitemap: configuredSitemap(sourceConfig.sitemapUrl, scope), - limit: resolveMaxPages(sourceConfig.maxPages), - }) + const session = await openSession(accessToken, sourceConfig, syncContext) + const { scope, headers } = session + const mode = discoveryMode(sourceConfig.discovery) + let discovery = + mode === 'links' + ? await crawlDiscovery(session, sourceConfig) + : await discoverSitemapPages(scope, headers, { + configuredSitemap: configuredSitemap(sourceConfig.sitemapUrl, scope), + limit: resolveMaxPages(sourceConfig.maxPages), + }) + if (mode === 'auto' && discovery.pages.length === 0 && !discovery.incomplete) + discovery = await crawlDiscovery(session, sourceConfig) // An empty listing would reconcile every stored page away, so fail instead. if (discovery.pages.length === 0) - throw new Error('No pages found in the site’s sitemaps within the configured scope') + throw new Error( + mode === 'sitemap' + ? 'No pages found in the site’s sitemaps within the configured scope' + : 'No pages found in the site’s sitemaps or by following its links within the configured scope' + ) listing = holdListing(discovery, syncContext) } return listingPage(listing, cursor) @@ -213,54 +388,12 @@ export const websiteConnector: ConnectorConfig = { externalId: string, syncContext?: Record ): Promise => { - const { scope, headers } = await openSession(accessToken, sourceConfig, syncContext) + const session = await openSession(accessToken, sourceConfig, syncContext) const listed = (syncContext?.[LISTING_KEY] as WebsiteListing | undefined)?.byUrl.get(externalId) // A page this sync did not list must still pass the current scope before it is read. - const page = listed ?? scopedPage(externalId, scope) + const page = listed ?? scopedPage(externalId, session.scope) if (!page) return null - let resource: Awaited> - try { - resource = await fetchSiteResource( - { - url: page.url, - site: scope.site, - headers, - accept: 'text/html, application/xhtml+xml;q=0.9', - }, - PAGE_MAX_BYTES, - (target) => scopedPage(target.toString(), scope) !== null - ) - } catch (error) { - if (!isPayloadSizeLimitError(error)) throw error - return markSkipped(pageToStub(page), sizeLimitSkipReason(PAGE_MAX_BYTES)) - } - if (!resource) return withdrawn(page, 'The page no longer exists on the site') - const contentType = resource.headers.get('content-type') ?? '' - if (!/html/i.test(contentType)) - return withdrawn(page, 'The URL serves a file, not an HTML page') - if (robotsHeaderNoindex(resource.headers.get('x-robots-tag'))) - return withdrawn(page, 'The page asks not to be indexed') - let extracted: ReturnType - try { - extracted = extractPageText(decodePage(resource.body, contentType)) - } catch (error) { - // Markup past the parser's limits, or nesting deep enough to exhaust the walk's stack. - if (!isHtmlComplexityError(error) && !(error instanceof RangeError)) throw error - return withdrawn(page, 'The page is too complex to read') - } - const { title, text, noindex } = extracted - if (noindex) return withdrawn(page, 'The page asks not to be indexed') - if (!text.trim()) return withdrawn(page, 'The page has no text content') - const stub = pageToStub(page) - return { - ...stub, - title: title || stub.title, - content: text, - contentDeferred: false, - contentHash: page.lastModified - ? stub.contentHash - : `website:${page.url}:${await computeContentHash(text)}`, - } + return (await readPage(session, page)).document }, validateConfig: async ( @@ -269,22 +402,46 @@ export const websiteConnector: ConnectorConfig = { ): Promise<{ valid: boolean; error?: string }> => { if (parseMaxPages(sourceConfig.maxPages) === null) return { valid: false, error: 'Max Pages must be a positive whole number' } + if (parseMaxDepth(sourceConfig.maxDepth) === null) + return { valid: false, error: 'Max Link Depth must be a positive whole number' } const retryOptions = { ...VALIDATE_RETRY_OPTIONS, signal: AbortSignal.timeout(VALIDATE_DEADLINE_MS), } try { - const { scope, headers } = await openSession( - accessToken, - sourceConfig, - undefined, - retryOptions - ) - const { pages } = await discoverSitemapPages(scope, headers, { - configuredSitemap: configuredSitemap(sourceConfig.sitemapUrl, scope), - limit: 1, - retryOptions, - }) + const session = await openSession(accessToken, sourceConfig, undefined, retryOptions) + const { scope, headers } = session + const mode = discoveryMode(sourceConfig.discovery) + const { pages } = + mode === 'links' + ? { pages: [] } + : await discoverSitemapPages(scope, headers, { + configuredSitemap: configuredSitemap(sourceConfig.sitemapUrl, scope), + limit: 1, + retryOptions, + }) + if (pages.length === 0 && mode !== 'sitemap') { + // The crawl reads pages the way a sync does, within the configured limits, and stops at + // the first page it would list. + const crawl = await crawlSitePages( + scope, + (page, _signal, within) => readPage(session, page, retryOptions, within), + { + maxPages: resolveMaxPages(sourceConfig.maxPages), + maxDepth: parseMaxDepth(sourceConfig.maxDepth) ?? WEBSITE_DEFAULT_MAX_DEPTH, + signal: retryOptions.signal, + maxListed: 1, + } + ) + // A crawl the deadline stopped before it found a page says nothing about the site. + if (!crawl.pages.length) retryOptions.signal.throwIfAborted() + return crawl.pages.length + ? { valid: true } + : { + valid: false, + error: `${scope.site.baseUrl} has no sitemap, and following its links found no page with text within the configured paths`, + } + } if (pages.length === 0) return { valid: false,