@aglyn/plugins-ai 1.12.0 → 1.14.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 (61) 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.js +11 -1
  7. package/src/lib/jobs/ai-job-import-step.js.map +1 -1
  8. package/src/lib/jobs/ai-site-import-compile.js +23 -3
  9. package/src/lib/jobs/ai-site-import-compile.js.map +1 -1
  10. package/src/lib/jobs/ai-site-import-look.d.ts +19 -4
  11. package/src/lib/jobs/ai-site-import-look.js +142 -45
  12. package/src/lib/jobs/ai-site-import-look.js.map +1 -1
  13. package/src/lib/jobs/ai-theme-brand-inputs.d.ts +12 -0
  14. package/src/lib/jobs/ai-theme-brand-inputs.js +1 -1
  15. package/src/lib/jobs/ai-theme-brand-inputs.js.map +1 -1
  16. package/src/lib/layout-language/ai-layout-compiler.js +90 -8
  17. package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
  18. package/src/lib/layout-language/ai-layout-language.d.ts +8 -2
  19. package/src/lib/layout-language/ai-layout-language.js +4 -2
  20. package/src/lib/layout-language/ai-layout-language.js.map +1 -1
  21. package/src/lib/model/ai-site-import-fidelity.d.ts +9 -0
  22. package/src/lib/model/ai-site-import-fidelity.js +64 -6
  23. package/src/lib/model/ai-site-import-fidelity.js.map +1 -1
  24. package/src/lib/model/ai-site-import.d.ts +36 -1
  25. package/src/lib/model/ai-site-import.js.map +1 -1
  26. package/src/lib/model/ai-upsell-copy.js +1 -1
  27. package/src/lib/model/ai-upsell-copy.js.map +1 -1
  28. package/src/lib/runtime/site-inventory.js +2 -3
  29. package/src/lib/runtime/site-inventory.js.map +1 -1
  30. package/src/lib/server/assist-view-context.js +3 -3
  31. package/src/lib/server/assist-view-context.js.map +1 -1
  32. package/src/lib/site-import/fixtures/site-import-fidelity-replay.d.ts +12 -1
  33. package/src/lib/site-import/fixtures/site-import-fidelity-replay.js +19 -9
  34. package/src/lib/site-import/fixtures/site-import-fidelity-replay.js.map +1 -1
  35. package/src/lib/site-import/fixtures/site-layout-recordings.d.ts +32 -0
  36. package/src/lib/site-import/fixtures/site-layout-recordings.js +55 -0
  37. package/src/lib/site-import/fixtures/site-layout-recordings.js.map +1 -1
  38. package/src/lib/site-import/site-import-concealed.d.ts +30 -0
  39. package/src/lib/site-import/site-import-concealed.js +231 -0
  40. package/src/lib/site-import/site-import-concealed.js.map +1 -0
  41. package/src/lib/site-import/site-import-crawl.d.ts +5 -1
  42. package/src/lib/site-import/site-import-crawl.js +35 -18
  43. package/src/lib/site-import/site-import-crawl.js.map +1 -1
  44. package/src/lib/site-import/site-import-css.d.ts +81 -0
  45. package/src/lib/site-import/site-import-css.js +456 -27
  46. package/src/lib/site-import/site-import-css.js.map +1 -1
  47. package/src/lib/site-import/site-import-data-forms.d.ts +32 -0
  48. package/src/lib/site-import/site-import-data-forms.js +531 -0
  49. package/src/lib/site-import/site-import-data-forms.js.map +1 -0
  50. package/src/lib/site-import/site-import-html.d.ts +36 -1
  51. package/src/lib/site-import/site-import-html.js +264 -54
  52. package/src/lib/site-import/site-import-html.js.map +1 -1
  53. package/src/lib/site-import/site-import-layout.d.ts +1 -1
  54. package/src/lib/site-import/site-import-layout.js +490 -44
  55. package/src/lib/site-import/site-import-layout.js.map +1 -1
  56. package/src/lib/site-import/site-import-nav.js +17 -3
  57. package/src/lib/site-import/site-import-nav.js.map +1 -1
  58. package/src/lib/site-import/site-import-page.js +2 -0
  59. package/src/lib/site-import/site-import-page.js.map +1 -1
  60. package/src/lib/testing/stand-in-dataset-index.js +6 -2
  61. package/src/lib/testing/stand-in-dataset-index.js.map +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/site-import/site-import-concealed.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 * WHAT A VISITOR CANNOT SEE IS NOT THE PAGE (AGL-4152).\n *\n * Read from what an element draws, through the page's own stylesheets, over\n * the structure a first walk of the page builds. The second walk leaves out\n * what this says, and only in a page's main region: a menu and a footer have\n * readers of their own.\n *\n * - **Drawn nowhere.** The `hidden` attribute, `display: none`,\n * `visibility: hidden`, a zero box, a `<dialog>` left shut. A template goes,\n * its picture and its words: a lightbox, an overlay, a drawer, a copy measured\n * out of sight. What a visitor opens stays: an accordion's answer, a tab, a\n * slide. So it stays where it holds words and no picture, or real words\n * beside its picture, or a form, or is a tab's panel, or is one of a set of\n * siblings built alike with one showing and says something else. Built alike\n * and saying the same, it is a copy for another screen, and goes.\n * - **Only heard.** Clipped to nothing, a one-pixel box, off-screen, or\n * `aria-hidden` (`sr-only` and its kin count with no sheet to say so). Its\n * words go. A picture under `aria-hidden` is still seen, and stays.\n * - **Waiting.** A lazy picture its own rule hides until it loads, or an element\n * hidden until its entrance plays, is shown to a visitor, and stays.\n * - **Going round.** Siblings that say the same again and again (a ticker) say\n * it once.\n *\n * Its other answer is where a text block breaks: an inline element set on a\n * line of its own, and the elements that keep the line breaks their words are\n * written with.\n *=========================================*/\n\nimport { siteImportCssOf, siteImportLengthPx, siteImportStylesOf, type SiteImportComputedStyle } from './site-import-css'\nimport type { SiteImportElement, SiteImportStructure } from './site-import-html'\n\n/** What a second walk of a page leaves out, and where its text blocks break, by element. */\nexport interface SiteImportConcealed {\n /** Drawn nowhere for anyone: its pictures and its words go. */\n gone: ReadonlySet<number>\n /** Only a screen reader hears it: its words go, its pictures stay. */\n unread: ReadonlySet<number>\n /** An inline element a text block sets on its own line. */\n lines: ReadonlySet<number>\n /** An element whose words keep the line breaks they are written with. */\n preserved: ReadonlySet<number>\n}\n\n/** The letters under a hidden element that make it a panel a visitor opens, not a template's \"Close\". */\nconst PANEL_MIN_LETTERS = 20\n\n/** The fewest letters a repeat must say to be a ticker going round, not a table's \"x\". */\nconst REPEAT_MIN_LETTERS = 3\n\n/** How far out of the page an element is set to be off-screen: past any screen's edge, or wholly past its own. */\nconst OFF_PAGE_PX = -999\n\n/** The convention for words only a screen reader hears, where no sheet says so. */\nconst ONLY_HEARD_CLASS = /(?:^|[\\s_-])(?:sr-only|screen-reader(?:-text|-only)?|visually-?hidden|visuallyhidden|assistive-text)(?:-focusable)?(?:\\s|$)/i\n\n/** An element waiting on an entrance a script plays: hidden only until then. */\nconst ENTRANCE_CLASS = /anim|invisible|reveal|fade|wow|aos/i\n\n/** Tags that hold words in a line, which a sheet may set on a line of their own. */\nconst INLINE_TAG = /^(?:span|b|strong|em|i|u|small|font|mark|abbr|cite)$/\n\n/** A grid of cells may say the same in each one and mean it. */\nconst CELLS_TAG = /^(?:table|thead|tbody|tfoot|tr|select|datalist)$/\n\nconst isOutOfFlow = (style: SiteImportComputedStyle) => /^(?:absolute|fixed)$/.test(style.get('position') ?? '')\n\n/** Whether a length sits past the page's edge. */\nfunction offPage(value: string | undefined): boolean {\n const text = value?.trim() ?? ''\n const percent = /^(-[\\d.]+)%$/.exec(text)\n if (percent) return Number(percent[1]) <= -100\n const px = text ? siteImportLengthPx(text) : null\n return px !== null && px <= OFF_PAGE_PX\n}\n\n/** Whether an element's box is nothing: nothing drawn, and nothing a padding opens. */\nfunction zeroBox(node: SiteImportElement, style: SiteImportComputedStyle): boolean {\n const width = siteImportLengthPx(style.get('width') ?? '')\n const height = siteImportLengthPx(style.get('height') ?? '')\n if (width !== 0 && height !== 0) return false\n if (node.tag !== 'img' && !/hidden|clip/.test(style.get('overflow') ?? '')) return false\n const open = (value: string | undefined) => !!value && (siteImportLengthPx(value) ?? 1) > 0\n return !['padding', 'padding-top', 'padding-bottom'].some((property) => open(style.get(property)?.split(/\\s+/)[0]))\n}\n\n/** Whether words are set where no visitor reads them: clipped to nothing, in a one-pixel box, or off-screen. */\nfunction onlyHeard(node: SiteImportElement, style: SiteImportComputedStyle): boolean {\n if (ONLY_HEARD_CLASS.test(node.attrs.class ?? '')) return true\n if (!isOutOfFlow(style)) return false\n // Clipped to a box of at most a pixel: `rect(0 0 0 0)`, `rect(1px, 1px, 1px, 1px)`.\n const clip = /^rect\\(([^)]*)\\)/.exec(style.get('clip') ?? '')\n if (clip && (clip[1]?.match(/[\\d.]+/g) ?? []).every((side) => Number(side) <= 1)) return true\n if (/^(?:inset\\((?:50|100)%\\)|circle\\(0(?:px|%)?\\))/.test(style.get('clip-path') ?? '')) return true\n const width = siteImportLengthPx(style.get('width') ?? '')\n const height = siteImportLengthPx(style.get('height') ?? '')\n if (width !== null && height !== null && width <= 1 && height <= 1) return true\n return ['left', 'right', 'top'].some((property) => offPage(style.get(property)))\n}\n\n/** A drawer set past the screen's edge, until something slides it in. */\nconst offCanvas = (style: SiteImportComputedStyle) => style.get('position') === 'fixed' && /translate(?:x|3d)?\\(\\s*-?100%/.test(style.get('transform') ?? '')\n\n/** What a page leaves out for a visitor, read through its own stylesheets; `null` where it leaves out nothing and breaks no block. */\nexport function siteImportConcealedOf(structure: SiteImportStructure, runs: ReadonlyMap<number, string>, stylesheets: readonly string[]): SiteImportConcealed | null {\n const { elements } = structure\n const styles = siteImportStylesOf(structure, siteImportCssOf([...structure.styles, ...stylesheets]))\n const gone = new Set<number>()\n const unread = new Set<number>()\n const lines = new Set<number>()\n const preserved = new Set<number>()\n /** Hidden by `visibility`, which a child may set back. */\n const byVisibility = new Set<number>()\n const panels = new Set(elements.flatMap((node) => (node.attrs.controls ? [node.attrs.controls] : [])))\n\n /** What an element says: its words, its pictures, its links, its icons, top to bottom. */\n const saidMemo = new Map<number, string>()\n const said = (id: number): string => {\n const held = saidMemo.get(id)\n if (held !== undefined) return held\n const node = elements[id] as SiteImportElement\n const parts = [runs.get(id) ?? '', node.picture ? `<${node.picture.url}>` : '', node.icon !== undefined ? `<icon ${node.icon}>` : '', node.tag === 'a' && node.attrs.href ? `<${node.attrs.href}>` : '', ...node.children.map(said)]\n const text = parts.join(' ').replace(/\\s+/g, ' ').trim()\n saidMemo.set(id, text)\n return text\n }\n const holdsForm = (id: number): boolean => {\n const node = elements[id] as SiteImportElement\n return node.form !== undefined || node.children.some(holdsForm)\n }\n const holdsPicture = (id: number): boolean => {\n const node = elements[id] as SiteImportElement\n return !!node.picture || node.children.some(holdsPicture)\n }\n const lettersIn = (text: string) => text.replace(/<[^>]*>/g, '').replace(/[^\\p{L}\\p{N}]/gu, '').length\n\n /** Whether an element is drawn nowhere by itself; what it inherits its parent answers for. */\n const notDrawn = (node: SiteImportElement, style: SiteImportComputedStyle): 'visibility' | 'box' | null => {\n if (node.attrs.notDrawn || style.get('display') === 'none' || (node.tag === 'dialog' && !node.attrs.open)) return 'box'\n if (zeroBox(node, style) || (node.tag === 'img' && node.attrs.tiny && !node.attrs.lazy)) return 'box'\n if (style.get('visibility') === 'hidden' && styles.of(node.parent).get('visibility') !== 'hidden') return 'visibility'\n return null\n }\n /** A shown sibling built alike, by a class they share, or by having none: a slide's neighbor, or the screen this one is a copy for. */\n const shownAlike = (node: SiteImportElement): SiteImportElement | null => {\n const classes = new Set((node.attrs.class ?? '').split(/\\s+/).filter(Boolean))\n const siblings = (node.parent >= 0 ? (elements[node.parent] as SiteImportElement).children : []).map((id) => elements[id] as SiteImportElement)\n const alike = siblings.filter((other) => other.id !== node.id && other.tag === node.tag && !other.attrs.ariaHidden && !notDrawn(other, styles.of(other.id)))\n return alike.find((other) => (other.attrs.class ?? '').split(/\\s+/).some((name) => classes.has(name))) ?? (classes.size === 0 ? (alike.find((other) => !other.attrs.class) ?? null) : null)\n }\n\n const subtree = (id: number, into: Set<number>) => {\n into.add(id)\n for (const child of (elements[id] as SiteImportElement).children) subtree(child, into)\n }\n\n for (const node of elements) {\n const style = styles.of(node.id)\n if (node.region !== 'main' || node.nav) continue\n if (/^pre(?:-wrap|-line)?$/.test(style.get('white-space') ?? '')) preserved.add(node.id)\n if (INLINE_TAG.test(node.tag) && /^(?:block|flex|grid|list-item|table)$/.test(style.get('display') ?? '')) lines.add(node.id)\n if (gone.has(node.parent)) {\n // `visibility` is the one way of hiding that a child may set back.\n if (!(byVisibility.has(node.parent) && style.get('visibility') === 'visible')) {\n gone.add(node.id)\n if (byVisibility.has(node.parent)) byVisibility.add(node.id)\n continue\n }\n }\n if (unread.has(node.parent)) unread.add(node.id)\n if (onlyHeard(node, style) || offCanvas(style)) {\n gone.add(node.id)\n continue\n }\n if (offPage(style.get('text-indent'))) unread.add(node.id)\n if (node.attrs.ariaHidden) {\n const beside = shownAlike(node)\n if (beside && said(beside.id) === said(node.id)) {\n gone.add(node.id)\n continue\n }\n // One of a set: the slide after the one showing, its words a visitor reads when it comes round.\n if (!beside || !node.attrs.class) unread.add(node.id)\n }\n // A lazy picture its own rule hides until it loads is on its way to a visitor.\n if (node.tag === 'img' && node.attrs.lazy) continue\n if (node.attrs.role === 'tabpanel' || (node.attrs.id && panels.has(node.attrs.id))) continue\n const hiddenBy = notDrawn(node, style)\n if (!hiddenBy) continue\n if (hiddenBy === 'visibility' && ENTRANCE_CLASS.test(node.attrs.class ?? '')) continue\n if (holdsForm(node.id)) continue\n // A dialog, what is fixed over the page, or what is measured out of sight: a template, never a panel of it.\n const overlay = node.tag === 'dialog' || /^(?:dialog|alertdialog)$/.test(node.attrs.role ?? '') || style.get('position') === 'fixed' || (hiddenBy === 'visibility' && isOutOfFlow(style))\n if (!overlay) {\n const beside = shownAlike(node)\n const copy = !!beside && said(beside.id) === said(node.id)\n // Not a copy: a slide of a set, or a panel a visitor opens.\n if (!copy && ((beside && node.attrs.class) || !holdsPicture(node.id) || lettersIn(said(node.id)) >= PANEL_MIN_LETTERS)) continue\n }\n gone.add(node.id)\n if (hiddenBy === 'visibility') byVisibility.add(node.id)\n }\n\n // Siblings that say the same again and again say it once: a ticker going round.\n for (const node of elements) {\n if (node.region !== 'main' || node.nav || gone.has(node.id) || CELLS_TAG.test(node.tag)) continue\n const saying = node.children.filter((child) => !gone.has(child) && !unread.has(child) && !!said(child))\n if (saying.length < 2) continue\n for (let period = 1; period * 2 <= saying.length; period += 1) {\n if (saying.some((child, at) => said(child) !== said(saying[at % period] as number))) continue\n if (lettersIn(saying.slice(0, period).map(said).join('')) < REPEAT_MIN_LETTERS) break\n for (const copy of saying.slice(period)) subtree(copy, gone)\n break\n }\n }\n\n return gone.size || unread.size || lines.size || preserved.size ? { gone, unread, lines, preserved } : null\n}\n"],"names":["siteImportCssOf","siteImportLengthPx","siteImportStylesOf","PANEL_MIN_LETTERS","REPEAT_MIN_LETTERS","OFF_PAGE_PX","ONLY_HEARD_CLASS","ENTRANCE_CLASS","INLINE_TAG","CELLS_TAG","isOutOfFlow","style","test","get","offPage","value","text","trim","percent","exec","Number","px","zeroBox","node","width","height","tag","open","some","property","split","onlyHeard","clip","attrs","class","match","every","side","offCanvas","siteImportConcealedOf","structure","runs","stylesheets","elements","styles","gone","Set","unread","lines","preserved","byVisibility","panels","flatMap","controls","saidMemo","Map","said","id","held","undefined","parts","picture","url","icon","href","children","map","join","replace","set","holdsForm","form","holdsPicture","lettersIn","length","notDrawn","tiny","lazy","of","parent","shownAlike","alike","classes","filter","Boolean","siblings","other","ariaHidden","find","name","has","size","subtree","into","add","child","region","nav","beside","role","hiddenBy","overlay","copy","saying","period","at","slice"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA2B2C,GAE3C,SAASA,eAAe,EAAEC,kBAAkB,EAAEC,kBAAkB,QAAsC,uBAAmB;AAezH,uGAAu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IQ,OAAO7B,MAAM,GAAG,GAAG;QACvB,IAAK,IAAI8B,SAAS,GAAGA,SAAS,KAAKD,OAAO7B,MAAM,EAAE8B,UAAU,EAAG;YAC7D,IAAID,OAAO3E,IAAI,CAAC,CAACmE,OAAOU,KAAOjD,KAAKuC,WAAWvC,KAAK+C,MAAM,CAACE,KAAKD,OAAO,IAAc;YACrF,IAAI/B,UAAU8B,OAAOG,KAAK,CAAC,GAAGF,QAAQtC,GAAG,CAACV,MAAMW,IAAI,CAAC,OAAO/D,oBAAoB;YAChF,KAAK,MAAMkG,QAAQC,OAAOG,KAAK,CAACF,QAASZ,QAAQU,MAAMzD;YACvD;QACF;IACF;IAEA,OAAOA,KAAK8C,IAAI,IAAI5C,OAAO4C,IAAI,IAAI3C,MAAM2C,IAAI,IAAI1C,UAAU0C,IAAI,GAAG;QAAE9C;QAAME;QAAQC;QAAOC;IAAU,IAAI;AACzG"}
@@ -16,7 +16,7 @@
16
16
  */
17
17
  import { type PublicFetchEdge, type PublicFetchOptions, type PublicFetchResult } from '../jobs/ai-theme-brand-inputs';
18
18
  import type { SiteImportFooter, SiteImportLayout, SiteImportLookFacts, SiteImportNavTree } from '../model/ai-site-import';
19
- import { type SiteImportBlock, type SiteImportBrandMark, type SiteImportForm, type SiteImportVideo, type SiteImportIcon, type SiteImportImage, type SiteImportNavLink, type SiteImportOrganization } from './site-import-html';
19
+ import { type SiteImportBlock, type SiteImportBrandMark, type SiteImportConcealedParts, type SiteImportForm, type SiteImportVideo, type SiteImportIcon, type SiteImportImage, type SiteImportNavLink, type SiteImportOrganization } from './site-import-html';
20
20
  /**
21
21
  * Where the bot's user agent points a site owner who wants to know what it is
22
22
  * (AGL-3983): the operator's own page about it. `SITE_IMPORT_BOT_INFO_URL` on
@@ -43,6 +43,8 @@ export declare const SITE_IMPORT_DEFAULTS: {
43
43
  readonly requestTimeoutMs: 8000;
44
44
  readonly robotsMaxBytes: number;
45
45
  readonly sitemapMaxBytes: number;
46
+ /** All the distinct stylesheets one crawl holds at once (AGL-4152): a site's pages share theirs, and one that does not stops here. */
47
+ readonly stylesheetsMaxBytes: number;
46
48
  /** Sitemap documents read, an index's children included: an index of six children is seven. */
47
49
  readonly maxSitemaps: 24;
48
50
  /** URLs a sitemap may contribute to the queue. */
@@ -85,6 +87,8 @@ export interface SiteImportSkipped {
85
87
  sameAs?: string;
86
88
  }
87
89
  export interface SiteImportPage {
90
+ /** What the page holds that a visitor cannot see (AGL-4152), which a build is held to not drawing. */
91
+ concealed?: SiteImportConcealedParts;
88
92
  /** The address the page was read from, after any same-site redirect. */
89
93
  url: string;
90
94
  path: string;
@@ -67,10 +67,11 @@ var _process_env_SITE_IMPORT_BOT_INFO_URL;
67
67
  * and a wave's read is exactly the pages it asks for.
68
68
  *=========================================*/ import { lookalikeBrandForHost } from "@aglyn/shared-util-email/outbound-phishing-screen";
69
69
  import { fenceUntrustedText } from "@aglyn/shared-util-tools/untrusted-text";
70
- import { AI_THEME_REFERENCE_STYLESHEETS, AI_THEME_STYLESHEET_MAX_BYTES, fetchPublicTextDetailed } from "../jobs/ai-theme-brand-inputs.js";
70
+ import { fetchPublicTextDetailed } from "../jobs/ai-theme-brand-inputs.js";
71
71
  import { extractSiteImportPage, readMetaValues } from "./site-import-html.js";
72
72
  import { AGLYN_BOT_TOKEN, parseRobotsTxt, parseSitemap, robotsAllows, robotsRulesFor } from "./site-import-robots.js";
73
73
  import { NO_SITE_IMPORT_HEADERS, siteImportEdgeHeadersFor } from "./site-import-edge.js";
74
+ import { siteImportReadStylesheets } from "./site-import-css.js";
74
75
  import { siteImportLayout, siteImportLookOf } from "./site-import-layout.js";
75
76
  import { siteImportAddressOf, siteImportCanonicalBelieved, siteImportCanonicalClaim, siteImportContentSignature, siteImportIsSystemScreen } from "./site-import-same-page.js";
76
77
  import { siteImportFooterColumns, siteImportNavTree } from "./site-import-nav.js";
@@ -96,6 +97,7 @@ export const SITE_IMPORT_DEFAULTS = {
96
97
  /** One request's own clock, inside the whole crawl's. */ requestTimeoutMs: 8000,
97
98
  robotsMaxBytes: 256 * 1024,
98
99
  sitemapMaxBytes: 4 * 1024 * 1024,
100
+ /** All the distinct stylesheets one crawl holds at once (AGL-4152): a site's pages share theirs, and one that does not stops here. */ stylesheetsMaxBytes: 32 * 1024 * 1024,
99
101
  /** Sitemap documents read, an index's children included: an index of six children is seven. */ maxSitemaps: 24,
100
102
  /** URLs a sitemap may contribute to the queue. */ maxSitemapUrls: 2000,
101
103
  /** Reasons kept in `skipped` before the list stops growing: every address a sitemap may name. */ maxSkipped: 2000,
@@ -220,17 +222,18 @@ function skipReasonFor(result) {
220
222
  const sameSite = (url)=>origins.includes(url.origin) && url.protocol === 'https:';
221
223
  const remainingBytes = ()=>maxTotalBytes - inventory.bytesRead;
222
224
  const outOfTime = ()=>controller.signal.aborted || now() >= deadlineAt;
223
- const request = (url, accept, acceptHeader, maxBytes)=>fetchText(url, {
225
+ /** 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. */ const request = (url, accept, acceptHeader, maxBytes, sheet = false)=>fetchText(url, _extends({
224
226
  maxBytes,
225
227
  accept,
226
228
  acceptHeader,
227
229
  userAgent: AGLYN_BOT_USER_AGENT,
228
230
  headersFor,
229
231
  signal: controller.signal,
230
- timeoutMs: Math.max(1, Math.min(SITE_IMPORT_DEFAULTS.requestTimeoutMs, deadlineAt - now())),
232
+ timeoutMs: Math.max(1, Math.min(SITE_IMPORT_DEFAULTS.requestTimeoutMs, deadlineAt - now()))
233
+ }, sheet ? {} : {
231
234
  redirectAllowed: (_from, to)=>sameSite(to),
232
235
  refuseOver: true
233
- });
236
+ }));
234
237
  /** Addresses taken in, read or not: one a page is waiting on that is here and is no page will never be. */ const takenIn = new Set();
235
238
  const skip = (entry)=>{
236
239
  takenIn.add(siteImportAddressOf(entry.url));
@@ -413,18 +416,24 @@ function skipReasonFor(result) {
413
416
  }
414
417
  };
415
418
  const readLayout = (_options_layout = options.layout) != null ? _options_layout : !!only;
416
- /** Linked stylesheets, each asked once a crawl. */ const sheets = new Map();
417
- const stylesheet = (url)=>{
419
+ /** Linked stylesheets, as far as any page has read each: a sheet a page shares is asked no further than it was. */ const sheets = new Map();
420
+ let sheetBytes = 0;
421
+ const stylesheet = async (url, maxBytes)=>{
422
+ var _ref, _ref1, _ref2, _ref3, _ref4;
423
+ var _held_answer, _held_answer1;
418
424
  const held = sheets.get(url);
419
- if (held) return held;
420
- const room = Math.min(AI_THEME_STYLESHEET_MAX_BYTES, remainingBytes() - reserved);
421
- const asked = room <= 0 || outOfTime() ? Promise.resolve(null) : request(url, /text\/css|text\/plain/i, 'text/css,*/*;q=0.1', room).then((answer)=>{
422
- if (!answer.ok) return null;
423
- inventory.bytesRead += answer.bytes;
424
- return answer.text;
425
- }, ()=>null);
426
- sheets.set(url, asked);
427
- return asked;
425
+ if (held && (held.asked >= maxBytes || held.answer && !held.answer.truncated)) return held.answer;
426
+ const room = Math.min(maxBytes, SITE_IMPORT_DEFAULTS.stylesheetsMaxBytes - sheetBytes + ((_ref = held == null ? void 0 : (_held_answer = held.answer) == null ? void 0 : _held_answer.bytes) != null ? _ref : 0), remainingBytes() - reserved);
427
+ if (room <= 0 || outOfTime()) return (_ref1 = held == null ? void 0 : held.answer) != null ? _ref1 : null;
428
+ const read = await request(url, /text\/css|text\/plain/i, 'text/css,*/*;q=0.1', room, true).catch(()=>null);
429
+ if (read == null ? void 0 : read.ok) inventory.bytesRead += read.bytes;
430
+ const answer = (read == null ? void 0 : read.ok) ? read : (_ref2 = held == null ? void 0 : held.answer) != null ? _ref2 : null;
431
+ sheetBytes += ((_ref3 = answer == null ? void 0 : answer.bytes) != null ? _ref3 : 0) - ((_ref4 = held == null ? void 0 : (_held_answer1 = held.answer) == null ? void 0 : _held_answer1.bytes) != null ? _ref4 : 0);
432
+ sheets.set(url, {
433
+ asked: room,
434
+ answer
435
+ });
436
+ return answer;
428
437
  };
429
438
  /** Takes one asked page in: the inventory's next page, a skip, or the reason the read must stop. */ const takeIn = async ({ next, key, cap, page })=>{
430
439
  var _siteImportPageKey;
@@ -471,7 +480,7 @@ function skipReasonFor(result) {
471
480
  }
472
481
  const isHome = foundBy === 'home';
473
482
  const structured = readLayout || isHome;
474
- const extract = extractSiteImportPage(page.text, page.url, sameSite, {
483
+ let extract = extractSiteImportPage(page.text, page.url, sameSite, {
475
484
  structure: structured
476
485
  });
477
486
  if (extract.loginForm) {
@@ -515,8 +524,14 @@ function skipReasonFor(result) {
515
524
  // How the page is built (AGL-4106), through its own stylesheets.
516
525
  let built = {};
517
526
  if (extract.structure) {
518
- const linked = await Promise.all(extract.structure.stylesheets.filter((url)=>!/fonts\.googleapis\.com/i.test(url)).slice(0, AI_THEME_REFERENCE_STYLESHEETS).map(stylesheet));
519
- const css = linked.filter((text)=>typeof text === 'string');
527
+ const css = await siteImportReadStylesheets(extract.structure.stylesheets.filter((url)=>!/fonts\.googleapis\.com/i.test(url)), stylesheet, {
528
+ outOfTime
529
+ });
530
+ // Read again through them (AGL-4152): what a visitor cannot see is often only their rule's to say.
531
+ if (css.length) extract = extractSiteImportPage(page.text, page.url, sameSite, {
532
+ structure: structured,
533
+ stylesheets: css
534
+ });
520
535
  const source = _extends({
521
536
  blocks: extract.blocks,
522
537
  organization: extract.organization,
@@ -562,6 +577,8 @@ function skipReasonFor(result) {
562
577
  forms: extract.forms
563
578
  }, extract.videos ? {
564
579
  videos: extract.videos
580
+ } : {}, extract.concealed ? {
581
+ concealed: extract.concealed
565
582
  } : {}, {
566
583
  bytes: page.bytes
567
584
  });
@@ -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 * - **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 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 {\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 /** 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 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 /** 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, 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 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 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 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","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","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","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","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","stylesheet","asked","Promise","resolve","then","answer","takeIn","cap","edge","finalKey","isHome","structured","extract","structure","loginForm","links","link","linkKey","own","canonical","built","linked","all","stylesheets","slice","css","source","blocks","organization","videos","nav","footer","look","taken","path","title","description","lang","ogImage","siteName","icons","brand","images","navLinks","forms","unshift","width","why","unread","clearTimeout","removeEventListener","readSiteVerificationMeta","metaName","answered","values","head","siteImportPagePromptText","maxChars","lines","block","kind","repeat","level","alt","inline","join"],"mappings":";IA2HEA;AA3HF;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAkD2C,GAE3C,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SAASC,kBAAkB,QAAQ,0CAAyC;AAC5E,SACEC,8BAA8B,EAC9BC,6BAA6B,EAC7BC,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,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,sBACXxB,wCAAAA,QAAQyB,GAAG,CAAC,2BAA2B,YAAvCzB,wCAA2C,0CAAyC;AAEtF,2CAA2C,GAC3C,OAAO,MAAM0B,uBAAuB,CAAC,eAAe,EAAEF,mBAAmB,CAAC,CAAC,CAAA;AAE3E,OAAO,MAAMG,uBAAuB;IAClCC,cAAc,IAAI,OAAO;IACzB;;;GAGC,GACDC,eAAe,MA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CAAC,CAAC,EAAE,EAAEqI,MAAM/H,IAAI,EAAE;aAC5D,IAAI+H,MAAMC,IAAI,KAAK,SAASF,MAAMpI,IAAI,CAAC,CAAC,EAAE,EAAEqI,MAAM/H,IAAI,EAAE;aACxD,IAAI+H,MAAMC,IAAI,KAAK,QAAQ;YAC9B,4DAA4D;YAC5D,IAAI,CAACD,MAAMK,MAAM,EAAEN,MAAMpI,IAAI,CAACqI,MAAM/H,IAAI;QAC1C,OAAO8H,MAAMpI,IAAI,CAACqI,MAAM/H,IAAI;IAC9B;IACA,OAAO7I,mBAAmB,CAAC,KAAK,EAAE+L,KAAKoD,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 SiteImportConcealedParts,\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 /** What the page holds that a visitor cannot see (AGL-4152), which a build is held to not drawing. */\n concealed?: SiteImportConcealedParts\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 let 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 // Read again through them (AGL-4152): what a visitor cannot see is often only their rule's to say.\n if (css.length) extract = extractSiteImportPage(page.text, page.url, sameSite, { structure: structured, stylesheets: css })\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 ...(extract.concealed ? { concealed: extract.concealed } : {}),\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","concealed","unshift","width","why","then","unread","clearTimeout","removeEventListener","readSiteVerificationMeta","metaName","answered","values","head","siteImportPagePromptText","maxChars","lines","block","kind","repeat","level","alt","inline","join"],"mappings":";IA2HEA;AA3HF;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAkD2C,GAE3C,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SAASC,kBAAkB,QAAQ,0CAAyC;AAC5E,SACEC,uBAAuB,QAIlB,mCAA+B;AAEtC,SACEC,qBAAqB,EACrBC,cAAc,QAUT,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,OAAO,MAAMyB,uBAAuB,CAAC,eAAe,EAAEF,mBAAmB,CAAC,CAAC,CAAA;AAE3E,OAAO,MAAMG,uBAAuB;IAClCC,cAAc,IAAI,OAA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