@aglyn/plugins-ai 1.11.0 → 1.13.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.
Files changed (74) hide show
  1. package/package.json +17 -17
  2. package/src/lib/components/ai-media-create.component.js +1 -1
  3. package/src/lib/components/ai-media-create.component.js.map +1 -1
  4. package/src/lib/components/ai-upsell-dialog.component.js +1 -1
  5. package/src/lib/components/ai-upsell-dialog.component.js.map +1 -1
  6. package/src/lib/jobs/ai-job-import-step.d.ts +1 -1
  7. package/src/lib/jobs/ai-job-import-step.js +37 -8
  8. package/src/lib/jobs/ai-job-import-step.js.map +1 -1
  9. package/src/lib/jobs/ai-job-privacy-step.js +2 -2
  10. package/src/lib/jobs/ai-job-privacy-step.js.map +1 -1
  11. package/src/lib/jobs/ai-site-import-compile.js +27 -37
  12. package/src/lib/jobs/ai-site-import-compile.js.map +1 -1
  13. package/src/lib/jobs/ai-site-import-look.d.ts +19 -4
  14. package/src/lib/jobs/ai-site-import-look.js +162 -46
  15. package/src/lib/jobs/ai-site-import-look.js.map +1 -1
  16. package/src/lib/jobs/ai-theme-brand-inputs.d.ts +12 -0
  17. package/src/lib/jobs/ai-theme-brand-inputs.js +1 -1
  18. package/src/lib/jobs/ai-theme-brand-inputs.js.map +1 -1
  19. package/src/lib/layout-language/ai-layout-compiler.js +7 -1
  20. package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
  21. package/src/lib/model/ai-credit-estimate.d.ts +15 -0
  22. package/src/lib/model/ai-credit-estimate.js +13 -0
  23. package/src/lib/model/ai-credit-estimate.js.map +1 -1
  24. package/src/lib/model/ai-site-import-fidelity.d.ts +46 -3
  25. package/src/lib/model/ai-site-import-fidelity.js +254 -62
  26. package/src/lib/model/ai-site-import-fidelity.js.map +1 -1
  27. package/src/lib/model/ai-site-import-report.d.ts +7 -0
  28. package/src/lib/model/ai-site-import-report.js +17 -5
  29. package/src/lib/model/ai-site-import-report.js.map +1 -1
  30. package/src/lib/model/ai-site-import.d.ts +75 -4
  31. package/src/lib/model/ai-site-import.js +34 -11
  32. package/src/lib/model/ai-site-import.js.map +1 -1
  33. package/src/lib/model/ai-site-look.d.ts +16 -0
  34. package/src/lib/model/ai-site-look.js +76 -14
  35. package/src/lib/model/ai-site-look.js.map +1 -1
  36. package/src/lib/model/ai-upsell-copy.js +1 -1
  37. package/src/lib/model/ai-upsell-copy.js.map +1 -1
  38. package/src/lib/site-import/fixtures/aglyn-com-recordings.d.ts +2 -1
  39. package/src/lib/site-import/fixtures/aglyn-com-recordings.js +3 -2
  40. package/src/lib/site-import/fixtures/aglyn-com-recordings.js.map +1 -1
  41. package/src/lib/site-import/fixtures/site-import-crawl-recordings.d.ts +5 -0
  42. package/src/lib/site-import/fixtures/site-import-crawl-recordings.js +116 -3
  43. package/src/lib/site-import/fixtures/site-import-crawl-recordings.js.map +1 -1
  44. package/src/lib/site-import/fixtures/site-import-fidelity-replay.d.ts +7 -0
  45. package/src/lib/site-import/fixtures/site-import-fidelity-replay.js +15 -0
  46. package/src/lib/site-import/fixtures/site-import-fidelity-replay.js.map +1 -1
  47. package/src/lib/site-import/fixtures/site-layout-recordings.d.ts +32 -0
  48. package/src/lib/site-import/fixtures/site-layout-recordings.js +59 -3
  49. package/src/lib/site-import/fixtures/site-layout-recordings.js.map +1 -1
  50. package/src/lib/site-import/fixtures/site-look-slate.d.ts +2 -1
  51. package/src/lib/site-import/fixtures/site-look-slate.js +2 -1
  52. package/src/lib/site-import/fixtures/site-look-slate.js.map +1 -1
  53. package/src/lib/site-import/site-import-crawl.d.ts +9 -1
  54. package/src/lib/site-import/site-import-crawl.js +128 -23
  55. package/src/lib/site-import/site-import-crawl.js.map +1 -1
  56. package/src/lib/site-import/site-import-css.d.ts +89 -1
  57. package/src/lib/site-import/site-import-css.js +468 -28
  58. package/src/lib/site-import/site-import-css.js.map +1 -1
  59. package/src/lib/site-import/site-import-data-forms.d.ts +32 -0
  60. package/src/lib/site-import/site-import-data-forms.js +531 -0
  61. package/src/lib/site-import/site-import-data-forms.js.map +1 -0
  62. package/src/lib/site-import/site-import-html.d.ts +10 -1
  63. package/src/lib/site-import/site-import-html.js +21 -5
  64. package/src/lib/site-import/site-import-html.js.map +1 -1
  65. package/src/lib/site-import/site-import-layout.d.ts +9 -2
  66. package/src/lib/site-import/site-import-layout.js +383 -62
  67. package/src/lib/site-import/site-import-layout.js.map +1 -1
  68. package/src/lib/site-import/site-import-nav.js +17 -3
  69. package/src/lib/site-import/site-import-nav.js.map +1 -1
  70. package/src/lib/site-import/site-import-page.js +5 -0
  71. package/src/lib/site-import/site-import-page.js.map +1 -1
  72. package/src/lib/site-import/site-import-same-page.d.ts +41 -0
  73. package/src/lib/site-import/site-import-same-page.js +108 -0
  74. package/src/lib/site-import/site-import-same-page.js.map +1 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/site-import/site-import-crawl.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * THE SITE-IMPORT CRAWLER (AGL-3974, parent AGL-3973).\n *\n * Reads a website a workspace has PROVED it owns (domain-ownership.ts in\n * tenant-data-admin; the doors check the proof before calling this) into a\n * typed inventory: each page's title, description, headings and text in\n * order, images and menu links. It writes nothing; the import job decides\n * what becomes a page.\n *\n * Every request goes through `fetchPublicTextDetailed`, the theme job's\n * SSRF-guarded fetch: https on the default port only, public addresses only,\n * the socket pinned to the address checked. On top of that:\n *\n * - **One site.** The site is `https://<domain>` and `https://www.<domain>`,\n * one site to its owner. Every redirect hop and every discovered link must\n * stay on it; a page that redirects anywhere else is refused, not followed.\n * - **AglynBot.** Every request says `AglynBot/1.0 (+<the operator's bot page>)`,\n * and robots.txt is read first and honored for every page: the AglynBot\n * group, else `*`. A robots.txt that answers 404 allows everything; one\n * that cannot be read at all (5xx, no answer) stops the crawl, because\n * \"could not ask\" is not \"allowed\".\n * - **Our own edge.** A site this platform serves gets the edge secret\n * (`site-import-edge.ts`, AGL-4085), which lifts our bot challenge for\n * AglynBot; it is asked per request and per redirect hop, and a request\n * that leaves the site's two origins never carries it.\n * - **Sitemap first.** The sitemaps robots.txt names, else /sitemap.xml (an\n * index's children included), then same-site links found on the pages read,\n * for whatever the sitemap missed.\n * - **Budgets.** Pages (the caller's, from the plan), bytes per page (a page\n * over it is refused, not cut), bytes in total, and wall-clock time. A\n * whole site's worth fits (AGL-4083): aglyn.com's 123 pages average 440 KB,\n * 54 MB in all, so the total is 160 MB; a page is parsed and dropped as it\n * is read, so what is held is its blocks, never its bytes.\n * - **Four at a time.** robots.txt, the sitemaps and the home page are read\n * one after another; the rest four at a time, and the inventory keeps the\n * order they were asked in, which is the sitemap's.\n * - **Nothing vanishes.** An address a stop (the clock, the bytes, the page\n * budget) left unread is listed as `not-reached`, so the inventory's\n * counts add up to the site. A wave's own read leaves its unread pages for\n * its next pass instead.\n * - **No lookalikes.** A domain that wears a brand it is not\n * (`lookalikeBrandForHost`) is refused before any request.\n * - **No sign-in pages.** A page with a password field is refused and\n * reported; forms with payment fields, scripts, iframes and embeds never\n * reach the inventory (site-import-html.ts).\n *=========================================*/\n\nimport { lookalikeBrandForHost } from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport { fenceUntrustedText } from '@aglyn/shared-util-tools/untrusted-text'\nimport {\n AI_THEME_REFERENCE_STYLESHEETS,\n AI_THEME_STYLESHEET_MAX_BYTES,\n fetchPublicTextDetailed,\n type PublicFetchEdge,\n type PublicFetchOptions,\n type PublicFetchResult,\n} from '../jobs/ai-theme-brand-inputs'\nimport type { SiteImportFooter, SiteImportLayout, SiteImportLookFacts, SiteImportNavTree } from '../model/ai-site-import'\nimport {\n extractSiteImportPage,\n readMetaValues,\n type SiteImportBlock,\n type SiteImportBrandMark,\n type SiteImportForm,\n type SiteImportVideo,\n type SiteImportIcon,\n type SiteImportImage,\n type SiteImportNavLink,\n type SiteImportOrganization,\n} from './site-import-html'\nimport {\n AGLYN_BOT_TOKEN,\n parseRobotsTxt,\n parseSitemap,\n robotsAllows,\n robotsRulesFor,\n type RobotsRule,\n} from './site-import-robots'\nimport { NO_SITE_IMPORT_HEADERS, siteImportEdgeHeadersFor, type SiteImportHeadersFor } from './site-import-edge'\nimport { siteImportLayout, siteImportLookOf } from './site-import-layout'\nimport { siteImportFooterColumns, siteImportNavTree } from './site-import-nav'\n\n/**\n * Where the bot's user agent points a site owner who wants to know what it is\n * (AGL-3983): the operator's own page about it. `SITE_IMPORT_BOT_INFO_URL` on\n * a self-hosted deployment, so its crawler never names Aglyn's address; the\n * literal is only that variable's default.\n *\n * Aglyn's is the Bring my site guide, which says what AglynBot reads and how\n * robots.txt keeps it out. There is no page of its own (Zach, 10/20: \"we don't\n * need a bot page at all\"), and the site it reads is the reader's own: an\n * import starts only once its owner has proved the site is theirs.\n */\nexport const AGLYN_BOT_INFO_URL =\n process.env['SITE_IMPORT_BOT_INFO_URL'] ?? 'https://docs.aglyn.com/ai/bring-my-site'\n\n/** What every crawler request says it is. */\nexport const AGLYN_BOT_USER_AGENT = `AglynBot/1.0 (+${AGLYN_BOT_INFO_URL})`\n\nexport const SITE_IMPORT_DEFAULTS = {\n maxPageBytes: 2 * 1024 * 1024,\n /**\n * A whole site's worth (AGL-4083): 54 MB for aglyn.com's 123 pages, with\n * room; 400 pages at its 440 KB average are 176 MB (AGL-4106).\n */\n maxTotalBytes: 320 * 1024 * 1024,\n timeBudgetMs: 60_000,\n /** One request's own clock, inside the whole crawl's. */\n requestTimeoutMs: 8_000,\n robotsMaxBytes: 256 * 1024,\n sitemapMaxBytes: 4 * 1024 * 1024,\n /** Sitemap documents read, an index's children included: an index of six children is seven. */\n maxSitemaps: 24,\n /** URLs a sitemap may contribute to the queue. */\n maxSitemapUrls: 2_000,\n /** Reasons kept in `skipped` before the list stops growing: every address a sitemap may name. */\n maxSkipped: 2_000,\n /** Pages read at once, after robots.txt, the sitemaps and the home page. */\n concurrency: 4,\n} as const\n\n/** Never a page: files a link may point at that are not HTML. */\nconst NON_PAGE_EXTENSION =\n /\\.(?:pdf|jpe?g|png|gif|webp|avif|svg|ico|bmp|tiff?|zip|gz|tgz|rar|7z|mp4|m4v|mov|webm|mp3|wav|ogg|m4a|docx?|xlsx?|pptx?|csv|txt|css|js|mjs|json|xml|rss|atom|woff2?|ttf|otf|eot|exe|dmg|apk)$/i\n\nconst TRACKING_PARAM = /^(?:utm_[a-z]+|fbclid|gclid|msclkid|mc_cid|mc_eid|_ga|ref)$/i\n\n/**\n * Never a page, whatever its extension (AGL-4106): an API's or a CDN's path\n * (aglyn.com's press kit links 136 `/api/media/cdn/…?download=1` files) and\n * any address that asks for a download.\n */\nconst NON_PAGE_PATH = /^\\/(?:api|cdn-cgi|wp-json|_next\\/static|_next\\/image)(?:\\/|$)/i\nconst DOWNLOAD_PARAM = /^(?:download|dl|attachment)$/i\n\nconst DOMAIN_PATTERN = /^(?!-)[a-z0-9-]{1,63}(\\.[a-z0-9-]{1,63})+$/\n\nexport type SiteImportSkipReason =\n /** The page has a password field: a sign-in page, refused outright. */\n | 'login-form'\n /** robots.txt keeps AglynBot off this path. */\n | 'robots'\n /** A redirect left the site. */\n | 'off-origin-redirect'\n /** Over the per-page byte cap. */\n | 'too-large'\n /** Answered with something that is not HTML. */\n | 'not-html'\n /** Answered 4xx or 5xx. */\n | 'http-error'\n /** No answer, a private address, or a refused address. */\n | 'unreachable'\n /** Never asked for: a stop (time, bytes, the page budget) came first (AGL-4083). */\n | 'not-reached'\n\nexport interface SiteImportSkipped {\n url: string\n reason: SiteImportSkipReason\n status?: number\n /** Where an off-origin redirect pointed. */\n location?: string\n /** Whose edge turned an error answer away, when it said (AGL-4083). */\n edge?: PublicFetchEdge\n}\n\nexport interface SiteImportPage {\n /** The address the page was read from, after any same-site redirect. */\n url: string\n path: string\n /** Where the crawler learned of the page. */\n foundBy: 'home' | 'sitemap' | 'link'\n title: string\n description: string\n lang: string | null\n canonical: string | null\n /** The share card (AGL-4083). */\n ogImage: string | null\n /** The site's own name, as its head gives it. */\n siteName: string\n icons: SiteImportIcon[]\n /** The header's link home: the brand's logo and words. */\n brand: SiteImportBrandMark | null\n organization: SiteImportOrganization | null\n blocks: SiteImportBlock[]\n images: SiteImportImage[]\n navLinks: SiteImportNavLink[]\n /** Same-site page addresses this page links to. */\n links: string[]\n forms: { kept: SiteImportForm[]; removed: number }\n /** Its videos (AGL-4140), each once; absent on a page with none. */\n videos?: SiteImportVideo[]\n bytes: number\n /** How the source lays the page out (AGL-4106), on a read asked for it (`layout`): a wave's. */\n layout?: SiteImportLayout | null\n /** The home page's menu, footer and look, as its source builds them (AGL-4106). */\n nav?: SiteImportNavTree | null\n footer?: SiteImportFooter | null\n look?: SiteImportLookFacts | null\n}\n\nexport type SiteImportStop =\n | 'page-budget'\n | 'total-bytes'\n | 'time'\n /** robots.txt could not be read, so nothing was asked of the site. */\n | 'robots-unreachable'\n\nexport interface SiteImportInventory {\n domain: string\n /** The site's origins: the bare name and its `www.` twin. */\n origins: string[]\n /** Set when nothing was fetched at all. */\n refused: 'invalid-domain' | 'lookalike' | null\n pages: SiteImportPage[]\n skipped: SiteImportSkipped[]\n /** Skips past {@link SITE_IMPORT_DEFAULTS.maxSkipped}, counted only. */\n skippedOverflow: number\n robots: { found: boolean; sitemaps: string[] }\n /** Page addresses the sitemaps listed (same-site, before robots and budget). */\n sitemapUrls: number\n stoppedBy: SiteImportStop | null\n bytesRead: number\n startedAt: number\n finishedAt: number\n}\n\nexport interface SiteImportCrawlOptions {\n /** The proved domain; `www.` is folded in. */\n domain: string\n /** The most pages the inventory may hold: the plan's page count. */\n maxPages: number\n maxPageBytes?: number\n maxTotalBytes?: number\n timeBudgetMs?: number\n signal?: AbortSignal\n /**\n * Read the sitemap's shallow addresses before its deep ones (AGL-3976), so a\n * crawl the page budget stops reads a site's main pages before the tail of\n * its blog. A sitemap's own order is kept among addresses of one depth.\n */\n shallowFirst?: boolean\n /**\n * Read exactly these addresses of the site, in order, and nothing else\n * (AGL-3976): an import's wave reads its own pages again when it starts. No\n * sitemap is read and no link is followed; robots.txt is read and honored\n * as for any crawl, and every other rule holds.\n */\n only?: readonly string[]\n /**\n * Read how each page is laid out (AGL-4106): its structure, through its own\n * stylesheets (the first two it links, each asked once a crawl). On by\n * default for a wave's read (`only`), whose pages are built; the home page's\n * menu, footer and look are read on every crawl.\n */\n layout?: boolean\n}\n\nexport interface SiteImportCrawlSeams {\n fetch?: (url: string, options: PublicFetchOptions) => Promise<PublicFetchResult>\n now?: () => number\n /**\n * Request headers for the site being read, asked once per crawl with its\n * domain (AGL-4083, AGL-4085). Absent, the crawl asks the edge\n * (`siteImportEdgeHeadersFor`): Aglyn's edge secret for each of the site's\n * two origins this platform serves, decided origin by origin, and nothing\n * anywhere else. Either way the headers go only to the site's two origins,\n * and the fetch asks again on every redirect hop, so a hop anywhere else\n * carries nothing. Always under the crawler's own `Accept` and `User-Agent`.\n */\n headersFor?: (domain: string) => Promise<Readonly<Record<string, string>>> | Readonly<Record<string, string>>\n}\n\n/**\n * The per-request headers of a crawl of `domain`: the seam's, else the edge's,\n * and none for any address off the site's two origins. Never throws.\n */\nasync function siteRequestHeaders(\n seams: SiteImportCrawlSeams,\n domain: string,\n origins: readonly string[],\n): Promise<SiteImportHeadersFor> {\n let inner: SiteImportHeadersFor = NO_SITE_IMPORT_HEADERS\n try {\n if (seams.headersFor) {\n const headers = await seams.headersFor(domain)\n if (headers && Object.keys(headers).length) inner = () => headers\n } else {\n inner = await siteImportEdgeHeadersFor(origins)\n }\n } catch (error) {\n console.warn('[site-import] the edge headers could not be read; reading without them', { domain, error })\n }\n return (url: URL) => (origins.includes(url.origin) ? inner(url) : {})\n}\n\n/** The site's two origins for a domain. */\nexport function siteImportOrigins(domain: string): string[] {\n const bare = domain.replace(/^www\\./, '')\n return [`https://${bare}`, `https://www.${bare}`]\n}\n\n/** A crawlable page address on the site, normalized for de-duplication; else null. */\nexport function siteImportPageKey(url: URL, origins: readonly string[]): string | null {\n if (url.protocol !== 'https:' || url.username || url.password) return null\n if (url.port && url.port !== '443') return null\n if (!origins.includes(url.origin)) return null\n if (NON_PAGE_EXTENSION.test(url.pathname) || NON_PAGE_PATH.test(url.pathname)) return null\n if ([...url.searchParams.keys()].some((key) => DOWNLOAD_PARAM.test(key))) return null\n const clean = new URL(url.toString())\n clean.hash = ''\n for (const key of [...clean.searchParams.keys()]) {\n if (TRACKING_PARAM.test(key)) clean.searchParams.delete(key)\n }\n clean.search = clean.searchParams.toString() ? `?${clean.searchParams.toString()}` : ''\n return clean.toString()\n}\n\nfunction skipReasonFor(result: PublicFetchResult): SiteImportSkipReason {\n switch (result.refusal) {\n case 'redirect-refused':\n return 'off-origin-redirect'\n case 'content-type':\n return 'not-html'\n case 'too-large':\n return 'too-large'\n case 'http-status':\n return 'http-error'\n default:\n return 'unreachable'\n }\n}\n\n/** Read a proved site into an inventory. Never throws for anything the site does. */\nexport async function crawlSiteForImport(\n options: SiteImportCrawlOptions,\n seams: SiteImportCrawlSeams = {},\n): Promise<SiteImportInventory> {\n const now = seams.now ?? Date.now\n const fetchText = seams.fetch ?? fetchPublicTextDetailed\n const domain = String(options.domain ?? '').trim().toLowerCase().replace(/\\.+$/, '').replace(/^www\\./, '')\n const origins = DOMAIN_PATTERN.test(domain) ? siteImportOrigins(domain) : []\n const startedAt = now()\n const inventory: SiteImportInventory = {\n domain,\n origins,\n refused: null,\n pages: [],\n skipped: [],\n skippedOverflow: 0,\n robots: { found: false, sitemaps: [] },\n sitemapUrls: 0,\n stoppedBy: null,\n bytesRead: 0,\n startedAt,\n finishedAt: startedAt,\n }\n const finish = () => {\n inventory.finishedAt = now()\n return inventory\n }\n if (!origins.length) {\n inventory.refused = 'invalid-domain'\n return finish()\n }\n if (lookalikeBrandForHost(domain)) {\n inventory.refused = 'lookalike'\n return finish()\n }\n\n // Asked once, before anything else, and held to the site's two origins.\n const headersFor = await siteRequestHeaders(seams, domain, origins)\n const maxPages = Math.max(0, Math.floor(options.maxPages))\n const maxPageBytes = options.maxPageBytes ?? SITE_IMPORT_DEFAULTS.maxPageBytes\n const maxTotalBytes = options.maxTotalBytes ?? SITE_IMPORT_DEFAULTS.maxTotalBytes\n const deadlineAt = startedAt + (options.timeBudgetMs ?? SITE_IMPORT_DEFAULTS.timeBudgetMs)\n const controller = new AbortController()\n const onAbort = () => controller.abort()\n options.signal?.addEventListener('abort', onAbort)\n if (options.signal?.aborted) controller.abort()\n const timer = setTimeout(() => controller.abort(), Math.max(0, deadlineAt - startedAt))\n\n const sameSite = (url: URL) => origins.includes(url.origin) && url.protocol === 'https:'\n const remainingBytes = () => maxTotalBytes - inventory.bytesRead\n const outOfTime = () => controller.signal.aborted || now() >= deadlineAt\n const request = (url: string, accept: RegExp, acceptHeader: string, maxBytes: number) =>\n fetchText(url, {\n maxBytes,\n accept,\n acceptHeader,\n userAgent: AGLYN_BOT_USER_AGENT,\n headersFor,\n signal: controller.signal,\n timeoutMs: Math.max(1, Math.min(SITE_IMPORT_DEFAULTS.requestTimeoutMs, deadlineAt - now())),\n redirectAllowed: (_from, to) => sameSite(to),\n refuseOver: true,\n })\n const skip = (entry: SiteImportSkipped) => {\n if (inventory.skipped.length < SITE_IMPORT_DEFAULTS.maxSkipped) inventory.skipped.push(entry)\n else inventory.skippedOverflow += 1\n }\n\n try {\n // robots.txt, before anything else is asked of the site.\n const home = `${origins[0]}/`\n let rules: RobotsRule[] = []\n const robots = await request(\n `${origins[0]}/robots.txt`,\n /text\\/plain|text\\/html|^$/i,\n 'text/plain',\n Math.min(SITE_IMPORT_DEFAULTS.robotsMaxBytes, remainingBytes()),\n )\n if (robots.ok) {\n inventory.bytesRead += robots.bytes\n const parsed = parseRobotsTxt(robots.text)\n rules = robotsRulesFor(parsed, AGLYN_BOT_TOKEN)\n inventory.robots = { found: true, sitemaps: parsed.sitemaps }\n } else if (\n !(robots.refusal === 'http-status' && (robots.status ?? 0) >= 400 && (robots.status ?? 0) < 500)\n ) {\n inventory.stoppedBy = outOfTime() ? 'time' : 'robots-unreachable'\n return finish()\n }\n const allowed = (key: string) => {\n const url = new URL(key)\n return robotsAllows(rules, `${url.pathname}${url.search}`)\n }\n\n // A wave's own pages (AGL-3976): exactly those, after robots.txt.\n const only = options.only\n ? options.only\n .map((raw) => {\n try {\n return siteImportPageKey(new URL(raw), origins)\n } catch {\n return null\n }\n })\n .filter((key): key is string => !!key)\n : null\n\n // Sitemaps: the ones robots.txt names on this site, else /sitemap.xml.\n const sitemapQueue: string[] = []\n for (const raw of inventory.robots.sitemaps) {\n try {\n const url = new URL(raw)\n if (sameSite(url)) sitemapQueue.push(url.toString())\n } catch {\n // A malformed Sitemap line names nothing.\n }\n }\n if (!sitemapQueue.length && !only) sitemapQueue.push(`${origins[0]}/sitemap.xml`)\n if (only) sitemapQueue.length = 0\n const sitemapSeen = new Set<string>()\n const fromSitemap: string[] = []\n let sitemapsRead = 0\n while (sitemapQueue.length && sitemapsRead < SITE_IMPORT_DEFAULTS.maxSitemaps && !outOfTime()) {\n const next = sitemapQueue.shift() as string\n if (sitemapSeen.has(next)) continue\n sitemapSeen.add(next)\n if (/\\.gz$/i.test(new URL(next).pathname)) continue\n if (!allowed(next)) continue\n const room = Math.min(SITE_IMPORT_DEFAULTS.sitemapMaxBytes, remainingBytes())\n if (room <= 0) break\n sitemapsRead += 1\n const sitemap = await request(next, /xml|text\\/plain/i, 'application/xml, text/xml;q=0.9', room)\n if (!sitemap.ok) continue\n inventory.bytesRead += sitemap.bytes\n const entries = parseSitemap(sitemap.text)\n for (const location of entries.locations) {\n let url: URL\n try {\n url = new URL(location)\n } catch {\n continue\n }\n if (entries.index) {\n if (sameSite(url)) sitemapQueue.push(url.toString())\n continue\n }\n const key = siteImportPageKey(url, origins)\n if (key && fromSitemap.length < SITE_IMPORT_DEFAULTS.maxSitemapUrls) fromSitemap.push(key)\n }\n }\n inventory.sitemapUrls = fromSitemap.length\n if (options.shallowFirst) {\n const depth = (key: string) => new URL(key).pathname.split('/').filter(Boolean).length\n const ranked = fromSitemap.map((key, order) => ({ key, order, depth: depth(key) }))\n ranked.sort((a, b) => a.depth - b.depth || a.order - b.order)\n fromSitemap.splice(0, fromSitemap.length, ...ranked.map((entry) => entry.key))\n }\n\n // Pages: home, then the sitemap's, then links the pages themselves name.\n // A wave's read is its own pages alone.\n const queue: { key: string; foundBy: SiteImportPage['foundBy'] }[] = only\n ? only.map((key) => ({ key, foundBy: (new URL(key).pathname === '/' ? 'home' : 'link') as SiteImportPage['foundBy'] }))\n : [{ key: home, foundBy: 'home' }]\n const queued = new Set<string>(only ?? [home])\n for (const key of fromSitemap) {\n if (queued.has(key)) continue\n queued.add(key)\n queue.push({ key, foundBy: 'sitemap' })\n }\n const read = new Set<string>()\n // The site's two names are one site: once the home page says which one\n // it answers on, every address is read on that one, so /about is not\n // read twice as example.com/about and www.example.com/about.\n // A wave's read starts on the name its pages were read on the first time.\n let preferred = only?.length ? new URL(only[0]).origin : origins[0]\n const canon = (raw: string) => {\n const url = new URL(raw)\n return origins.includes(url.origin) && url.origin !== preferred\n ? `${preferred}${url.pathname}${url.search}`\n : raw\n }\n const maxAttempts = maxPages * 3 + 10\n let attempts = 0\n type Asked = { next: (typeof queue)[number]; key: string; cap: number; page: PublicFetchResult }\n /** The pages asked for and not yet taken in, in the order they were asked. */\n const window: Array<Promise<Asked>> = []\n /** The bytes the asked pages may still read: what is left is shared, never promised twice. */\n let reserved = 0\n let stop: SiteImportStop | null = null\n /** Asked for and never read, because a stop came first: listed as not reached. */\n const cutOff: string[] = []\n /** Home alone first, so its answer settles which of the site's two names the rest are read on. */\n let homeIn = !!only\n /** Why no more may be asked now: a stop, `wait` for an asked page to come in first, or nothing. */\n const held = (): SiteImportStop | 'wait' | null => {\n if (inventory.pages.length >= maxPages) return 'page-budget'\n if (outOfTime()) return 'time'\n if (remainingBytes() <= 0) return 'total-bytes'\n if (attempts >= maxAttempts) return 'page-budget'\n if (inventory.pages.length + window.length >= maxPages) return 'wait'\n if (remainingBytes() - reserved <= 0) return 'wait'\n return null\n }\n const readLayout = options.layout ?? !!only\n /** Linked stylesheets, each asked once a crawl. */\n const sheets = new Map<string, Promise<string | null>>()\n const stylesheet = (url: string): Promise<string | null> => {\n const held = sheets.get(url)\n if (held) return held\n const room = Math.min(AI_THEME_STYLESHEET_MAX_BYTES, remainingBytes() - reserved)\n const asked: Promise<string | null> =\n room <= 0 || outOfTime()\n ? Promise.resolve(null)\n : request(url, /text\\/css|text\\/plain/i, 'text/css,*/*;q=0.1', room).then(\n (answer) => {\n if (!answer.ok) return null\n inventory.bytesRead += answer.bytes\n return answer.text\n },\n () => null,\n )\n sheets.set(url, asked)\n return asked\n }\n /** Takes one asked page in: the inventory's next page, a skip, or the reason the read must stop. */\n const takeIn = async ({ next, key, cap, page }: Asked): Promise<SiteImportStop | null> => {\n const foundBy = next.foundBy\n if (foundBy === 'home') homeIn = true\n if (!page.ok) {\n if (page.refusal === 'too-large' && cap < maxPageBytes) {\n cutOff.push(key)\n return 'total-bytes'\n }\n if (page.refusal === 'network' && outOfTime()) {\n cutOff.push(key)\n return 'time'\n }\n // A file is not a page: it takes nothing from the page budget's attempts (AGL-4106).\n if (page.refusal === 'content-type') attempts = Math.max(0, attempts - 1)\n skip({\n url: key,\n reason: skipReasonFor(page),\n ...(page.status ? { status: page.status } : {}),\n ...(page.location ? { location: page.location } : {}),\n ...(page.edge ? { edge: page.edge } : {}),\n })\n return null\n }\n inventory.bytesRead += page.bytes\n if (foundBy === 'home') preferred = new URL(page.url).origin\n const finalKey = canon(siteImportPageKey(new URL(page.url), origins) ?? page.url)\n if (finalKey !== key) {\n if (read.has(finalKey)) return null\n read.add(finalKey)\n if (!allowed(finalKey)) {\n skip({ url: finalKey, reason: 'robots' })\n return null\n }\n }\n const isHome = foundBy === 'home'\n const structured = readLayout || isHome\n const extract = extractSiteImportPage(page.text, page.url, sameSite, { structure: structured })\n if (extract.loginForm) {\n skip({ url: finalKey, reason: 'login-form' })\n return null\n }\n const links: string[] = []\n for (const link of extract.links) {\n const linkKey = siteImportPageKey(new URL(link), origins)\n if (!linkKey) continue\n links.push(linkKey)\n if (!only && !queued.has(linkKey)) {\n queued.add(linkKey)\n queue.push({ key: linkKey, foundBy: 'link' })\n }\n }\n // How the page is built (AGL-4106), through its own stylesheets.\n let built: Pick<SiteImportPage, 'layout' | 'nav' | 'footer' | 'look'> = {}\n if (extract.structure) {\n const linked = await Promise.all(extract.structure.stylesheets.filter((url) => !/fonts\\.googleapis\\.com/i.test(url)).slice(0, AI_THEME_REFERENCE_STYLESHEETS).map(stylesheet))\n const css = linked.filter((text): text is string => typeof text === 'string')\n const source = { blocks: extract.blocks, organization: extract.organization, structure: extract.structure, ...(extract.videos ? { videos: extract.videos } : {}) }\n try {\n built = {\n ...(readLayout ? { layout: siteImportLayout(source, css) } : {}),\n ...(isHome ? { nav: siteImportNavTree(source, css), footer: siteImportFooterColumns(source, css), look: siteImportLookOf(source, css) } : {}),\n }\n } catch (error) {\n // A page the reader cannot lay out is still its words.\n console.warn('[site-import] the layout could not be read', { url: page.url, error })\n }\n }\n inventory.pages.push({\n ...built,\n url: finalKey,\n path: new URL(finalKey).pathname,\n foundBy,\n title: extract.title,\n description: extract.description,\n lang: extract.lang,\n canonical: extract.canonical,\n ogImage: extract.ogImage,\n siteName: extract.siteName,\n icons: extract.icons,\n brand: extract.brand,\n organization: extract.organization,\n blocks: extract.blocks,\n images: extract.images,\n navLinks: extract.navLinks,\n links: [...new Set(links.map(canon))],\n forms: extract.forms,\n ...(extract.videos ? { videos: extract.videos } : {}),\n bytes: page.bytes,\n })\n return null\n }\n for (;;) {\n const width = homeIn ? SITE_IMPORT_DEFAULTS.concurrency : 1\n while (!stop && queue.length && window.length < width) {\n const why = held()\n if (why === 'wait') break\n if (why) {\n stop = why\n break\n }\n const next = queue.shift() as (typeof queue)[number]\n const key = canon(next.key)\n if (read.has(key)) continue\n if (!allowed(key)) {\n skip({ url: key, reason: 'robots' })\n if (next.foundBy === 'home') homeIn = true\n continue\n }\n attempts += 1\n read.add(key)\n const cap = Math.min(maxPageBytes, remainingBytes() - reserved)\n reserved += cap\n window.push(\n request(key, /text\\/html|application\\/xhtml\\+xml/i, 'text/html, application/xhtml+xml;q=0.9', cap).then((page) => ({ next, key, cap, page })),\n )\n }\n if (!window.length) break\n const asked = await (window.shift() as Promise<Asked>)\n reserved -= asked.cap\n stop = (await takeIn(asked)) ?? stop\n }\n inventory.stoppedBy = stop\n // Whatever a stop left unread is said, never dropped; a wave's own read\n // leaves its unread pages for its next pass instead.\n if (stop && !only) {\n const unread = [...cutOff]\n for (const next of queue) {\n const key = canon(next.key)\n if (!read.has(key) && !unread.includes(key)) unread.push(key)\n }\n for (const url of unread) skip({ url, reason: 'not-reached' })\n }\n return finish()\n } finally {\n clearTimeout(timer)\n options.signal?.removeEventListener('abort', onAbort)\n }\n}\n\n/**\n * The home page's `aglyn-site-verification` values, for the meta-tag proof:\n * the same fetch, user agent and same-site redirects as the crawl, but no\n * robots.txt, because the person asked for this one page to be read.\n * `answered: false` when the page could not be read at all.\n */\nexport async function readSiteVerificationMeta(\n domain: string,\n metaName: string,\n seams: SiteImportCrawlSeams = {},\n): Promise<{ answered: boolean; values: string[]; url?: string }> {\n const fetchText = seams.fetch ?? fetchPublicTextDetailed\n const bare = String(domain ?? '').trim().toLowerCase().replace(/^www\\./, '')\n if (!DOMAIN_PATTERN.test(bare) || lookalikeBrandForHost(bare)) return { answered: false, values: [] }\n const origins = siteImportOrigins(bare)\n const result = await fetchText(`${origins[0]}/`, {\n maxBytes: SITE_IMPORT_DEFAULTS.maxPageBytes,\n accept: /text\\/html|application\\/xhtml\\+xml/i,\n acceptHeader: 'text/html, application/xhtml+xml;q=0.9',\n userAgent: AGLYN_BOT_USER_AGENT,\n headersFor: await siteRequestHeaders(seams, bare, origins),\n timeoutMs: SITE_IMPORT_DEFAULTS.requestTimeoutMs,\n redirectAllowed: (_from, to) => to.protocol === 'https:' && origins.includes(to.origin),\n })\n if (!result.ok) {\n // An answer that is not the page (a 404, a redirect off the site) is\n // still an answer: the tag is not where it must be.\n const answered = result.refusal === 'http-status' || result.refusal === 'redirect-refused' || result.refusal === 'content-type'\n return { answered, values: [], url: result.url }\n }\n const head = result.text.split(/<body\\b/i)[0] ?? ''\n return { answered: true, values: readMetaValues(head, metaName), url: result.url }\n}\n\n/**\n * One page as text for a prompt: its title, description and blocks in order,\n * fenced as untrusted data. The importer's prompt carries `UNTRUSTED_TEXT_RULE`.\n */\nexport function siteImportPagePromptText(page: SiteImportPage, maxChars = 12_000): string {\n const lines: string[] = []\n if (page.title) lines.push(`Title: ${page.title}`)\n if (page.description) lines.push(`Description: ${page.description}`)\n for (const block of page.blocks) {\n if (block.kind === 'heading') lines.push(`${'#'.repeat(block.level)} ${block.text}`)\n else if (block.kind === 'image') lines.push(`[image: ${block.alt || 'no description'}]`)\n else if (block.kind === 'list-item') lines.push(`- ${block.text}`)\n else if (block.kind === 'quote') lines.push(`> ${block.text}`)\n else if (block.kind === 'link') {\n // A link inside a sentence is in its block's words already.\n if (!block.inline) lines.push(block.text)\n } else lines.push(block.text)\n }\n return fenceUntrustedText(`Page ${page.path} of the site being imported`, lines.join('\\n'), { maxChars })\n}\n"],"names":["process","lookalikeBrandForHost","fenceUntrustedText","AI_THEME_REFERENCE_STYLESHEETS","AI_THEME_STYLESHEET_MAX_BYTES","fetchPublicTextDetailed","extractSiteImportPage","readMetaValues","AGLYN_BOT_TOKEN","parseRobotsTxt","parseSitemap","robotsAllows","robotsRulesFor","NO_SITE_IMPORT_HEADERS","siteImportEdgeHeadersFor","siteImportLayout","siteImportLookOf","siteImportFooterColumns","siteImportNavTree","AGLYN_BOT_INFO_URL","env","AGLYN_BOT_USER_AGENT","SITE_IMPORT_DEFAULTS","maxPageBytes","maxTotalBytes","timeBudgetMs","requestTimeoutMs","robotsMaxBytes","sitemapMaxBytes","maxSitemaps","maxSitemapUrls","maxSkipped","concurrency","NON_PAGE_EXTENSION","TRACKING_PARAM","NON_PAGE_PATH","DOWNLOAD_PARAM","DOMAIN_PATTERN","siteRequestHeaders","seams","domain","origins","inner","headersFor","headers","Object","keys","length","error","console","warn","url","includes","origin","siteImportOrigins","bare","replace","siteImportPageKey","protocol","username","password","port","test","pathname","searchParams","some","key","clean","URL","toString","hash","delete","search","skipReasonFor","result","refusal","crawlSiteForImport","options","now","Date","fetchText","fetch","String","trim","toLowerCase","startedAt","inventory","refused","pages","skipped","skippedOverflow","robots","found","sitemaps","sitemapUrls","stoppedBy","bytesRead","finishedAt","finish","maxPages","Math","max","floor","deadlineAt","controller","AbortController","onAbort","abort","signal","addEventListener","aborted","timer","setTimeout","sameSite","remainingBytes","outOfTime","request","accept","acceptHeader","maxBytes","userAgent","timeoutMs","min","redirectAllowed","_from","to","refuseOver","skip","entry","push","home","rules","ok","bytes","parsed","text","status","allowed","only","map","raw","filter","sitemapQueue","sitemapSeen","Set","fromSitemap","sitemapsRead","next","shift","has","add","room","sitemap","entries","location","locations","index","shallowFirst","depth","split","Boolean","ranked","order","sort","a","b","splice","queue","foundBy","queued","read","preferred","canon","maxAttempts","attempts","window","reserved","stop","cutOff","homeIn","held","readLayout","layout","sheets","Map","stylesheet","get","asked","Promise","resolve","then","answer","set","takeIn","cap","page","reason","edge","finalKey","isHome","structured","extract","structure","loginForm","links","link","linkKey","built","linked","all","stylesheets","slice","css","source","blocks","organization","videos","nav","footer","look","path","title","description","lang","canonical","ogImage","siteName","icons","brand","images","navLinks","forms","width","why","unread","clearTimeout","removeEventListener","readSiteVerificationMeta","metaName","answered","values","head","siteImportPagePromptText","maxChars","lines","block","kind","repeat","level","alt","inline","join"],"mappings":";IA+GEA;AA/GF;;;;;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SAASlD,KAAKmB,MAAM,CAAE;QAC/B,IAAI+B,MAAMC,IAAI,KAAK,WAAWF,MAAMnH,IAAI,CAAC,GAAG,IAAIsH,MAAM,CAACF,MAAMG,KAAK,EAAE,CAAC,EAAEH,MAAM9G,IAAI,EAAE;aAC9E,IAAI8G,MAAMC,IAAI,KAAK,SAASF,MAAMnH,IAAI,CAAC,CAAC,QAAQ,EAAEoH,MAAMI,GAAG,IAAI,iBAAiB,CAAC,CAAC;aAClF,IAAIJ,MAAMC,IAAI,KAAK,aAAaF,MAAMnH,IAAI,CAAC,CAAC,EAAE,EAAEoH,MAAM9G,IAAI,EAAE;aAC5D,IAAI8G,MAAMC,IAAI,KAAK,SAASF,MAAMnH,IAAI,CAAC,CAAC,EAAE,EAAEoH,MAAM9G,IAAI,EAAE;aACxD,IAAI8G,MAAMC,IAAI,KAAK,QAAQ;YAC9B,4DAA4D;YAC5D,IAAI,CAACD,MAAMK,MAAM,EAAEN,MAAMnH,IAAI,CAACoH,MAAM9G,IAAI;QAC1C,OAAO6G,MAAMnH,IAAI,CAACoH,MAAM9G,IAAI;IAC9B;IACA,OAAOrI,mBAAmB,CAAC,KAAK,EAAEiM,KAAKyB,IAAI,CAAC,2BAA2B,CAAC,EAAEwB,MAAMO,IAAI,CAAC,OAAO;QAAER;IAAS;AACzG"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/site-import/site-import-crawl.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * THE SITE-IMPORT CRAWLER (AGL-3974, parent AGL-3973).\n *\n * Reads a website a workspace has PROVED it owns (domain-ownership.ts in\n * tenant-data-admin; the doors check the proof before calling this) into a\n * typed inventory: each page's title, description, headings and text in\n * order, images and menu links. It writes nothing; the import job decides\n * what becomes a page.\n *\n * Every request goes through `fetchPublicTextDetailed`, the theme job's\n * SSRF-guarded fetch: https on the default port only, public addresses only,\n * the socket pinned to the address checked. On top of that:\n *\n * - **One site.** The site is `https://<domain>` and `https://www.<domain>`,\n * one site to its owner. Every redirect hop and every discovered link must\n * stay on it; a page that redirects anywhere else is refused, not followed.\n * - **AglynBot.** Every request says `AglynBot/1.0 (+<the operator's bot page>)`,\n * and robots.txt is read first and honored for every page: the AglynBot\n * group, else `*`. A robots.txt that answers 404 allows everything; one\n * that cannot be read at all (5xx, no answer) stops the crawl, because\n * \"could not ask\" is not \"allowed\".\n * - **Our own edge.** A site this platform serves gets the edge secret\n * (`site-import-edge.ts`, AGL-4085), which lifts our bot challenge for\n * AglynBot; it is asked per request and per redirect hop, and a request\n * that leaves the site's two origins never carries it.\n * - **Sitemap first.** The sitemaps robots.txt names, else /sitemap.xml (an\n * index's children included), then same-site links found on the pages read,\n * for whatever the sitemap missed.\n * - **Budgets.** Pages (the caller's, from the plan), bytes per page (a page\n * over it is refused, not cut), bytes in total, and wall-clock time. A\n * whole site's worth fits (AGL-4083): aglyn.com's 123 pages average 440 KB,\n * 54 MB in all, so the total is 160 MB; a page is parsed and dropped as it\n * is read, so what is held is its blocks, never its bytes.\n * - **Four at a time.** robots.txt, the sitemaps and the home page are read\n * one after another; the rest four at a time, and the inventory keeps the\n * order they were asked in, which is the sitemap's.\n * - **Nothing vanishes.** An address a stop (the clock, the bytes, the page\n * budget) left unread is listed as `not-reached`, so the inventory's\n * counts add up to the site. A wave's own read leaves its unread pages for\n * its next pass instead.\n * - **No lookalikes.** A domain that wears a brand it is not\n * (`lookalikeBrandForHost`) is refused before any request.\n * - **No sign-in pages.** A page with a password field is refused and\n * reported; forms with payment fields, scripts, iframes and embeds never\n * reach the inventory (site-import-html.ts).\n * - **Pages, not addresses (AGL-4152).** Another address of a page already\n * found, and a platform's own cart or account screen, are reported and\n * take nothing from the page budget (site-import-same-page.ts). Addresses a\n * link adds a query to wait for the rest. The home page is always a page,\n * and a wave's read is exactly the pages it asks for.\n *=========================================*/\n\nimport { lookalikeBrandForHost } from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport { fenceUntrustedText } from '@aglyn/shared-util-tools/untrusted-text'\nimport {\n fetchPublicTextDetailed,\n type PublicFetchEdge,\n type PublicFetchOptions,\n type PublicFetchResult,\n} from '../jobs/ai-theme-brand-inputs'\nimport type { SiteImportFooter, SiteImportLayout, SiteImportLookFacts, SiteImportNavTree } from '../model/ai-site-import'\nimport {\n extractSiteImportPage,\n readMetaValues,\n type SiteImportBlock,\n type SiteImportBrandMark,\n type SiteImportForm,\n type SiteImportVideo,\n type SiteImportIcon,\n type SiteImportImage,\n type SiteImportNavLink,\n type SiteImportOrganization,\n} from './site-import-html'\nimport {\n AGLYN_BOT_TOKEN,\n parseRobotsTxt,\n parseSitemap,\n robotsAllows,\n robotsRulesFor,\n type RobotsRule,\n} from './site-import-robots'\nimport { NO_SITE_IMPORT_HEADERS, siteImportEdgeHeadersFor, type SiteImportHeadersFor } from './site-import-edge'\nimport { siteImportReadStylesheets, type SiteImportSheetAnswer } from './site-import-css'\nimport { siteImportLayout, siteImportLookOf } from './site-import-layout'\nimport {\n siteImportAddressOf,\n siteImportCanonicalBelieved,\n siteImportCanonicalClaim,\n siteImportContentSignature,\n siteImportIsSystemScreen,\n} from './site-import-same-page'\nimport { siteImportFooterColumns, siteImportNavTree } from './site-import-nav'\n\n/**\n * Where the bot's user agent points a site owner who wants to know what it is\n * (AGL-3983): the operator's own page about it. `SITE_IMPORT_BOT_INFO_URL` on\n * a self-hosted deployment, so its crawler never names Aglyn's address; the\n * literal is only that variable's default.\n *\n * Aglyn's is the Bring my site guide, which says what AglynBot reads and how\n * robots.txt keeps it out. There is no page of its own (Zach, 10/20: \"we don't\n * need a bot page at all\"), and the site it reads is the reader's own: an\n * import starts only once its owner has proved the site is theirs.\n */\nexport const AGLYN_BOT_INFO_URL =\n process.env['SITE_IMPORT_BOT_INFO_URL'] ?? 'https://docs.aglyn.com/ai/bring-my-site'\n\n/** What every crawler request says it is. */\nexport const AGLYN_BOT_USER_AGENT = `AglynBot/1.0 (+${AGLYN_BOT_INFO_URL})`\n\nexport const SITE_IMPORT_DEFAULTS = {\n maxPageBytes: 2 * 1024 * 1024,\n /**\n * A whole site's worth (AGL-4083): 54 MB for aglyn.com's 123 pages, with\n * room; 400 pages at its 440 KB average are 176 MB (AGL-4106).\n */\n maxTotalBytes: 320 * 1024 * 1024,\n timeBudgetMs: 60_000,\n /** One request's own clock, inside the whole crawl's. */\n requestTimeoutMs: 8_000,\n robotsMaxBytes: 256 * 1024,\n sitemapMaxBytes: 4 * 1024 * 1024,\n /** All the distinct stylesheets one crawl holds at once (AGL-4152): a site's pages share theirs, and one that does not stops here. */\n stylesheetsMaxBytes: 32 * 1024 * 1024,\n /** Sitemap documents read, an index's children included: an index of six children is seven. */\n maxSitemaps: 24,\n /** URLs a sitemap may contribute to the queue. */\n maxSitemapUrls: 2_000,\n /** Reasons kept in `skipped` before the list stops growing: every address a sitemap may name. */\n maxSkipped: 2_000,\n /** Pages read at once, after robots.txt, the sitemaps and the home page. */\n concurrency: 4,\n} as const\n\n/** Never a page: files a link may point at that are not HTML. */\nconst NON_PAGE_EXTENSION =\n /\\.(?:pdf|jpe?g|png|gif|webp|avif|svg|ico|bmp|tiff?|zip|gz|tgz|rar|7z|mp4|m4v|mov|webm|mp3|wav|ogg|m4a|docx?|xlsx?|pptx?|csv|txt|css|js|mjs|json|xml|rss|atom|woff2?|ttf|otf|eot|exe|dmg|apk)$/i\n\nconst TRACKING_PARAM = /^(?:utm_[a-z]+|fbclid|gclid|msclkid|mc_cid|mc_eid|_ga|ref)$/i\n\n/**\n * Never a page, whatever its extension (AGL-4106): an API's or a CDN's path\n * (aglyn.com's press kit links 136 `/api/media/cdn/…?download=1` files) and\n * any address that asks for a download.\n */\nconst NON_PAGE_PATH = /^\\/(?:api|cdn-cgi|wp-json|_next\\/static|_next\\/image)(?:\\/|$)/i\nconst DOWNLOAD_PARAM = /^(?:download|dl|attachment)$/i\n\nconst DOMAIN_PATTERN = /^(?!-)[a-z0-9-]{1,63}(\\.[a-z0-9-]{1,63})+$/\n\nexport type SiteImportSkipReason =\n /** The page has a password field: a sign-in page, refused outright. */\n | 'login-form'\n /** robots.txt keeps AglynBot off this path. */\n | 'robots'\n /** A redirect left the site. */\n | 'off-origin-redirect'\n /** Over the per-page byte cap. */\n | 'too-large'\n /** Answered with something that is not HTML. */\n | 'not-html'\n /** Answered 4xx or 5xx. */\n | 'http-error'\n /** No answer, a private address, or a refused address. */\n | 'unreachable'\n /** Never asked for: a stop (time, bytes, the page budget) came first (AGL-4083). */\n | 'not-reached'\n /** Another address of a page already found (AGL-4152). */\n | 'duplicate'\n /** The cart, checkout or account screen the site's platform makes (AGL-4152). */\n | 'system-page'\n\nexport interface SiteImportSkipped {\n url: string\n reason: SiteImportSkipReason\n status?: number\n /** Where an off-origin redirect pointed. */\n location?: string\n /** Whose edge turned an error answer away, when it said (AGL-4083). */\n edge?: PublicFetchEdge\n /** The page a `duplicate` is another address of (AGL-4152). */\n sameAs?: string\n}\n\nexport interface SiteImportPage {\n /** The address the page was read from, after any same-site redirect. */\n url: string\n path: string\n /** Where the crawler learned of the page. */\n foundBy: 'home' | 'sitemap' | 'link'\n title: string\n description: string\n lang: string | null\n canonical: string | null\n /** The share card (AGL-4083). */\n ogImage: string | null\n /** The site's own name, as its head gives it. */\n siteName: string\n icons: SiteImportIcon[]\n /** The header's link home: the brand's logo and words. */\n brand: SiteImportBrandMark | null\n organization: SiteImportOrganization | null\n blocks: SiteImportBlock[]\n images: SiteImportImage[]\n navLinks: SiteImportNavLink[]\n /** Same-site page addresses this page links to. */\n links: string[]\n forms: { kept: SiteImportForm[]; removed: number }\n /** Its videos (AGL-4140), each once; absent on a page with none. */\n videos?: SiteImportVideo[]\n bytes: number\n /** How the source lays the page out (AGL-4106), on a read asked for it (`layout`): a wave's. */\n layout?: SiteImportLayout | null\n /** The home page's menu, footer and look, as its source builds them (AGL-4106). */\n nav?: SiteImportNavTree | null\n footer?: SiteImportFooter | null\n look?: SiteImportLookFacts | null\n}\n\nexport type SiteImportStop =\n | 'page-budget'\n | 'total-bytes'\n | 'time'\n /** robots.txt could not be read, so nothing was asked of the site. */\n | 'robots-unreachable'\n\nexport interface SiteImportInventory {\n domain: string\n /** The site's origins: the bare name and its `www.` twin. */\n origins: string[]\n /** Set when nothing was fetched at all. */\n refused: 'invalid-domain' | 'lookalike' | null\n pages: SiteImportPage[]\n skipped: SiteImportSkipped[]\n /** Skips past {@link SITE_IMPORT_DEFAULTS.maxSkipped}, counted only. */\n skippedOverflow: number\n robots: { found: boolean; sitemaps: string[] }\n /** Page addresses the sitemaps listed (same-site, before robots and budget). */\n sitemapUrls: number\n stoppedBy: SiteImportStop | null\n bytesRead: number\n startedAt: number\n finishedAt: number\n}\n\nexport interface SiteImportCrawlOptions {\n /** The proved domain; `www.` is folded in. */\n domain: string\n /** The most pages the inventory may hold: the plan's page count. */\n maxPages: number\n maxPageBytes?: number\n maxTotalBytes?: number\n timeBudgetMs?: number\n signal?: AbortSignal\n /**\n * Read the sitemap's shallow addresses before its deep ones (AGL-3976), so a\n * crawl the page budget stops reads a site's main pages before the tail of\n * its blog. A sitemap's own order is kept among addresses of one depth.\n */\n shallowFirst?: boolean\n /**\n * Read exactly these addresses of the site, in order, and nothing else\n * (AGL-3976): an import's wave reads its own pages again when it starts. No\n * sitemap is read and no link is followed; robots.txt is read and honored\n * as for any crawl, and every other rule holds.\n */\n only?: readonly string[]\n /**\n * Read how each page is laid out (AGL-4106): its structure, through its own\n * stylesheets (the first two it links, each asked once a crawl). On by\n * default for a wave's read (`only`), whose pages are built; the home page's\n * menu, footer and look are read on every crawl.\n */\n layout?: boolean\n}\n\nexport interface SiteImportCrawlSeams {\n fetch?: (url: string, options: PublicFetchOptions) => Promise<PublicFetchResult>\n now?: () => number\n /**\n * Request headers for the site being read, asked once per crawl with its\n * domain (AGL-4083, AGL-4085). Absent, the crawl asks the edge\n * (`siteImportEdgeHeadersFor`): Aglyn's edge secret for each of the site's\n * two origins this platform serves, decided origin by origin, and nothing\n * anywhere else. Either way the headers go only to the site's two origins,\n * and the fetch asks again on every redirect hop, so a hop anywhere else\n * carries nothing. Always under the crawler's own `Accept` and `User-Agent`.\n */\n headersFor?: (domain: string) => Promise<Readonly<Record<string, string>>> | Readonly<Record<string, string>>\n}\n\n/**\n * The per-request headers of a crawl of `domain`: the seam's, else the edge's,\n * and none for any address off the site's two origins. Never throws.\n */\nasync function siteRequestHeaders(\n seams: SiteImportCrawlSeams,\n domain: string,\n origins: readonly string[],\n): Promise<SiteImportHeadersFor> {\n let inner: SiteImportHeadersFor = NO_SITE_IMPORT_HEADERS\n try {\n if (seams.headersFor) {\n const headers = await seams.headersFor(domain)\n if (headers && Object.keys(headers).length) inner = () => headers\n } else {\n inner = await siteImportEdgeHeadersFor(origins)\n }\n } catch (error) {\n console.warn('[site-import] the edge headers could not be read; reading without them', { domain, error })\n }\n return (url: URL) => (origins.includes(url.origin) ? inner(url) : {})\n}\n\n/** The site's two origins for a domain. */\nexport function siteImportOrigins(domain: string): string[] {\n const bare = domain.replace(/^www\\./, '')\n return [`https://${bare}`, `https://www.${bare}`]\n}\n\n/** A crawlable page address on the site, normalized for de-duplication; else null. */\nexport function siteImportPageKey(url: URL, origins: readonly string[]): string | null {\n if (url.protocol !== 'https:' || url.username || url.password) return null\n if (url.port && url.port !== '443') return null\n if (!origins.includes(url.origin)) return null\n if (NON_PAGE_EXTENSION.test(url.pathname) || NON_PAGE_PATH.test(url.pathname)) return null\n if ([...url.searchParams.keys()].some((key) => DOWNLOAD_PARAM.test(key))) return null\n const clean = new URL(url.toString())\n clean.hash = ''\n for (const key of [...clean.searchParams.keys()]) {\n if (TRACKING_PARAM.test(key)) clean.searchParams.delete(key)\n }\n clean.search = clean.searchParams.toString() ? `?${clean.searchParams.toString()}` : ''\n return clean.toString()\n}\n\nfunction skipReasonFor(result: PublicFetchResult): SiteImportSkipReason {\n switch (result.refusal) {\n case 'redirect-refused':\n return 'off-origin-redirect'\n case 'content-type':\n return 'not-html'\n case 'too-large':\n return 'too-large'\n case 'http-status':\n return 'http-error'\n default:\n return 'unreachable'\n }\n}\n\n/** Read a proved site into an inventory. Never throws for anything the site does. */\nexport async function crawlSiteForImport(\n options: SiteImportCrawlOptions,\n seams: SiteImportCrawlSeams = {},\n): Promise<SiteImportInventory> {\n const now = seams.now ?? Date.now\n const fetchText = seams.fetch ?? fetchPublicTextDetailed\n const domain = String(options.domain ?? '').trim().toLowerCase().replace(/\\.+$/, '').replace(/^www\\./, '')\n const origins = DOMAIN_PATTERN.test(domain) ? siteImportOrigins(domain) : []\n const startedAt = now()\n const inventory: SiteImportInventory = {\n domain,\n origins,\n refused: null,\n pages: [],\n skipped: [],\n skippedOverflow: 0,\n robots: { found: false, sitemaps: [] },\n sitemapUrls: 0,\n stoppedBy: null,\n bytesRead: 0,\n startedAt,\n finishedAt: startedAt,\n }\n const finish = () => {\n inventory.finishedAt = now()\n return inventory\n }\n if (!origins.length) {\n inventory.refused = 'invalid-domain'\n return finish()\n }\n if (lookalikeBrandForHost(domain)) {\n inventory.refused = 'lookalike'\n return finish()\n }\n\n // Asked once, before anything else, and held to the site's two origins.\n const headersFor = await siteRequestHeaders(seams, domain, origins)\n const maxPages = Math.max(0, Math.floor(options.maxPages))\n const maxPageBytes = options.maxPageBytes ?? SITE_IMPORT_DEFAULTS.maxPageBytes\n const maxTotalBytes = options.maxTotalBytes ?? SITE_IMPORT_DEFAULTS.maxTotalBytes\n const deadlineAt = startedAt + (options.timeBudgetMs ?? SITE_IMPORT_DEFAULTS.timeBudgetMs)\n const controller = new AbortController()\n const onAbort = () => controller.abort()\n options.signal?.addEventListener('abort', onAbort)\n if (options.signal?.aborted) controller.abort()\n const timer = setTimeout(() => controller.abort(), Math.max(0, deadlineAt - startedAt))\n\n const sameSite = (url: URL) => origins.includes(url.origin) && url.protocol === 'https:'\n const remainingBytes = () => maxTotalBytes - inventory.bytesRead\n const outOfTime = () => controller.signal.aborted || now() >= deadlineAt\n /** A stylesheet's read (`sheet`) may be cut at its cap and may go where its CDN sends it: every hop is checked as public all the same. */\n const request = (url: string, accept: RegExp, acceptHeader: string, maxBytes: number, sheet = false) =>\n fetchText(url, {\n maxBytes,\n accept,\n acceptHeader,\n userAgent: AGLYN_BOT_USER_AGENT,\n headersFor,\n signal: controller.signal,\n timeoutMs: Math.max(1, Math.min(SITE_IMPORT_DEFAULTS.requestTimeoutMs, deadlineAt - now())),\n ...(sheet ? {} : { redirectAllowed: (_from: URL, to: URL) => sameSite(to), refuseOver: true }),\n })\n /** Addresses taken in, read or not: one a page is waiting on that is here and is no page will never be. */\n const takenIn = new Set<string>()\n const skip = (entry: SiteImportSkipped) => {\n takenIn.add(siteImportAddressOf(entry.url))\n if (inventory.skipped.length < SITE_IMPORT_DEFAULTS.maxSkipped) inventory.skipped.push(entry)\n else inventory.skippedOverflow += 1\n }\n\n try {\n // robots.txt, before anything else is asked of the site.\n const home = `${origins[0]}/`\n let rules: RobotsRule[] = []\n const robots = await request(\n `${origins[0]}/robots.txt`,\n /text\\/plain|text\\/html|^$/i,\n 'text/plain',\n Math.min(SITE_IMPORT_DEFAULTS.robotsMaxBytes, remainingBytes()),\n )\n if (robots.ok) {\n inventory.bytesRead += robots.bytes\n const parsed = parseRobotsTxt(robots.text)\n rules = robotsRulesFor(parsed, AGLYN_BOT_TOKEN)\n inventory.robots = { found: true, sitemaps: parsed.sitemaps }\n } else if (\n !(robots.refusal === 'http-status' && (robots.status ?? 0) >= 400 && (robots.status ?? 0) < 500)\n ) {\n inventory.stoppedBy = outOfTime() ? 'time' : 'robots-unreachable'\n return finish()\n }\n const allowed = (key: string) => {\n const url = new URL(key)\n return robotsAllows(rules, `${url.pathname}${url.search}`)\n }\n\n // A wave's own pages (AGL-3976): exactly those, after robots.txt.\n const only = options.only\n ? options.only\n .map((raw) => {\n try {\n return siteImportPageKey(new URL(raw), origins)\n } catch {\n return null\n }\n })\n .filter((key): key is string => !!key)\n : null\n\n // Sitemaps: the ones robots.txt names on this site, else /sitemap.xml.\n const sitemapQueue: string[] = []\n for (const raw of inventory.robots.sitemaps) {\n try {\n const url = new URL(raw)\n if (sameSite(url)) sitemapQueue.push(url.toString())\n } catch {\n // A malformed Sitemap line names nothing.\n }\n }\n if (!sitemapQueue.length && !only) sitemapQueue.push(`${origins[0]}/sitemap.xml`)\n if (only) sitemapQueue.length = 0\n const sitemapSeen = new Set<string>()\n const fromSitemap: string[] = []\n let sitemapsRead = 0\n while (sitemapQueue.length && sitemapsRead < SITE_IMPORT_DEFAULTS.maxSitemaps && !outOfTime()) {\n const next = sitemapQueue.shift() as string\n if (sitemapSeen.has(next)) continue\n sitemapSeen.add(next)\n if (/\\.gz$/i.test(new URL(next).pathname)) continue\n if (!allowed(next)) continue\n const room = Math.min(SITE_IMPORT_DEFAULTS.sitemapMaxBytes, remainingBytes())\n if (room <= 0) break\n sitemapsRead += 1\n const sitemap = await request(next, /xml|text\\/plain/i, 'application/xml, text/xml;q=0.9', room)\n if (!sitemap.ok) continue\n inventory.bytesRead += sitemap.bytes\n const entries = parseSitemap(sitemap.text)\n for (const location of entries.locations) {\n let url: URL\n try {\n url = new URL(location)\n } catch {\n continue\n }\n if (entries.index) {\n if (sameSite(url)) sitemapQueue.push(url.toString())\n continue\n }\n const key = siteImportPageKey(url, origins)\n if (key && fromSitemap.length < SITE_IMPORT_DEFAULTS.maxSitemapUrls) fromSitemap.push(key)\n }\n }\n inventory.sitemapUrls = fromSitemap.length\n if (options.shallowFirst) {\n const depth = (key: string) => new URL(key).pathname.split('/').filter(Boolean).length\n const ranked = fromSitemap.map((key, order) => ({ key, order, depth: depth(key) }))\n ranked.sort((a, b) => a.depth - b.depth || a.order - b.order)\n fromSitemap.splice(0, fromSitemap.length, ...ranked.map((entry) => entry.key))\n }\n\n // Pages: home, then the sitemap's, then links the pages themselves name.\n // A wave's read is its own pages alone.\n const queue: { key: string; foundBy: SiteImportPage['foundBy'] }[] = only\n ? only.map((key) => ({ key, foundBy: (new URL(key).pathname === '/' ? 'home' : 'link') as SiteImportPage['foundBy'] }))\n : [{ key: home, foundBy: 'home' }]\n /** Addresses a link adds a query to, which wait for every other (AGL-4152): a gallery's hundred never starve a page. */\n const later: typeof queue = []\n const queued = new Set<string>(only ?? [home])\n for (const key of fromSitemap) {\n if (queued.has(key)) continue\n queued.add(key)\n queue.push({ key, foundBy: 'sitemap' })\n }\n const read = new Set<string>()\n // The site's two names are one site: once the home page says which one\n // it answers on, every address is read on that one, so /about is not\n // read twice as example.com/about and www.example.com/about.\n // A wave's read starts on the name its pages were read on the first time.\n let preferred = only?.length ? new URL(only[0]).origin : origins[0]\n const canon = (raw: string) => {\n const url = new URL(raw)\n return origins.includes(url.origin) && url.origin !== preferred\n ? `${preferred}${url.pathname}${url.search}`\n : raw\n }\n const maxAttempts = maxPages * 3 + 10\n let attempts = 0\n type Asked = { next: (typeof queue)[number]; key: string; cap: number; page: PublicFetchResult }\n /** The pages asked for and not yet taken in, in the order they were asked. */\n const window: Array<Promise<Asked>> = []\n /** The bytes the asked pages may still read: what is left is shared, never promised twice. */\n let reserved = 0\n let stop: SiteImportStop | null = null\n /** Asked for and never read, because a stop came first: listed as not reached. */\n const cutOff: string[] = []\n /** Home alone first, so its answer settles which of the site's two names the rest are read on. */\n let homeIn = !!only\n /** Why no more may be asked now: a stop, `wait` for an asked page to come in first, or nothing. */\n const held = (): SiteImportStop | 'wait' | null => {\n if (inventory.pages.length >= maxPages) return 'page-budget'\n if (outOfTime()) return 'time'\n if (remainingBytes() <= 0) return 'total-bytes'\n if (attempts >= maxAttempts) return 'page-budget'\n if (inventory.pages.length + window.length >= maxPages) return 'wait'\n if (remainingBytes() - reserved <= 0) return 'wait'\n return null\n }\n /** The page each address is, its other addresses included. */\n const pageAt = new Map<string, SiteImportPage>()\n /** The first page found with each main content. */\n const pageWith = new Map<string, SiteImportPage>()\n /** Pages whose canonical names an address not yet taken in. */\n const waiting: Array<{ page: SiteImportPage; claim: string; signature: string | null }> = []\n const place = (page: SiteImportPage, signature: string | null) => {\n inventory.pages.push(page)\n pageAt.set(siteImportAddressOf(page.url), page)\n if (signature && !pageWith.has(signature)) pageWith.set(signature, page)\n }\n const leaveSameAs = (url: string, page: SiteImportPage) => {\n pageAt.set(siteImportAddressOf(url), page)\n skip({ url, reason: 'duplicate', sameAs: page.url })\n }\n /** The page this address is another address of; `wait` for the one its canonical names; or `null`, its own page. */\n const sameAs = (url: string, claim: string | null, signature: string | null): SiteImportPage | 'wait' | null => {\n const same = signature ? pageWith.get(signature) : undefined\n if (same) return same\n if (!claim) return null\n const named = pageAt.get(siteImportAddressOf(claim))\n if (named) return siteImportCanonicalBelieved(url, claim) ? named : null\n return takenIn.has(siteImportAddressOf(claim)) ? null : 'wait'\n }\n /** The waiting pages whose answer is in; `last`, all of them: what they named never came, so each stands. */\n const settle = (last = false) => {\n for (const entry of [...waiting]) {\n const verdict = sameAs(entry.page.url, entry.claim, entry.signature)\n if (verdict === 'wait' && !last) continue\n waiting.splice(waiting.indexOf(entry), 1)\n if (verdict && verdict !== 'wait') leaveSameAs(entry.page.url, verdict)\n else if (inventory.pages.length < maxPages) place(entry.page, entry.signature)\n else {\n stop ??= 'page-budget'\n skip({ url: entry.page.url, reason: 'not-reached' })\n }\n }\n }\n const readLayout = options.layout ?? !!only\n /** Linked stylesheets, as far as any page has read each: a sheet a page shares is asked no further than it was. */\n const sheets = new Map<string, { asked: number; answer: SiteImportSheetAnswer | null }>()\n let sheetBytes = 0\n const stylesheet = async (url: string, maxBytes: number): Promise<SiteImportSheetAnswer | null> => {\n const held = sheets.get(url)\n if (held && (held.asked >= maxBytes || (held.answer && !held.answer.truncated))) return held.answer\n const room = Math.min(maxBytes, SITE_IMPORT_DEFAULTS.stylesheetsMaxBytes - sheetBytes + (held?.answer?.bytes ?? 0), remainingBytes() - reserved)\n if (room <= 0 || outOfTime()) return held?.answer ?? null\n const read = await request(url, /text\\/css|text\\/plain/i, 'text/css,*/*;q=0.1', room, true).catch(() => null)\n if (read?.ok) inventory.bytesRead += read.bytes\n const answer = read?.ok ? read : (held?.answer ?? null)\n sheetBytes += (answer?.bytes ?? 0) - (held?.answer?.bytes ?? 0)\n sheets.set(url, { asked: room, answer })\n return answer\n }\n /** Takes one asked page in: the inventory's next page, a skip, or the reason the read must stop. */\n const takeIn = async ({ next, key, cap, page }: Asked): Promise<SiteImportStop | null> => {\n const foundBy = next.foundBy\n if (foundBy === 'home') homeIn = true\n takenIn.add(siteImportAddressOf(key))\n if (!page.ok) {\n if (page.refusal === 'too-large' && cap < maxPageBytes) {\n cutOff.push(key)\n return 'total-bytes'\n }\n if (page.refusal === 'network' && outOfTime()) {\n cutOff.push(key)\n return 'time'\n }\n // A file is not a page: it takes nothing from the page budget's attempts (AGL-4106).\n if (page.refusal === 'content-type') attempts = Math.max(0, attempts - 1)\n skip({\n url: key,\n reason: skipReasonFor(page),\n ...(page.status ? { status: page.status } : {}),\n ...(page.location ? { location: page.location } : {}),\n ...(page.edge ? { edge: page.edge } : {}),\n })\n return null\n }\n inventory.bytesRead += page.bytes\n if (foundBy === 'home') preferred = new URL(page.url).origin\n const finalKey = canon(siteImportPageKey(new URL(page.url), origins) ?? page.url)\n takenIn.add(siteImportAddressOf(finalKey))\n if (finalKey !== key) {\n if (read.has(finalKey)) return null\n read.add(finalKey)\n if (!allowed(finalKey)) {\n skip({ url: finalKey, reason: 'robots' })\n return null\n }\n }\n const isHome = foundBy === 'home'\n const structured = readLayout || isHome\n const extract = extractSiteImportPage(page.text, page.url, sameSite, { structure: structured })\n if (extract.loginForm) {\n skip({ url: finalKey, reason: 'login-form' })\n return null\n }\n const links: string[] = []\n for (const link of extract.links) {\n const linkKey = siteImportPageKey(new URL(link), origins)\n if (!linkKey) continue\n links.push(linkKey)\n if (!only && !queued.has(linkKey)) {\n queued.add(linkKey)\n ;(new URL(linkKey).search ? later : queue).push({ key: linkKey, foundBy: 'link' })\n }\n }\n // Whether it is a page of its own (AGL-4152). What is not takes nothing from the budget.\n const own = !only && !isHome\n if (own && siteImportIsSystemScreen(new URL(finalKey).pathname, extract)) {\n attempts = Math.max(0, attempts - 1)\n skip({ url: finalKey, reason: 'system-page' })\n return null\n }\n const signature = only ? null : siteImportContentSignature(extract)\n const claim = own ? siteImportCanonicalClaim(extract.canonical, finalKey, (url) => siteImportPageKey(url, origins)) : null\n const verdict = own ? sameAs(finalKey, claim, signature) : null\n if (verdict && verdict !== 'wait') {\n attempts = Math.max(0, attempts - 1)\n leaveSameAs(finalKey, verdict)\n return null\n }\n // How the page is built (AGL-4106), through its own stylesheets.\n let built: Pick<SiteImportPage, 'layout' | 'nav' | 'footer' | 'look'> = {}\n if (extract.structure) {\n const css = await siteImportReadStylesheets(extract.structure.stylesheets.filter((url) => !/fonts\\.googleapis\\.com/i.test(url)), stylesheet, { outOfTime })\n const source = { blocks: extract.blocks, organization: extract.organization, structure: extract.structure, ...(extract.videos ? { videos: extract.videos } : {}) }\n try {\n built = {\n ...(readLayout ? { layout: siteImportLayout(source, css) } : {}),\n ...(isHome ? { nav: siteImportNavTree(source, css), footer: siteImportFooterColumns(source, css), look: siteImportLookOf(source, css) } : {}),\n }\n } catch (error) {\n // A page the reader cannot lay out is still its words.\n console.warn('[site-import] the layout could not be read', { url: page.url, error })\n }\n }\n const taken: SiteImportPage = {\n ...built,\n url: finalKey,\n path: new URL(finalKey).pathname,\n foundBy,\n title: extract.title,\n description: extract.description,\n lang: extract.lang,\n canonical: extract.canonical,\n ogImage: extract.ogImage,\n siteName: extract.siteName,\n icons: extract.icons,\n brand: extract.brand,\n organization: extract.organization,\n blocks: extract.blocks,\n images: extract.images,\n navLinks: extract.navLinks,\n links: [...new Set(links.map(canon))],\n forms: extract.forms,\n ...(extract.videos ? { videos: extract.videos } : {}),\n bytes: page.bytes,\n }\n if (verdict === 'wait' && claim) {\n // The page it names comes next, even if nothing else links it.\n attempts = Math.max(0, attempts - 1)\n waiting.push({ page: taken, claim, signature })\n if (!queued.has(claim) && !read.has(canon(claim))) {\n queued.add(claim)\n queue.unshift({ key: claim, foundBy: 'link' })\n }\n return null\n }\n place(taken, signature)\n return null\n }\n for (;;) {\n const width = homeIn ? SITE_IMPORT_DEFAULTS.concurrency : 1\n while (!stop && (queue.length || later.length) && window.length < width) {\n const why = held()\n if (why === 'wait') break\n if (why) {\n stop = why\n break\n }\n const next = (queue.shift() ?? later.shift()) as (typeof queue)[number]\n const key = canon(next.key)\n if (read.has(key)) continue\n if (!allowed(key)) {\n skip({ url: key, reason: 'robots' })\n if (next.foundBy === 'home') homeIn = true\n continue\n }\n attempts += 1\n read.add(key)\n const cap = Math.min(maxPageBytes, remainingBytes() - reserved)\n reserved += cap\n window.push(\n request(key, /text\\/html|application\\/xhtml\\+xml/i, 'text/html, application/xhtml+xml;q=0.9', cap).then((page) => ({ next, key, cap, page })),\n )\n }\n if (!window.length) break\n const asked = await (window.shift() as Promise<Asked>)\n reserved -= asked.cap\n stop = (await takeIn(asked)) ?? stop\n settle()\n }\n settle(true)\n inventory.stoppedBy = stop\n // Whatever a stop left unread is said, never dropped; a wave's own read\n // leaves its unread pages for its next pass instead.\n if (stop && !only) {\n const unread = [...cutOff]\n for (const next of [...queue, ...later]) {\n const key = canon(next.key)\n if (!read.has(key) && !unread.includes(key)) unread.push(key)\n }\n for (const url of unread) skip({ url, reason: 'not-reached' })\n }\n return finish()\n } finally {\n clearTimeout(timer)\n options.signal?.removeEventListener('abort', onAbort)\n }\n}\n\n/**\n * The home page's `aglyn-site-verification` values, for the meta-tag proof:\n * the same fetch, user agent and same-site redirects as the crawl, but no\n * robots.txt, because the person asked for this one page to be read.\n * `answered: false` when the page could not be read at all.\n */\nexport async function readSiteVerificationMeta(\n domain: string,\n metaName: string,\n seams: SiteImportCrawlSeams = {},\n): Promise<{ answered: boolean; values: string[]; url?: string }> {\n const fetchText = seams.fetch ?? fetchPublicTextDetailed\n const bare = String(domain ?? '').trim().toLowerCase().replace(/^www\\./, '')\n if (!DOMAIN_PATTERN.test(bare) || lookalikeBrandForHost(bare)) return { answered: false, values: [] }\n const origins = siteImportOrigins(bare)\n const result = await fetchText(`${origins[0]}/`, {\n maxBytes: SITE_IMPORT_DEFAULTS.maxPageBytes,\n accept: /text\\/html|application\\/xhtml\\+xml/i,\n acceptHeader: 'text/html, application/xhtml+xml;q=0.9',\n userAgent: AGLYN_BOT_USER_AGENT,\n headersFor: await siteRequestHeaders(seams, bare, origins),\n timeoutMs: SITE_IMPORT_DEFAULTS.requestTimeoutMs,\n redirectAllowed: (_from, to) => to.protocol === 'https:' && origins.includes(to.origin),\n })\n if (!result.ok) {\n // An answer that is not the page (a 404, a redirect off the site) is\n // still an answer: the tag is not where it must be.\n const answered = result.refusal === 'http-status' || result.refusal === 'redirect-refused' || result.refusal === 'content-type'\n return { answered, values: [], url: result.url }\n }\n const head = result.text.split(/<body\\b/i)[0] ?? ''\n return { answered: true, values: readMetaValues(head, metaName), url: result.url }\n}\n\n/**\n * One page as text for a prompt: its title, description and blocks in order,\n * fenced as untrusted data. The importer's prompt carries `UNTRUSTED_TEXT_RULE`.\n */\nexport function siteImportPagePromptText(page: SiteImportPage, maxChars = 12_000): string {\n const lines: string[] = []\n if (page.title) lines.push(`Title: ${page.title}`)\n if (page.description) lines.push(`Description: ${page.description}`)\n for (const block of page.blocks) {\n if (block.kind === 'heading') lines.push(`${'#'.repeat(block.level)} ${block.text}`)\n else if (block.kind === 'image') lines.push(`[image: ${block.alt || 'no description'}]`)\n else if (block.kind === 'list-item') lines.push(`- ${block.text}`)\n else if (block.kind === 'quote') lines.push(`> ${block.text}`)\n else if (block.kind === 'link') {\n // A link inside a sentence is in its block's words already.\n if (!block.inline) lines.push(block.text)\n } else lines.push(block.text)\n }\n return fenceUntrustedText(`Page ${page.path} of the site being imported`, lines.join('\\n'), { maxChars })\n}\n"],"names":["process","lookalikeBrandForHost","fenceUntrustedText","fetchPublicTextDetailed","extractSiteImportPage","readMetaValues","AGLYN_BOT_TOKEN","parseRobotsTxt","parseSitemap","robotsAllows","robotsRulesFor","NO_SITE_IMPORT_HEADERS","siteImportEdgeHeadersFor","siteImportReadStylesheets","siteImportLayout","siteImportLookOf","siteImportAddressOf","siteImportCanonicalBelieved","siteImportCanonicalClaim","siteImportContentSignature","siteImportIsSystemScreen","siteImportFooterColumns","siteImportNavTree","AGLYN_BOT_INFO_URL","env","AGLYN_BOT_USER_AGENT","SITE_IMPORT_DEFAULTS","maxPageBytes","maxTotalBytes","timeBudgetMs","requestTimeoutMs","robotsMaxBytes","sitemapMaxBytes","stylesheetsMaxBytes","maxSitemaps","maxSitemapUrls","maxSkipped","concurrency","NON_PAGE_EXTENSION","TRACKING_PARAM","NON_PAGE_PATH","DOWNLOAD_PARAM","DOMAIN_PATTERN","siteRequestHeaders","seams","domain","origins","inner","headersFor","headers","Object","keys","length","error","console","warn","url","includes","origin","siteImportOrigins","bare","replace","siteImportPageKey","protocol","username","password","port","test","pathname","searchParams","some","key","clean","URL","toString","hash","delete","search","skipReasonFor","result","refusal","crawlSiteForImport","options","now","Date","fetchText","fetch","String","trim","toLowerCase","startedAt","inventory","refused","pages","skipped","skippedOverflow","robots","found","sitemaps","sitemapUrls","stoppedBy","bytesRead","finishedAt","finish","maxPages","Math","max","floor","deadlineAt","controller","AbortController","onAbort","abort","signal","addEventListener","aborted","timer","setTimeout","sameSite","remainingBytes","outOfTime","request","accept","acceptHeader","maxBytes","sheet","userAgent","timeoutMs","min","redirectAllowed","_from","to","refuseOver","takenIn","Set","skip","entry","add","push","home","rules","ok","bytes","parsed","text","status","allowed","only","map","raw","filter","sitemapQueue","sitemapSeen","fromSitemap","sitemapsRead","next","shift","has","room","sitemap","entries","location","locations","index","shallowFirst","depth","split","Boolean","ranked","order","sort","a","b","splice","queue","foundBy","later","queued","read","preferred","canon","maxAttempts","attempts","window","reserved","stop","cutOff","homeIn","held","pageAt","Map","pageWith","waiting","place","page","signature","set","leaveSameAs","reason","sameAs","claim","same","get","undefined","named","settle","last","verdict","indexOf","readLayout","layout","sheets","sheetBytes","stylesheet","asked","answer","truncated","catch","takeIn","cap","edge","finalKey","isHome","structured","extract","structure","loginForm","links","link","linkKey","own","canonical","built","css","stylesheets","source","blocks","organization","videos","nav","footer","look","taken","path","title","description","lang","ogImage","siteName","icons","brand","images","navLinks","forms","unshift","width","why","then","unread","clearTimeout","removeEventListener","readSiteVerificationMeta","metaName","answered","values","head","siteImportPagePromptText","maxChars","lines","block","kind","repeat","level","alt","inline","join"],"mappings":";IA0HEA;AA1HF;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAkD2C,GAE3C,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SAASC,kBAAkB,QAAQ,0CAAyC;AAC5E,SACEC,uBAAuB,QAIlB,mCAA+B;AAEtC,SACEC,qBAAqB,EACrBC,cAAc,QAST,wBAAoB;AAC3B,SACEC,eAAe,EACfC,cAAc,EACdC,YAAY,EACZC,YAAY,EACZC,cAAc,QAET,0BAAsB;AAC7B,SAASC,sBAAsB,EAAEC,wBAAwB,QAAmC,wBAAoB;AAChH,SAASC,yBAAyB,QAAoC,uBAAmB;AACzF,SAASC,gBAAgB,EAAEC,gBAAgB,QAAQ,0BAAsB;AACzE,SACEC,mBAAmB,EACnBC,2BAA2B,EAC3BC,wBAAwB,EACxBC,0BAA0B,EAC1BC,wBAAwB,QACnB,6BAAyB;AAChC,SAASC,uBAAuB,EAAEC,iBAAiB,QAAQ,uBAAmB;AAE9E;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,sBACXvB,wCAAAA,QAAQwB,GAAG,CAAC,2BAA2B,YAAvCxB,wCAA2C,0CAAyC;AAEtF,2CAA2C,GAC3C,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ontFaces: string[];
