Documentation
¶
Overview ¶
Package extract converts raw HTML and PDF payloads into clean GitHub-Flavored Markdown, plain text, resolved links, images, CSS branding signals, BM25 query-reranked passages, and `llms.txt` structured discovery metadata using only the Go standard library.
Extraction Pipeline ¶
- Head metadata & branding signals (`<title>`, OpenGraph, canonical URL, favicon, CSS hex palette, fonts).
- Boilerplate & chrome removal (`<nav>`, `<footer>`, `<aside>`, `<script>`, `<style>`) with `<main>` / `<article>` focus when `OnlyMainContent` is enabled.
- Sentinel-protected `<pre><code>` and multi-backtick inline `<code>` conversion so generic type signatures (`Promise<void>`, `#include <stdio.h>`) survive HTML tag stripping intact.
- GFM table reconstruction, optional BM25 passage reranking (RerankPassages), and optional PII redaction (RedactPII).
- Streaming Poppler `pdftotext -layout` extraction with a pure-Go FlateDecode fallback (ExtractPDFText) for distroless Lite deployments.
Index ¶
- func CandidateCompanionMarkdownURL(pageURL string) string
- func DetectRenderedChallenge(rawHTML string) string
- func ExtractPDFFileText(ctx context.Context, pdfPath string, maxPages int) (text string, usedPoppler bool, err error)
- func ExtractPDFText(ctx context.Context, pdfBytes []byte, maxPages int) (text string, usedPoppler bool, err error)
- func GetRegistrableDomain(host string) string
- func HasPDFToText() bool
- func HasPrivateSharedHostingSuffix(host string) bool
- func IsPDFBytes(data []byte) bool
- func IsPublicOrPrivateSuffix(host string) bool
- func MatchesApprovedWildcard(rawWildcard, rawCandidate string) bool
- func NeedsBrowserRender(rawHTML string) bool
- func ParseDeclarativeYAML(raw []byte) (any, error)
- func PlainText(rawHTML string) string
- func RedactPII(s string) string
- func RerankPassages(doc, query string, maxChars int) string
- func SanitizeMarkdown(md, baseURL string) string
- func SanitizeMarkdownWithOptions(md, baseURL string, allowPdfPageMarkers bool) string
- func SanitizeScrapedMarkdown(md string) string
- func SanitizeScrapedMeta(s string) string
- func ValidateDeclarativeManifests(manifests []DeclarativeAdapterManifest) error
- func YAMLToJSON(raw []byte) ([]byte, error)
- type BrandingProfile
- type DeclarativeAdapterManifest
- type DeclarativeAdapterSummary
- type DeclarativeBulletSpec
- type DeclarativeCatalogConfig
- type DeclarativeCodeByPathSpec
- type DeclarativeDedupeSpec
- type DeclarativeDerivedParamSpec
- type DeclarativeDynamicKeyPath
- type DeclarativeExtractSpec
- type DeclarativeFindInArray
- type DeclarativeFindLangSpec
- type DeclarativeFormattedDoc
- type DeclarativeHTMLRouteSpec
- type DeclarativeHTMLVarSpec
- type DeclarativeHostMapSpec
- type DeclarativeHostSubdomainSpec
- type DeclarativeManifest
- type DeclarativeMatchSpec
- type DeclarativeNestedSubValuesSpec
- type DeclarativePaginationMetaSpec
- type DeclarativeParallelArraysSpec
- type DeclarativeParamSegment
- type DeclarativePathOverrideSpec
- type DeclarativeQueryParamSpec
- type DeclarativeReplaceSpec
- type DeclarativeRouteSpec
- type DeclarativeScanSegmentSpec
- type DeclarativeSectionFilterSpec
- type DeclarativeSectionSpec
- type DeclarativeSegmentSpec
- type DeclarativeSortSpec
- type DeclarativeSplitSegmentSpec
- type DeclarativeSubFieldsJoin
- type DeclarativeTableColumn
- type DeclarativeTreeCommentsSpec
- type DeclarativeTwinMatch
- type DeclarativeTwinSpec
- type DeclarativeVarSpec
- type DeclarativeXMLColumnSpec
- type DeclarativeXMLItemVarSpec
- type DeclarativeXMLSpec
- type ExtractOptions
- type ImageInfo
- type LlmsDiscovery
- type LlmsDocument
- type LlmsLink
- type PageExtraction
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CandidateCompanionMarkdownURL ¶
CandidateCompanionMarkdownURL returns `<url>.md` when `pageURL` looks like a clean documentation/article path (e.g. `https://developers.cloudflare.com/workers/wrangler` -> `https://developers.cloudflare.com/workers/wrangler.md`).
func DetectRenderedChallenge ¶
DetectRenderedChallenge checks whether an HTML payload (HTTP or headless browser) is gated by a bot/CAPTCHA challenge. Delegates to `classify.ClassifyWAF` (`R2` & `R3`) so all 4 anti-false-positive guardrails (visible word-count veto, Schema.org JSON-LD veto, `<pre>`/`<code>` immunity, and `<nav>` landmark veto) protect rendered pages too.
func ExtractPDFFileText ¶
func ExtractPDFFileText(ctx context.Context, pdfPath string, maxPages int) (text string, usedPoppler bool, err error)
ExtractPDFFileText extracts UTF-8 text from an on-disk PDF file up to `maxPages` (default 60) using `pdftotext` (`poppler-utils`), falling back to a bounded pure-Go FlateDecode stream reader when `pdftotext` is absent. Reading from a seekable file path allows Poppler to seek directly to the PDF `xref` trailer at EOF without buffering large manuals in RAM.
func ExtractPDFText ¶
func ExtractPDFText(ctx context.Context, pdfBytes []byte, maxPages int) (text string, usedPoppler bool, err error)
ExtractPDFText extracts UTF-8 text from `pdfBytes` up to `maxPages` (default 60). When `pdftotext` (`poppler-utils`) is installed, it streams `pdfBytes` directly over stdin into `pdftotext -layout` (zero temporary files on disk). On distroless Lite nodes without `pdftotext`, it falls back to a pure-Go FlateDecode content-stream text reader so PDF fetches remain functional everywhere.
func GetRegistrableDomain ¶ added in v2.7.2
GetRegistrableDomain returns the eTLD+1 registrable domain (or "" if host is itself a public/private suffix or invalid).
func HasPDFToText ¶
func HasPDFToText() bool
HasPDFToText reports whether `pdftotext` (`poppler-utils`, bundled in the browser/PDF worker image) is available in $PATH.
func HasPrivateSharedHostingSuffix ¶ added in v2.7.2
HasPrivateSharedHostingSuffix reports whether host matches a rule from the Mozilla PSL PRIVATE DOMAINS section.
func IsPDFBytes ¶
IsPDFBytes checks whether `data` starts with `%PDF-` within the first 1024 bytes (per PDF spec §7.5.2).
func IsPublicOrPrivateSuffix ¶ added in v2.7.2
IsPublicOrPrivateSuffix reports whether host is itself a public or private suffix (or unregistrable).
func MatchesApprovedWildcard ¶ added in v2.7.2
MatchesApprovedWildcard reports whether candidate (an exact domain or wildcard pattern) matches one of the 3 allowlisted wildcard shapes (`*.suffix`, `gitlab.*`, `careers.*.com` / `jobs.*.com`).
func NeedsBrowserRender ¶
NeedsBrowserRender heuristics detect empty client-side SPA shells (`<div id="root"></div>` + script bundles with almost zero SSR body text) so `renderMode: "auto"` only launches Chromium when static HTTP/2 lacks content.
func ParseDeclarativeYAML ¶ added in v2.6.2
ParseDeclarativeYAML parses a safe YAML 1.2 Core Schema subset into standard Go JSON-compatible values (`map[string]any`, `[]any`, `string`, `bool`, `json.Number`, `nil`). Explicitly rejects YAML anchors (`&`), aliases (`*`), merge keys (`<<`), custom tags (`!`), and tab indentation.
func RedactPII ¶
RedactPII replaces email addresses, SSNs, phone numbers, and Luhn-valid payment card numbers with `[REDACTED_*]`.
func RerankPassages ¶
RerankPassages splits long Markdown or PDF text into semantic paragraphs/sections and selects the top chunks matching `query` via BM25-style term scoring + exact-phrase boost while preserving original document reading order.
func SanitizeMarkdown ¶ added in v2.7.2
SanitizeMarkdown enforces the fail-closed Markdown sanitization contract:
- Outside recognized CommonMark fenced code blocks (strictly top-level 0..3 column or verified list-item content-column+0..3 backtick/tilde fences, never blockquote `> ``` ` or same-line `- ``` ` fences), EVERY residual `<` is escaped to `<` and EVERY disallowed inline `](...)` or reference `[id]: ...` link destination is neutralized — INCLUDING inside inline backtick code spans “ `...` “!
- Runs in strictly O(N) linear time (<40ms on 7M `[` / 3.5M `](` / 2M `<`).
func SanitizeMarkdownWithOptions ¶ added in v2.7.2
SanitizeMarkdownWithOptions sanitizes Markdown with optional PDF page marker preservation.
func SanitizeScrapedMarkdown ¶ added in v2.6.3
SanitizeScrapedMarkdown applies the fail-closed Markdown sanitizer with empty baseURL.
func SanitizeScrapedMeta ¶ added in v2.6.3
SanitizeScrapedMeta strips NUL/smuggling code points, control newlines, raw HTML tags, and disallowed link schemes from single-line metadata fields (Title, Description, Author).
func ValidateDeclarativeManifests ¶ added in v2.7.2
func ValidateDeclarativeManifests(manifests []DeclarativeAdapterManifest) error
ValidateDeclarativeManifests enforces full compiler-equivalent security invariants across a manifest slice: per-manifest schema/host/twin/catalog validation, approved wildcard allowlist, reserved core ATS domains, exactOwners uniqueness + MatchesApprovedWildcard collision rejection, and same-registrable-domain twin.fetchUrl checks (H7).
func YAMLToJSON ¶ added in v2.6.2
YAMLToJSON converts a safe YAML document into canonical UTF-8 JSON bytes.
Types ¶
type BrandingProfile ¶
type BrandingProfile struct {
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
CanonicalURL string `json:"canonicalUrl,omitempty"`
Favicon string `json:"favicon,omitempty"`
Logo string `json:"logo,omitempty"`
OGImage string `json:"ogImage,omitempty"`
ThemeColor string `json:"themeColor,omitempty"`
Colors []string `json:"colors,omitempty"`
Fonts []string `json:"fonts,omitempty"`
}
BrandingProfile summarizes visual brand identity signals extracted from HTML/CSS (`formats: ["branding"]`).
type DeclarativeAdapterManifest ¶ added in v2.6.2
type DeclarativeAdapterManifest struct {
ID string `json:"id"`
Name string `json:"name"`
Category string `json:"category"`
Description string `json:"description"`
Domains []string `json:"domains"`
UniversalEngine bool `json:"universalEngine,omitempty"`
ExampleURLs []string `json:"exampleUrls"`
Match *DeclarativeMatchSpec `json:"match,omitempty"`
Twin *DeclarativeTwinSpec `json:"twin,omitempty"`
Extract *DeclarativeExtractSpec `json:"extract,omitempty"`
Routes []DeclarativeRouteSpec `json:"routes,omitempty"`
HTMLRoutes []DeclarativeHTMLRouteSpec `json:"htmlRoutes,omitempty"`
Catalog *DeclarativeCatalogConfig `json:"catalog,omitempty"`
}
DeclarativeAdapterManifest is the canonical shared Go + TypeScript declarative YAML v2 adapter contract.
func ParseDeclarativeManifest ¶ added in v2.6.2
func ParseDeclarativeManifest(raw []byte) (*DeclarativeAdapterManifest, error)
ParseDeclarativeManifest parses and strictly validates a single declarative JSON manifest.
func ParseDeclarativeYAMLManifest ¶ added in v2.6.2
func ParseDeclarativeYAMLManifest(raw []byte) (*DeclarativeAdapterManifest, error)
ParseDeclarativeYAMLManifest parses and validates a declarative YAML manifest (explicitly rejecting anchors, aliases, merge keys, and non-ASCII keys).
type DeclarativeAdapterSummary ¶ added in v2.6.2
type DeclarativeAdapterSummary struct {
ID string `json:"id"`
Name string `json:"name"`
Category string `json:"category"`
Description string `json:"description"`
Modes []string `json:"modes"`
Domains []string `json:"domains"`
UniversalEngine bool `json:"universalEngine"`
ExampleURLs []string `json:"exampleUrls"`
}
DeclarativeAdapterSummary describes an embedded declarative site adapter in `GET /v1/extractors` and MCP `find_extractors`.
func FindDeclarativeAdapters ¶ added in v2.6.2
func FindDeclarativeAdapters(query, category string, limit int) []DeclarativeAdapterSummary
FindDeclarativeAdapters filters and ranks embedded declarative site adapters by optional query and category.
func ListDeclarativeAdapters ¶ added in v2.6.2
func ListDeclarativeAdapters() []DeclarativeAdapterSummary
ListDeclarativeAdapters returns metadata summaries for all embedded declarative site adapters.
type DeclarativeBulletSpec ¶ added in v2.6.2
type DeclarativeBulletSpec struct {
Label string `json:"label,omitempty"`
Template string `json:"template"`
WhenVar string `json:"whenVar,omitempty"`
UnlessVar string `json:"unlessVar,omitempty"`
}
DeclarativeBulletSpec renders `- **<Label>**: <Template>` (or `**<Label>**: <Template>` in metaLine).
type DeclarativeCatalogConfig ¶ added in v2.6.3
type DeclarativeCatalogConfig struct {
Platform string `json:"platform"`
PauseMs int `json:"pauseMs"`
PageCap int `json:"pageCap"`
FirstPageTemplate string `json:"firstPageTemplate,omitempty"`
CollectionPageTemplate string `json:"collectionPageTemplate,omitempty"`
PerPage int `json:"perPage,omitempty"`
MaxVariantsPerProduct int `json:"maxVariantsPerProduct,omitempty"`
MaxImagesPerProduct int `json:"maxImagesPerProduct,omitempty"`
}
DeclarativeCatalogConfig defines polite full-store catalog pagination (`shopify`, `woocommerce`).
type DeclarativeCodeByPathSpec ¶ added in v2.6.3
type DeclarativeCodeByPathSpec struct {
SourceVar string `json:"sourceVar"`
PathParam string `json:"pathParam"`
RawIfMarkdown bool `json:"rawIfMarkdown,omitempty"`
}
DeclarativeCodeByPathSpec formats a code/markdown variable using the file extension from a path parameter.
type DeclarativeDedupeSpec ¶ added in v2.6.3
type DeclarativeDedupeSpec struct {
KeyPaths []string `json:"keyPaths"`
MergeTextPaths []string `json:"mergeTextPaths,omitempty"`
MergeTargetVar string `json:"mergeTargetVar,omitempty"`
MergeSep string `json:"mergeSep,omitempty"`
MergeLimit int `json:"mergeLimit,omitempty"`
OrBoolPaths []string `json:"orBoolPaths,omitempty"`
OrBoolTargetField string `json:"orBoolTargetField,omitempty"`
}
DeclarativeDedupeSpec merges multi-location duplicate rows (e.g. Rippling uuid, Workable shortcode).
type DeclarativeDerivedParamSpec ¶ added in v2.6.3
type DeclarativeDerivedParamSpec struct {
FromParam string `json:"fromParam"`
Transform string `json:"transform"`
}
DeclarativeDerivedParamSpec computes a derived parameter from an existing captured parameter.
type DeclarativeDynamicKeyPath ¶ added in v2.6.2
type DeclarativeDynamicKeyPath struct {
Base string `json:"base"`
KeyVar string `json:"keyVar"`
SubPath string `json:"subPath,omitempty"`
}
DeclarativeDynamicKeyPath looks up root[Base][vars[KeyVar]][SubPath].
type DeclarativeExtractSpec ¶ added in v2.6.2
type DeclarativeExtractSpec struct {
CommerceMode string `json:"commerceMode,omitempty"`
IcimsPortal bool `json:"icimsPortal,omitempty"`
TextMode string `json:"textMode,omitempty"`
PathParam string `json:"pathParam,omitempty"`
XML *DeclarativeXMLSpec `json:"xml,omitempty"`
JSONSource string `json:"jsonSource,omitempty"`
WrapRootArrayAs string `json:"wrapRootArrayAs,omitempty"`
UnwrapFirstArrayElement bool `json:"unwrapFirstArrayElement,omitempty"`
RootPath string `json:"rootPath,omitempty"`
RejectIfFieldTruthy string `json:"rejectIfFieldTruthy,omitempty"`
RequireFieldEquals *struct {
Path string `json:"path"`
Value string `json:"value"`
} `json:"requireFieldEquals,omitempty"`
RequireArrayItemField *struct {
ArrayPath string `json:"arrayPath"`
Field string `json:"field"`
} `json:"requireArrayItemField,omitempty"`
FindInArray *DeclarativeFindInArray `json:"findInArray,omitempty"`
FallbackExtract *DeclarativeExtractSpec `json:"fallbackExtract,omitempty"`
RequireFields []string `json:"requireFields,omitempty"`
RequireAnyFields []string `json:"requireAnyFields,omitempty"`
RequireVars []string `json:"requireVars,omitempty"`
Vars map[string]DeclarativeVarSpec `json:"vars,omitempty"`
CodeByPath *DeclarativeCodeByPathSpec `json:"codeByPath,omitempty"`
TitleTemplate string `json:"titleTemplate,omitempty"`
TitleWhenVar string `json:"titleWhenVar,omitempty"`
TitleFallbackTemplate string `json:"titleFallbackTemplate,omitempty"`
DescriptionVar string `json:"descriptionVar,omitempty"`
DescriptionTemplate string `json:"descriptionTemplate,omitempty"`
AuthorVar string `json:"authorVar,omitempty"`
AuthorTemplate string `json:"authorTemplate,omitempty"`
PublishedTimeVar string `json:"publishedTimeVar,omitempty"`
BlockquoteTemplate string `json:"blockquoteTemplate,omitempty"`
BlockquoteWhenVar string `json:"blockquoteWhenVar,omitempty"`
MetaLine []DeclarativeBulletSpec `json:"metaLine,omitempty"`
MetaLineItalic bool `json:"metaLineItalic,omitempty"`
IntroVar string `json:"introVar,omitempty"`
Bullets []DeclarativeBulletSpec `json:"bullets,omitempty"`
ObjectLinksPath string `json:"objectLinksPath,omitempty"`
BodyVar string `json:"bodyVar,omitempty"`
Sections []DeclarativeSectionSpec `json:"sections,omitempty"`
LinksVars []string `json:"linksVars,omitempty"`
LinkTemplates []string `json:"linkTemplates,omitempty"`
}
DeclarativeExtractSpec defines how a JSON, XML, or text twin payload is converted into Markdown and metadata.
type DeclarativeFindInArray ¶ added in v2.6.2
type DeclarativeFindInArray struct {
ArrayPath string `json:"arrayPath"`
MatchField string `json:"matchField,omitempty"`
MatchFields []string `json:"matchFields,omitempty"`
EndsWithField string `json:"endsWithField,omitempty"`
MatchTemplate string `json:"matchTemplate"`
EndsWithTemplate string `json:"endsWithTemplate,omitempty"`
IgnoreCase bool `json:"ignoreCase,omitempty"`
}
DeclarativeFindInArray selects a matching element from a JSON array to serve as the active root object.
type DeclarativeFindLangSpec ¶ added in v2.6.3
type DeclarativeFindLangSpec struct {
ArrayPath string `json:"arrayPath"`
LangField string `json:"langField"`
LangValue string `json:"langValue"`
ValueField string `json:"valueField"`
}
DeclarativeFindLangSpec selects a localized string from an array of `{ lang, value }` objects.
type DeclarativeFormattedDoc ¶ added in v2.6.2
type DeclarativeFormattedDoc struct {
Title string `json:"title"`
Description string `json:"description,omitempty"`
Author string `json:"author,omitempty"`
PublishedTime string `json:"publishedTime,omitempty"`
Markdown string `json:"markdown"`
Links []string `json:"links,omitempty"`
}
DeclarativeFormattedDoc holds the structured Markdown and metadata produced from a declarative twin payload.
type DeclarativeHTMLRouteSpec ¶ added in v2.6.3
type DeclarativeHTMLRouteSpec struct {
ID string `json:"id,omitempty"`
Match DeclarativeMatchSpec `json:"match"`
Mode string `json:"mode"`
JSONLdTypes []string `json:"jsonLdTypes,omitempty"`
EmbeddedBalancedKey string `json:"embeddedBalancedKey,omitempty"`
Vars map[string]DeclarativeHTMLVarSpec `json:"vars,omitempty"`
RequireVars []string `json:"requireVars,omitempty"`
RequireBulletsOrVars []string `json:"requireBulletsOrVars,omitempty"`
TitleTemplate string `json:"titleTemplate,omitempty"`
TitleWhenVar string `json:"titleWhenVar,omitempty"`
TitleFallbackTemplate string `json:"titleFallbackTemplate,omitempty"`
DescriptionVar string `json:"descriptionVar,omitempty"`
AuthorVar string `json:"authorVar,omitempty"`
PublishedTimeVar string `json:"publishedTimeVar,omitempty"`
BlockquoteTemplate string `json:"blockquoteTemplate,omitempty"`
BlockquoteWhenVar string `json:"blockquoteWhenVar,omitempty"`
MetaItalicTemplate string `json:"metaItalicTemplate,omitempty"`
MetaItalicWhenVar string `json:"metaItalicWhenVar,omitempty"`
IntroVar string `json:"introVar,omitempty"`
Bullets []DeclarativeBulletSpec `json:"bullets,omitempty"`
BodyVar string `json:"bodyVar,omitempty"`
BodyFallbackHeading string `json:"bodyFallbackHeading,omitempty"`
Sections []struct {
Heading string `json:"heading"`
TextVar string `json:"textVar"`
} `json:"sections,omitempty"`
AppendCurrentMdDelta *struct {
BaseVar string `json:"baseVar,omitempty"`
MinExtraChars int `json:"minExtraChars"`
} `json:"appendCurrentMdDelta,omitempty"`
LinkTemplates []string `json:"linkTemplates,omitempty"`
PreserveBodyLinksFromVar string `json:"preserveBodyLinksFromVar,omitempty"`
ScriptID string `json:"scriptId,omitempty"`
DataAttr string `json:"dataAttr,omitempty"`
Extract *DeclarativeExtractSpec `json:"extract,omitempty"`
XML *DeclarativeXMLSpec `json:"xml,omitempty"`
CleanPreset string `json:"cleanPreset,omitempty"`
}
DeclarativeHTMLRouteSpec defines a post-fetch HTML extraction rule in YAML manifests.
type DeclarativeHTMLVarSpec ¶ added in v2.6.3
type DeclarativeHTMLVarSpec struct {
JSONLdPaths []string `json:"jsonLdPaths,omitempty"`
EmbeddedPaths []string `json:"embeddedPaths,omitempty"`
MetaKeys []string `json:"metaKeys,omitempty"`
AllMetaKey string `json:"allMetaKey,omitempty"`
CSSText []string `json:"cssText,omitempty"`
CSSAttr *struct {
Selector string `json:"selector"`
Attr string `json:"attr"`
} `json:"cssAttr,omitempty"`
CSSAllText *struct {
Selector string `json:"selector"`
Limit int `json:"limit,omitempty"`
Dedupe *bool `json:"dedupe,omitempty"`
Join string `json:"join,omitempty"`
} `json:"cssAllText,omitempty"`
CSSHTMLToMd []string `json:"cssHtmlToMd,omitempty"`
RegexExtract *struct {
Source string `json:"source"`
Pattern string `json:"pattern"`
Group int `json:"group,omitempty"`
Transform string `json:"transform,omitempty"`
} `json:"regexExtract,omitempty"`
Template string `json:"template,omitempty"`
WhenVars []string `json:"whenVars,omitempty"`
WhenAnyVars []string `json:"whenAnyVars,omitempty"`
FallbackVar string `json:"fallbackVar,omitempty"`
FallbackTemplate string `json:"fallbackTemplate,omitempty"`
Default string `json:"default,omitempty"`
Join string `json:"join,omitempty"`
Limit int `json:"limit,omitempty"`
Format string `json:"format,omitempty"`
CurrencyVar string `json:"currencyVar,omitempty"`
StripPrefix string `json:"stripPrefix,omitempty"`
StripSuffix string `json:"stripSuffix,omitempty"`
StripRegexSuffix string `json:"stripRegexSuffix,omitempty"`
ReplaceAll *DeclarativeReplaceSpec `json:"replaceAll,omitempty"`
SliceMax int `json:"sliceMax,omitempty"`
MinLen int `json:"minLen,omitempty"`
Trim *bool `json:"trim,omitempty"`
}
DeclarativeHTMLVarSpec defines a post-fetch DOM/JSON-LD/Meta extraction variable in `htmlRoutes`.
type DeclarativeHostMapSpec ¶ added in v2.6.3
type DeclarativeHostMapSpec struct {
Param string `json:"param"`
Exact map[string]string `json:"exact,omitempty"`
StripWww bool `json:"stripWww,omitempty"`
SuffixSubdomain string `json:"suffixSubdomain,omitempty"`
}
DeclarativeHostMapSpec maps known hostnames or suffix subdomains to an API site parameter.
type DeclarativeHostSubdomainSpec ¶ added in v2.6.3
type DeclarativeHostSubdomainSpec struct {
Suffix string `json:"suffix"`
Param string `json:"param"`
Reserved []string `json:"reserved,omitempty"`
StripOptional2LetterRegion bool `json:"stripOptional2LetterRegion,omitempty"`
}
DeclarativeHostSubdomainSpec captures `<sub-label><suffix>` from incoming hostnames.
type DeclarativeManifest ¶ added in v2.7.2
type DeclarativeManifest = DeclarativeAdapterManifest
DeclarativeManifest is an alias for DeclarativeAdapterManifest.
type DeclarativeMatchSpec ¶ added in v2.6.2
type DeclarativeMatchSpec struct {
AnyOf []DeclarativeMatchSpec `json:"anyOf,omitempty"`
Hosts []string `json:"hosts,omitempty"`
ExcludeHosts []string `json:"excludeHosts,omitempty"`
SocrataHost bool `json:"socrataHost,omitempty"`
HostSubdomain *DeclarativeHostSubdomainSpec `json:"hostSubdomain,omitempty"`
HostMap *DeclarativeHostMapSpec `json:"hostMap,omitempty"`
OptionalLeadingLocale bool `json:"optionalLeadingLocale,omitempty"`
ExactSegments *bool `json:"exactSegments,omitempty"`
MinSegments *int `json:"minSegments,omitempty"`
MaxSegments *int `json:"maxSegments,omitempty"`
PathPrefix string `json:"pathPrefix,omitempty"`
PathSuffix string `json:"pathSuffix,omitempty"`
PathEquals []string `json:"pathEquals,omitempty"`
PathContainsSegment string `json:"pathContainsSegment,omitempty"`
ExcludeSegmentSuffixes []string `json:"excludeSegmentSuffixes,omitempty"`
AllSegmentsCharset string `json:"allSegmentsCharset,omitempty"`
ReservedFirstSegment []string `json:"reservedFirstSegment,omitempty"`
ScanSegment *DeclarativeScanSegmentSpec `json:"scanSegment,omitempty"`
SplitOnSegment *DeclarativeSplitSegmentSpec `json:"splitOnSegment,omitempty"`
ArcgisRestLayer bool `json:"arcgisRestLayer,omitempty"`
PathSegments []DeclarativeSegmentSpec `json:"pathSegments,omitempty"`
QueryParams []DeclarativeQueryParamSpec `json:"queryParams,omitempty"`
DerivedParams map[string]DeclarativeDerivedParamSpec `json:"derivedParams,omitempty"`
Defaults map[string]string `json:"defaults,omitempty"`
}
DeclarativeMatchSpec matches incoming HTTPS URLs without regular-expression backtracking.
type DeclarativeNestedSubValuesSpec ¶ added in v2.6.3
type DeclarativeNestedSubValuesSpec struct {
ArrayPath string `json:"arrayPath"`
SubArrayField string `json:"subArrayField"`
ValueField string `json:"valueField"`
ExcludeValues []string `json:"excludeValues,omitempty"`
Limit int `json:"limit,omitempty"`
Join string `json:"join,omitempty"`
}
DeclarativeNestedSubValuesSpec collects unique values across nested sub-arrays (e.g. NIST NVD weaknesses).
type DeclarativePaginationMetaSpec ¶ added in v2.6.3
type DeclarativePaginationMetaSpec struct {
TotalPath string `json:"totalPath,omitempty"`
CursorMode string `json:"cursorMode,omitempty"`
IDField string `json:"idField,omitempty"`
}
DeclarativePaginationMetaSpec emits truncation counts for board feeds.
type DeclarativeParallelArraysSpec ¶ added in v2.6.3
type DeclarativeParallelArraysSpec struct {
BasePath string `json:"basePath"`
Fields map[string]string `json:"fields"`
PriorityFilterAfter *struct {
Index int `json:"index"`
Field string `json:"field"`
AllowValues []string `json:"allowValues"`
} `json:"priorityFilterAfter,omitempty"`
}
DeclarativeParallelArraysSpec zips parallel column arrays into row objects (e.g. SEC EDGAR filings.recent).
type DeclarativeParamSegment ¶ added in v2.6.2
type DeclarativeParamSegment struct {
Param string `json:"param"`
Charset string `json:"charset,omitempty"`
AllowValues []string `json:"allowValues,omitempty"`
Reserved []string `json:"reserved,omitempty"`
StripPrefix string `json:"stripPrefix,omitempty"`
StripSuffix string `json:"stripSuffix,omitempty"`
MinLen int `json:"minLen,omitempty"`
MaxLen int `json:"maxLen,omitempty"`
Greedy bool `json:"greedy,omitempty"`
Optional bool `json:"optional,omitempty"`
Transform string `json:"transform,omitempty"`
}
DeclarativeParamSegment defines a strictly validated URL path segment capture.
type DeclarativePathOverrideSpec ¶ added in v2.6.3
type DeclarativePathOverrideSpec struct {
MatchPaths []string `json:"matchPaths"`
NewPath string `json:"newPath"`
}
DeclarativePathOverrideSpec rewrites matched paths when `fetchUrl` is `{requestUrl}`.
type DeclarativeQueryParamSpec ¶ added in v2.6.2
type DeclarativeQueryParamSpec struct {
Name string `json:"name,omitempty"`
Names []string `json:"names,omitempty"`
Param string `json:"param"`
Charset string `json:"charset,omitempty"`
MinLen int `json:"minLen,omitempty"`
MaxLen int `json:"maxLen,omitempty"`
Optional bool `json:"optional,omitempty"`
Default string `json:"default,omitempty"`
Transform string `json:"transform,omitempty"`
}
DeclarativeQueryParamSpec defines a query parameter capture and validation rule.
type DeclarativeReplaceSpec ¶ added in v2.6.3
DeclarativeReplaceSpec defines a literal substring replacement.
type DeclarativeRouteSpec ¶ added in v2.6.2
type DeclarativeRouteSpec struct {
Match DeclarativeMatchSpec `json:"match"`
Twin DeclarativeTwinSpec `json:"twin"`
Extract DeclarativeExtractSpec `json:"extract"`
}
DeclarativeRouteSpec pairs a URL match specification with its twin fetch and extraction contract.
type DeclarativeScanSegmentSpec ¶ added in v2.6.3
type DeclarativeScanSegmentSpec struct {
AfterLiteral string `json:"afterLiteral,omitempty"`
LastOrBeforeLiteral string `json:"lastOrBeforeLiteral,omitempty"`
Param string `json:"param"`
Charset string `json:"charset,omitempty"`
StripPrefix string `json:"stripPrefix,omitempty"`
StripSuffix string `json:"stripSuffix,omitempty"`
MinLen int `json:"minLen,omitempty"`
MaxLen int `json:"maxLen,omitempty"`
Transform string `json:"transform,omitempty"`
}
DeclarativeScanSegmentSpec scans path segments for a matching literal-followed or charset-validated segment.
type DeclarativeSectionFilterSpec ¶ added in v2.6.3
type DeclarativeSectionFilterSpec struct {
RequireField string `json:"requireField,omitempty"`
ExcludeFieldPrefix *struct {
Field string `json:"field"`
Prefix string `json:"prefix"`
} `json:"excludeFieldPrefix,omitempty"`
ExcludeFieldSuffixes *struct {
Field string `json:"field"`
Suffixes []string `json:"suffixes"`
} `json:"excludeFieldSuffixes,omitempty"`
TagFilterParam *struct {
Param string `json:"param"`
SkipIfEquals string `json:"skipIfEquals,omitempty"`
TagsField string `json:"tagsField"`
} `json:"tagFilterParam,omitempty"`
}
DeclarativeSectionFilterSpec filters array elements prior to table/list rendering.
type DeclarativeSectionSpec ¶ added in v2.6.2
type DeclarativeSectionSpec struct {
Heading string `json:"heading"`
HeadingTemplate string `json:"headingTemplate,omitempty"`
WhenVar string `json:"whenVar,omitempty"`
UnlessVar string `json:"unlessVar,omitempty"`
TextVar string `json:"textVar,omitempty"`
ArrayPath string `json:"arrayPath,omitempty"`
ParallelArrays *DeclarativeParallelArraysSpec `json:"parallelArrays,omitempty"`
MinItems int `json:"minItems,omitempty"`
EmptyText string `json:"emptyText,omitempty"`
Filter *DeclarativeSectionFilterSpec `json:"filter,omitempty"`
DedupeBy *DeclarativeDedupeSpec `json:"dedupeBy,omitempty"`
SortBy *DeclarativeSortSpec `json:"sortBy,omitempty"`
Columns []DeclarativeTableColumn `json:"columns,omitempty"`
ListArrayPath string `json:"listArrayPath,omitempty"`
SubsectionsArrayPath string `json:"subsectionsArrayPath,omitempty"`
SubsectionHeadingTemplate string `json:"subsectionHeadingTemplate,omitempty"`
SubsectionAltHeadingTemplate string `json:"subsectionAltHeadingTemplate,omitempty"`
SubsectionAltWhenVar string `json:"subsectionAltWhenVar,omitempty"`
SubsectionBodyVar string `json:"subsectionBodyVar,omitempty"`
SubsectionSubkeys []string `json:"subsectionSubkeys,omitempty"`
TreeComments *DeclarativeTreeCommentsSpec `json:"treeComments,omitempty"`
Limit int `json:"limit,omitempty"`
IndentField string `json:"indentField,omitempty"`
IndentOffset int `json:"indentOffset,omitempty"`
MaxIndent int `json:"maxIndent,omitempty"`
ItemTemplate string `json:"itemTemplate,omitempty"`
RequireItemVar string `json:"requireItemVar,omitempty"`
ItemVars map[string]DeclarativeVarSpec `json:"itemVars,omitempty"`
CollectLinkVars []string `json:"collectLinkVars,omitempty"`
LinkScanLimit int `json:"linkScanLimit,omitempty"`
RecordFields map[string]string `json:"recordFields,omitempty"`
PaginationMeta *DeclarativePaginationMetaSpec `json:"paginationMeta,omitempty"`
}
DeclarativeSectionSpec renders a `## <Heading>` prose, GFM table, subsection list, or nested bullet list section.
type DeclarativeSegmentSpec ¶ added in v2.6.2
type DeclarativeSegmentSpec struct {
IsLiteral bool
Literal string
ParamSpec DeclarativeParamSegment
}
DeclarativeSegmentSpec represents either a literal path segment ("gems") or a DeclarativeParamSegment.
func (*DeclarativeSegmentSpec) UnmarshalJSON ¶ added in v2.6.2
func (s *DeclarativeSegmentSpec) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes a string literal segment or an object parameter segment.
type DeclarativeSortSpec ¶ added in v2.6.3
type DeclarativeSortSpec struct {
BoolDescField string `json:"boolDescField,omitempty"`
NumDescField string `json:"numDescField,omitempty"`
}
DeclarativeSortSpec sorts array rows before rendering.
type DeclarativeSplitSegmentSpec ¶ added in v2.6.3
type DeclarativeSplitSegmentSpec struct {
Delimiter string `json:"delimiter"`
LeftParam string `json:"leftParam"`
LeftMinSegs int `json:"leftMinSegs,omitempty"`
AfterLiteral string `json:"afterLiteral,omitempty"`
RightParam string `json:"rightParam,omitempty"`
TailParam string `json:"tailParam,omitempty"`
}
DeclarativeSplitSegmentSpec splits path segments around a delimiter segment (e.g. GitLab `/-/blob/`).
type DeclarativeSubFieldsJoin ¶ added in v2.6.2
type DeclarativeSubFieldsJoin struct {
Fields []string `json:"fields"`
Sep string `json:"sep"`
FallbackField string `json:"fallbackField,omitempty"`
}
DeclarativeSubFieldsJoin joins subfields from objects inside an array (e.g. Crossref given + family).
type DeclarativeTableColumn ¶ added in v2.6.2
type DeclarativeTableColumn struct {
Header string `json:"header"`
Paths []string `json:"paths,omitempty"`
Template string `json:"template,omitempty"`
FallbackVar string `json:"fallbackVar,omitempty"`
Format string `json:"format,omitempty"`
OutcomesField string `json:"outcomesField,omitempty"`
PricesField string `json:"pricesField,omitempty"`
DefaultOutcomes []string `json:"defaultOutcomes,omitempty"`
StripPrefix string `json:"stripPrefix,omitempty"`
Code bool `json:"code,omitempty"`
SliceMax int `json:"sliceMax,omitempty"`
}
DeclarativeTableColumn defines a column in a GFM Markdown table section.
type DeclarativeTreeCommentsSpec ¶ added in v2.6.3
type DeclarativeTreeCommentsSpec struct {
ChildrenPath string `json:"childrenPath"`
AuthorPath string `json:"authorPath"`
HTMLTextPath string `json:"htmlTextPath"`
MaxDepth int `json:"maxDepth,omitempty"`
MaxItems int `json:"maxItems,omitempty"`
}
DeclarativeTreeCommentsSpec renders nested comment trees (e.g. Hacker News Algolia).
type DeclarativeTwinMatch ¶ added in v2.6.2
type DeclarativeTwinMatch struct {
ID string
AdapterID string
FetchURL string
Kind classify.Kind
Accept string
// contains filtered or unexported fields
}
DeclarativeTwinMatch represents a resolved 1-hop declarative twin upgrade ready to fetch and format.
func ResolveDeclarativeTwin ¶ added in v2.6.2
func ResolveDeclarativeTwin(rawURL string) (*DeclarativeTwinMatch, bool)
ResolveDeclarativeTwin checks if `rawURL` matches any embedded declarative adapter and returns its 1-hop twin descriptor.
func (*DeclarativeTwinMatch) Format ¶ added in v2.6.2
func (m *DeclarativeTwinMatch) Format(rawBody string) (*DeclarativeFormattedDoc, bool)
Format transforms a fetched JSON, XML, or text twin body into clean GitHub-Flavored Markdown and structured metadata. Returns `(nil, false)` on malformed, HTML soft-404, or schema-mismatched payloads so callers safely fall back to HTML scraping.
func (*DeclarativeTwinMatch) ValidateRedirectTarget ¶ added in v2.7.2
func (m *DeclarativeTwinMatch) ValidateRedirectTarget(finalURL string) bool
ValidateRedirectTarget verifies that a twin HTTP redirect destination remains a safe public HTTPS URL on the exact initial FetchURL host or an explicitly declared non-wildcard manifest domain (matching TypeScript `isTrustedTwinRedirectUrl` 1:1 without following redirects to unclaimed same-registrable subdomains or across multi-tenant wildcards).
type DeclarativeTwinSpec ¶ added in v2.6.2
type DeclarativeTwinSpec struct {
ID string `json:"id,omitempty"`
FetchURL string `json:"fetchUrl"`
RawPathParams []string `json:"rawPathParams,omitempty"`
OverridePathIf *DeclarativePathOverrideSpec `json:"overridePathIf,omitempty"`
SetQueryParams map[string]string `json:"setQueryParams,omitempty"`
DefaultQueryParams map[string]string `json:"defaultQueryParams,omitempty"`
Kind string `json:"kind"`
Accept string `json:"accept"`
}
DeclarativeTwinSpec describes the 1-hop HTTPS JSON/text endpoint upgrade.
type DeclarativeVarSpec ¶ added in v2.6.2
type DeclarativeVarSpec struct {
Paths []string `json:"paths,omitempty"`
DynamicKeyPath *DeclarativeDynamicKeyPath `json:"dynamicKeyPath,omitempty"`
NestedSubValues *DeclarativeNestedSubValuesSpec `json:"nestedSubValues,omitempty"`
TocHeading string `json:"tocHeading,omitempty"`
FindInArrayLang *DeclarativeFindLangSpec `json:"findInArrayLang,omitempty"`
Template string `json:"template,omitempty"`
WhenVars []string `json:"whenVars,omitempty"`
WhenAnyVars []string `json:"whenAnyVars,omitempty"`
FallbackVar string `json:"fallbackVar,omitempty"`
FirstNonMatchingKey string `json:"firstNonMatchingKey,omitempty"`
SubField string `json:"subField,omitempty"`
SubFieldsJoin *DeclarativeSubFieldsJoin `json:"subFieldsJoin,omitempty"`
ItemWrap string `json:"itemWrap,omitempty"`
Join string `json:"join,omitempty"`
Limit int `json:"limit,omitempty"`
Format string `json:"format,omitempty"`
TrueValue string `json:"trueValue,omitempty"`
FalseValue string `json:"falseValue,omitempty"`
StripFrontmatter bool `json:"stripFrontmatter,omitempty"`
StripPrefix string `json:"stripPrefix,omitempty"`
StripSuffix string `json:"stripSuffix,omitempty"`
ReplaceAll *DeclarativeReplaceSpec `json:"replaceAll,omitempty"`
ExcludeEquals string `json:"excludeEquals,omitempty"`
EqualsVar string `json:"equalsVar,omitempty"`
Trim bool `json:"trim,omitempty"`
Upper bool `json:"upper,omitempty"`
Lower bool `json:"lower,omitempty"`
RequireHTTPS bool `json:"requireHttps,omitempty"`
RequireHTTPPrefix bool `json:"requireHttpPrefix,omitempty"`
SliceMax int `json:"sliceMax,omitempty"`
Default string `json:"default,omitempty"`
FallbackTemplate string `json:"fallbackTemplate,omitempty"`
}
DeclarativeVarSpec extracts and formats a named string variable from JSON.
type DeclarativeXMLColumnSpec ¶ added in v2.6.3
type DeclarativeXMLColumnSpec struct {
Header string `json:"header"`
Template string `json:"template"`
}
DeclarativeXMLColumnSpec renders a column in an XML/RSS table.
type DeclarativeXMLItemVarSpec ¶ added in v2.6.3
type DeclarativeXMLItemVarSpec struct {
Tags []string `json:"tags"`
SplitColonPart *int `json:"splitColonPart,omitempty"`
SliceMax int `json:"sliceMax,omitempty"`
Default string `json:"default,omitempty"`
}
DeclarativeXMLItemVarSpec extracts a tag value inside an XML/RSS item block.
type DeclarativeXMLSpec ¶ added in v2.6.3
type DeclarativeXMLSpec struct {
Mode string `json:"mode"`
RequireAnyTags []string `json:"requireAnyTags,omitempty"`
ItemTag string `json:"itemTag,omitempty"`
ChannelTitleFallbackParam string `json:"channelTitleFallbackParam,omitempty"`
FirstItemVars map[string][]string `json:"firstItemVars,omitempty"`
TitleTemplate string `json:"titleTemplate,omitempty"`
EmptyText string `json:"emptyText,omitempty"`
Limit int `json:"limit,omitempty"`
RequireItemVar string `json:"requireItemVar,omitempty"`
ItemVars map[string]DeclarativeXMLItemVarSpec `json:"itemVars,omitempty"`
Columns []DeclarativeXMLColumnSpec `json:"columns,omitempty"`
CollectLinkVar string `json:"collectLinkVar,omitempty"`
RecordFields map[string]string `json:"recordFields,omitempty"`
EmitTotals bool `json:"emitTotals,omitempty"`
}
DeclarativeXMLSpec extracts structured tables or prose from XML, RSS, or JATS payloads.
type ExtractOptions ¶
type ExtractOptions struct {
BaseURL string
OnlyMainContent bool
IncludeLinks bool
IncludeImages bool
IncludeBranding bool
RedactPII bool
Query string
MaxChars int
}
ExtractOptions configures HTML extraction.
type LlmsDiscovery ¶
type LlmsDiscovery struct {
Found bool `json:"found"`
LlmsTxtURL string `json:"llmsTxtUrl,omitempty"`
LlmsFullTxtURL string `json:"llmsFullTxtUrl,omitempty"`
CompanionMdURL string `json:"companionMdUrl,omitempty"`
UsedCompanionMd bool `json:"usedCompanionMd,omitempty"`
SiteTitle string `json:"siteTitle,omitempty"`
SiteSummary string `json:"siteSummary,omitempty"`
MatchedEntry *LlmsLink `json:"matchedEntry,omitempty"`
RelatedLinks []LlmsLink `json:"relatedLinks,omitempty"`
}
LlmsDiscovery reports `llms.txt` / companion `.md` enrichment attached to a crawled page Result.
type LlmsDocument ¶
type LlmsDocument struct {
SourceURL string `json:"sourceUrl"`
Title string `json:"title,omitempty"`
Summary string `json:"summary,omitempty"`
FullTxtURL string `json:"fullTxtUrl,omitempty"`
Links []LlmsLink `json:"links,omitempty"`
RawPreview string `json:"rawPreview,omitempty"`
}
LlmsDocument represents a parsed `/llms.txt` index per https://llmstxt.org/.
func ParseLlmsTxt ¶
func ParseLlmsTxt(raw, sourceURL string) (*LlmsDocument, bool)
ParseLlmsTxt parses an `llms.txt` Markdown file, rejecting HTML 200 soft-404 pages masquerading as `/llms.txt`.
Example ¶
package main
import (
"fmt"
"github.com/bartrumb/edgefetch/v2/internal/extract"
)
func main() {
raw := `# EdgeFetch Docs
> Distributed edge web crawler for AI agents.
## Guides
- [Quickstart](/docs/quickstart.md): Deploy Hub + Go Worker in 60 seconds
`
doc, ok := extract.ParseLlmsTxt(raw, "https://docs.example.com/llms.txt")
fmt.Println("valid:", ok, "| title:", doc.Title, "| firstUrl:", doc.Links[0].URL)
}
Output: valid: true | title: EdgeFetch Docs | firstUrl: https://docs.example.com/docs/quickstart.md
type LlmsLink ¶
type LlmsLink struct {
Section string `json:"section,omitempty"`
Title string `json:"title"`
URL string `json:"url"`
Notes string `json:"notes,omitempty"`
}
LlmsLink represents a single `- [Title](URL): Notes` entry inside `/llms.txt`.
type PageExtraction ¶
type PageExtraction struct {
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Favicon string `json:"favicon,omitempty"`
Markdown string `json:"markdown,omitempty"`
Text string `json:"text,omitempty"`
Links []string `json:"links,omitempty"`
Images []ImageInfo `json:"images,omitempty"`
Branding *BrandingProfile `json:"branding,omitempty"`
}
PageExtraction holds the structured outputs extracted from an HTML document.
func ExtractHTML ¶
func ExtractHTML(rawHTML string, opts ExtractOptions) PageExtraction
ExtractHTML parses rawHTML into clean Markdown, plain text, links, images, and optional branding profile.
Example ¶
package main
import (
"fmt"
"github.com/bartrumb/edgefetch/v2/internal/extract"
)
func main() {
rawHTML := `<!doctype html>
<html>
<head><title>Async Runtime</title></head>
<body>
<nav><a href="/home">Home</a></nav>
<main>
<h1>Async Runtime</h1>
<p>Returns <code>Promise<void></code> when complete.</p>
</main>
</body>
</html>`
page := extract.ExtractHTML(rawHTML, extract.ExtractOptions{
BaseURL: "https://docs.example.com/guide",
OnlyMainContent: true,
})
fmt.Println(page.Markdown)
}
Output: # Async Runtime Returns `Promise<void>` when complete.