61
+ /** Read for its dark scheme (AGL-4152): the rules that scheme alone selects, by a media query or a class on the page. */
62
+ darkRules: number;
63
+ /** How many declarations read each custom property (AGL-4152): what its palette uses most. */
64
+ variableUses: Map<string, number>;
65
+ }
66
+ /** Which of a page's color schemes a read of its stylesheets answers for. */
67
+ export interface SiteImportCssOptions {
68
+ /** Absent is `light`, as a page is first read. */
69
+ scheme?: 'light' | 'dark';
61
70
  }
62
71
  /** A length in px at the read width; `em`/`rem` at 16. */
63
72
  export declare function siteImportLengthPx(value: string): number | null;
@@ -65,7 +74,7 @@ export declare function siteImportLengthPx(value: string): number | null;
65
74
  * The page's sheets parsed for a wide screen. Malformed CSS is read as far as
66
75
  * it makes sense, as a browser would; nothing throws.
67
76
  */
68
- export declare function siteImportCssOf(sheets: readonly string[], viewport?: number): SiteImportCss;
77
+ export declare function siteImportCssOf(sheets: readonly string[], viewport?: number, options?: SiteImportCssOptions): SiteImportCss;
69
78
  /** One element's resolved style: the kept properties, `var()` read, lowercased. */
70
79
  export type SiteImportComputedStyle = ReadonlyMap<string, string>;
71
80
  /** Reads elements' styles over a page's structure, each once. */
@@ -73,6 +82,8 @@ export interface SiteImportStyles {
73
82
  of(element: number): SiteImportComputedStyle;
74
83
  /** The root's (`<html>`) element id, which `:root` matches; -1 for none. */
75
84
  readonly root: number;
85
+ /** The custom properties the root declares (AGL-4152), each read through to what it holds. */
86
+ rootVariables(): ReadonlyMap<string, string>;
76
87
  }
77
88
  /**
78
89
  * Elements' styles over a page's structure and its sheets. Styles are
@@ -87,6 +98,13 @@ export interface SiteImportRgba {
87
98
  }
88
99
  /** The first color a value names, or `null`; `transparent` is a color of no strength. */
89
100
  export declare function siteImportColorOf(value: string | undefined): SiteImportRgba | null;
101
+ /**
102
+ * The brand colors a page's root declares (AGL-4152): the custom properties
103
+ * named for a brand that hold a color, a triple included, none too pale, dark
104
+ * or grey to carry one, the most read first. What the page says its brand is,
105
+ * even where nothing on this page happens to draw it.
106
+ */
107
+ export declare function siteImportPaletteOf(styles: Pick<SiteImportStyles, 'rootVariables'>, uses: ReadonlyMap<string, number>): string[];
90
108
  /** `#rrggbb` of a color, its strength ignored. */
91
109
  export declare function siteImportHex(color: SiteImportRgba): string;
92
110
  /** Relative luminance, 0 (black) to 1 (white). */
@@ -132,8 +150,78 @@ export declare function siteImportRadiusPx(style: SiteImportComputedStyle): numb
132
150
  export declare function siteImportFontSizePx(style: SiteImportComputedStyle): number | null;
133
151
  /** The relative widths a grid template draws its columns at, or `null` for none. */
134
152
  export declare function siteImportGridColumns(template: string | undefined): number[] | null;
153
+ /**
154
+ * How many tracks a grid template draws (AGL-4152), each `repeat()` opened at
155
+ * its whole count; `null` for none, or where the screen decides (`auto-fill`).
156
+ */
157
+ export declare function siteImportGridTrackCount(template: string | undefined): number | null;
158
+ /** The cells a child of a grid covers, by grid line: `rowEnd` and `columnEnd` are the lines after its last row and column. */
159
+ export interface SiteImportGridBox {
160
+ rowStart: number;
161
+ rowEnd: number;
162
+ columnStart: number;
163
+ columnEnd: number;
164
+ }
165
+ /** A flex or grid child's `order`, 0 where it sets none. */
166
+ export declare function siteImportOrderOf(style: SiteImportComputedStyle): number;
167
+ /**
168
+ * Where a grid places its children (AGL-4152), each child's cells by grid
169
+ * line, as a browser lays them out: the lines each child names (by
170
+ * `grid-area`, a named area, `grid-row` or `grid-column`, a longhand over the
171
+ * shorthand; lines from the end read from the template), then the children it
172
+ * leaves to the grid's flow, in `order`, each in the first cells free.
173
+ *
174
+ * `null` where it cannot say, or there is nothing to say: no child names a
175
+ * place (a `span` says how wide, and `1 / -1` the whole row, not where), the
176
+ * rest of the children flow by columns, or through tracks the screen decides.
177
+ */
178
+ export declare function siteImportGridBoxes(container: SiteImportComputedStyle, items: readonly SiteImportComputedStyle[]): SiteImportGridBox[] | null;
135
179
  /** Weights scaled to twelfths, each at least 1: `[420, 788]` is `[4, 8]`. */
136
180
  export declare function siteImportTwelfths(weights: readonly number[]): number[];
137
181
  /** The families a `font-family` value names, quotes dropped, generic ones left out. */
138
182
  export declare function siteImportFontFamilies(value: string | undefined): string[];
183
+ /**
184
+ * How much of a page's stylesheets is read (AGL-4152). A site builder's own
185
+ * sheet can be its fifth link and 1.3 MB, with half a megabyte more behind it,
186
+ * and every color and font of the site is in it. So:
187
+ *
188
+ * - `firstLookBytes`: every link is first read this far. Most sheets end
189
+ * inside it, and those are done; a larger one shows here whether it declares
190
+ * `:root` custom properties, which they do at their top.
191
+ * - `budgetBytes`: what all the page's sheets may hold together, first looks
192
+ * included. Three times the sheet that set it, with room for what comes with
193
+ * it. What does not fit is cut, and a cut sheet is read as far as it goes.
194
+ * - `atOnce`: first looks asked together, so twenty links are not twenty
195
+ * connections to one host.
196
+ *
197
+ * So one page's read costs at most its links' first looks and the budget:
198
+ * 3.8 MB at the most links a page lists, however large its sheets are.
199
+ */
200
+ export declare const SITE_IMPORT_SHEET_LIMITS: {
201
+ readonly firstLookBytes: number;
202
+ readonly budgetBytes: number;
203
+ readonly atOnce: 6;
204
+ };
205
+ /** What a read of a stylesheet gives back. */
206
+ export interface SiteImportSheetAnswer {
207
+ ok: boolean;
208
+ text: string;
209
+ /** Bytes read. */
210
+ bytes: number;
211
+ /** Whether the sheet goes on past `maxBytes`. */
212
+ truncated: boolean;
213
+ }
214
+ /** Reads a stylesheet to a number of bytes; `null` where it cannot. */
215
+ export type SiteImportSheetRead = (url: string, maxBytes: number) => Promise<SiteImportSheetAnswer | null>;
216
+ /**
217
+ * Every stylesheet a page links, to a byte budget (AGL-4152), in link order,
218
+ * as the cascade needs them. Each is read a first look; then the ones that go
219
+ * on are read whole, the ones declaring `:root` custom properties first, then
220
+ * the rest in link order, each to what is left of the budget. A read that fails
221
+ * leaves its sheet out, and never the page.
222
+ */
223
+ export declare function siteImportReadStylesheets(urls: readonly string[], read: SiteImportSheetRead, options?: {
224
+ budgetBytes?: number;
225
+ outOfTime?: () => boolean;
226
+ }): Promise<string[]>;
139
227
  export {};