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 ¶
- Constants
- Variables
- func BuildWikimediaRobotsSuggestion(rawHost string) string
- func BuildWikipediaDirectTitleGuessURL(rawQuery, lang string) string
- func CandidateCompanionMarkdownURL(pageURL string) string
- func CheckApprovedWildcardDomains(m *DeclarativeAdapterManifest) error
- func CleanFenceInfoString(rawInfo string) string
- func CleanMediaWikiMarkdown(rawMD string) string
- func CleanPDFMarkdown(md string) string
- func CollapseAnimatedCounterTickers(prose string) string
- func DecodeBasicEntities(s string) string
- func DecodeHTMLEntities(input string) string
- func DecodeMarkdownEntities(md string) string
- func DereferenceNuxtDevaluePayload(flat []any, maxNodes int) any
- func DeriveQuickMarkdownFromRawBytes(data []byte, baseURL string) string
- func DetectRenderedChallenge(rawHTML string) string
- func DetectUnsupportedBinaryPayload(data []byte, contentType, urlStr string) (unsupported bool, mimeLabel, reason string)
- func DiscoverWordPressRestTwinURL(rawHTML, pageFinalURL, selfHost string) string
- func DistillStructuredRecordsFromJSONTree(root any, baseURL string, maxRecords int) []map[string]any
- func EscapeAllResidualLtInProse(prose string, allowPdfPageMarkers bool) string
- func EscapeGfmTaskListCheckboxes(prose string) string
- func ExtractBalancedJSONAt(src string, startIdx, maxScanChars int) (rawJSON string, endIdx int, ok bool)
- func ExtractInertiaPageProps(rawHTML string, maxScanChars int) map[string]any
- func ExtractJSONLDObjects(rawHTML string, maxEntities int) []map[string]any
- func ExtractLargestURLFromSrcset(srcset 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 ExtractPDFTitle(md, urlStr string) string
- func ExtractStructuredJSONFromPageWithDiagnostics(rawHTML string, doc ExtractedDocumentFull, schema map[string]any, ...) (result map[string]any, matchedFields []string, unfilledFields []string)
- func ExtractStructuredProduct(rawBody, finalURL, fallbackTitle, fallbackDescription string) map[string]any
- func ExtractWikipediaLangFromHost(rawHost string) string
- func ExtractYouTubeTranscriptFromHTML(rawHTML string) string
- func FilterSafeResponseHeaders(rawHeaders map[string]string) map[string]string
- func FinalizeScrapedMarkdown(md, baseURL string, opts FullExtractOptions) (finalMD string, totalChars, returnedChars int, truncated bool, nextOffset *int)
- func GetRegistrableDomain(host string) string
- func HasPDFToText() bool
- func HasPrivateSharedHostingSuffix(host string) bool
- func HasRawOrEncodedUnicodeTag(raw string) bool
- func InspectRawSchemaOrgJSONLD(rawHTML string) string
- func IsDisallowedMarkdownLinkDestination(rawHref string) bool
- func IsDisallowedWikipediaTitle(decodedTitle string) bool
- func IsJSONLDScriptAttr(attrStr string) bool
- func IsNuxtDevalueFlatArray(parsed any) bool
- func IsPDFBytes(data []byte) bool
- func IsPublicOrPrivateSuffix(host string) bool
- func IsSafeDeclarativeTwinURL(raw string) bool
- func IsWikimediaHost(rawHost string) bool
- func IsWikipediaHost(rawHost string) bool
- func LookupKnownRegistrableDomain(host string) (string, bool)
- func MakeSafeCodeFence(code, lang string, preferTilde bool) string
- func MatchDeclarativeRouteURL(spec DeclarativeMatchSpec, rawURL string) (map[string]string, bool)
- func MatchesApprovedWildcard(rawWildcard, rawCandidate string) bool
- func NeedsBrowserRender(rawHTML string) bool
- func NeutralizeAllUnsafeMarkdownLinks(prose string) string
- func NormalizeTrackerHostCandidate(raw string) (string, bool)
- func NormalizeWikipediaLang(rawLang, fallback string) string
- func ParseDeclarativeYAML(raw []byte) (any, error)
- func ParseMarkdownFrontmatter(md string) (title, description, body string)
- func PercentEncodeUnsafeRecordURLChars(urlStr string) string
- func PlainText(rawHTML string) string
- func RecognizeAndHardenMarkdownFences(rawMD string, opts RecognizeMarkdownFencesOptions) (hardened string, segments []string)
- func RedactPII(s string) string
- func RedactPIIMarkdownSafe(text string) string
- func RerankPassages(doc, query string, maxChars int) string
- func ResolveGatsbyPageDataTwinURL(rawHTML, pageFinalURL, selfHost string) string
- func ResolveWikipediaCanonicalFinalURL(requestedURL, responseFinalURL string) string
- func ResolveWikipediaCanonicalFinalURLFull(requestedURL, storedFinalURL, title, markdown string) string
- func SanitizeFullMarkdownDocumentForArtifact(fullMD string) string
- func SanitizeMarkdown(md, baseURL string) string
- func SanitizeMarkdownPageSlice(rawFullMD string, safeOffset int, rawSliceInput string, ...) string
- func SanitizeMarkdownPageSliceUTF16(rawFullMD string, utf16Offset int, rawSliceInput string, ...) string
- func SanitizeMarkdownWithOptions(md, baseURL string, allowPdfPageMarkers bool) string
- func SanitizePlainMetadataText(raw string, maxLen int) string
- func SanitizeSchemaHTTPSURL(raw any, baseURL string) string
- func SanitizeSchemaPlainField(raw any, maxLen int) string
- func SanitizeSchemaRichMarkdown(raw any, baseURL string, htmlToMD func(frag, base string) (string, []string), ...) string
- func SanitizeScrapedMarkdown(md string) string
- func SanitizeScrapedMeta(s string) string
- func SanitizeScrapedMetadataField(raw string, maxLen int) string
- func SanitizeScrapedTimestampField(raw string, maxLen int) string
- func ScanGeneratorMetaTags(htmlStr string, maxChars int) []string
- func ScanJSONStringLiteralAt(src string, openQuoteIdx, maxEnd int) (decoded string, nextIdx int, ok bool)
- func SplitMarkdownByCodeFences(rawMD string) []string
- func SplitPDFPagesAndMarkers(rawText string, maxPages int) (pages []string, markedMarkdown string)
- func StripInvisibleSchemaChars(s string) string
- func StripInvisibleSmugglingChars(s string) string
- func StripMarkdownTableDividerLinesLinear(s string) string
- func UTF16Len(s string) int
- func UTF16OffsetToByteOffset(s string, utf16Off int) int
- func ValidateDeclarativeManifests(manifests []DeclarativeAdapterManifest) error
- func YAMLToJSON(raw []byte) ([]byte, error)
- type AttrSelectorItem
- type AttrSelectorSpec
- type BrandingProfile
- type BrowserFrameworkGlobals
- type CMSAutoTwinFormatted
- type CapturedJSONPayloadInput
- type DeclarativeAdapterManifest
- type DeclarativeAdapterSummary
- type DeclarativeBulletSpec
- type DeclarativeCatalogConfig
- type DeclarativeCodeByPathSpec
- type DeclarativeDedupeSpec
- type DeclarativeDerivedParamSpec
- type DeclarativeDynamicKeyPath
- type DeclarativeExactSegments
- type DeclarativeExtractSpec
- type DeclarativeFindInArray
- type DeclarativeFindLangSpec
- type DeclarativeFormattedDoc
- func FormatDeclarativeTwinByURL(requestURL, rawBody, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatJSONWithExtractSpec(rawBody string, ext DeclarativeExtractSpec, params map[string]string, ...) (*DeclarativeFormattedDoc, bool)
- func FormatTwinOnManifest(m *DeclarativeAdapterManifest, requestURL, rawBody, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatTwinOnValidatedManifest(m *DeclarativeAdapterManifest, requestURL, rawBody, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatYAMLFrontmatterCard(rawMD, fallbackTitle string) *DeclarativeFormattedDoc
- type DeclarativeHTMLRouteSpec
- type DeclarativeHTMLVarSpec
- type DeclarativeHostMapSpec
- type DeclarativeHostSubdomainSpec
- type DeclarativeManifest
- type DeclarativeMatchSpec
- type DeclarativeNestedSubValuesSpec
- type DeclarativePaginationMetaSpec
- type DeclarativeParallelArraysSpec
- type DeclarativeParamSegment
- type DeclarativePathOverrideSpec
- type DeclarativePostFetchResult
- func ApplyDeclarativeHTMLExtractor(rawHTML, baseURL, currentMD string, ...) (*DeclarativePostFetchResult, bool)
- func ExtractHTMLOnManifest(m *DeclarativeAdapterManifest, rawHTML, baseURL, currentMD string, ...) (*DeclarativePostFetchResult, bool)
- func ExtractHTMLOnValidatedManifest(cp *DeclarativeAdapterManifest, rawHTML, baseURL, currentMD string, ...) (*DeclarativePostFetchResult, bool)
- 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
- func (m *DeclarativeTwinMatch) CommerceMode() string
- func (m *DeclarativeTwinMatch) EffectiveMaxBytes() int
- func (m *DeclarativeTwinMatch) Format(rawBody string) (*DeclarativeFormattedDoc, bool)
- func (m *DeclarativeTwinMatch) RawAccept() string
- func (m *DeclarativeTwinMatch) ValidateRedirectTarget(finalURL string) bool
- type DeclarativeTwinSpec
- type DeclarativeVarSpec
- type DeclarativeXMLColumnSpec
- type DeclarativeXMLItemVarSpec
- type DeclarativeXMLSpec
- type DetectSiteFrameworkParams
- type DetectedSiteStack
- type DistilledRecordsResult
- type ExtractOptions
- type ExtractedDocumentFull
- type FormattedPayloadDoc
- func FormatDelimitedTableToMarkdown(raw, sep, titleHint string) *FormattedPayloadDoc
- func FormatFeedXMLToMarkdown(raw, baseURL string) (doc *FormattedPayloadDoc, links []string)
- func FormatGitPatchToMarkdown(raw, urlStr string) *FormattedPayloadDoc
- func FormatICalendarToMarkdown(raw string) *FormattedPayloadDoc
- func FormatInertiaPagePropsToMarkdown(props map[string]any, pageURL string) *FormattedPayloadDoc
- func FormatJupyterNotebookToMarkdown(raw, urlStr string) *FormattedPayloadDoc
- func FormatOpenAPISpecToMarkdown(raw, urlStr string) *FormattedPayloadDoc
- func FormatSourceCodeURLToMarkdown(raw, urlStr, contentType string) *FormattedPayloadDoc
- func FormatVCardToMarkdown(raw string) *FormattedPayloadDoc
- func TryParseJSONPayloadForScrape(raw, urlStr string) *FormattedPayloadDoc
- type FullExtractOptions
- type HTMLDoc
- type HTMLNode
- func (n *HTMLNode) Attr(name string) (string, bool)
- func (n *HTMLNode) AttrOf(subSelector, name string) string
- func (n *HTMLNode) AttrOrEmpty(name string) string
- func (n *HTMLNode) DLMap(subSelector ...string) map[string]string
- func (n *HTMLNode) First(selector string) *HTMLNode
- func (n *HTMLNode) HTML(subSelector ...string) string
- func (n *HTMLNode) OuterHTML() string
- func (n *HTMLNode) Select(selector string, limit int) []*HTMLNode
- func (n *HTMLNode) TableRows(subSelector ...string) [][]string
- func (n *HTMLNode) Tag() string
- func (n *HTMLNode) Text(subSelector ...string) string
- type HydratedFrameworkStateResult
- func DistillCapturedJSONResponses(inputs []CapturedJSONPayloadInput, baseURL string, ...) *HydratedFrameworkStateResult
- func ExtractFromParsedStateTree(root any, framework, baseURL string, ...) *HydratedFrameworkStateResult
- func ExtractNextRSCFlight(rawHTML, baseURL string, htmlToMD func(frag, base string) (string, []string)) *HydratedFrameworkStateResult
- func RecoverSSRHydrationContent(rawHTML, baseURL string, htmlToMD func(frag, base string) (string, []string)) *HydratedFrameworkStateResult
- type ImageInfo
- type LlmsDiscovery
- type LlmsDocument
- type LlmsLink
- type MarkdownFenceRecognizerState
- type MarkdownSliceCheckpoint
- type MarkdownSliceEscapedUntrusted
- type PageExtraction
- type ParsedWikipediaArticle
- type PromptInjectionResult
- type RecognizeMarkdownFencesOptions
- type ReopenedMarkdownFence
- type UniversalSchemaOrgResult
- type ValidatedEasyPrivacyResult
- type YouTubeWatchMeta
Examples ¶
Constants ¶
const ( // DefaultMaxHTMLDocChars is the default 2 MiB input ceiling for ParseHTMLDoc. DefaultMaxHTMLDocChars = 2_097_152 // HardMaxHTMLDocChars is the absolute 4 MiB ceiling for ParseHTMLDoc even when maxChars is larger. HardMaxHTMLDocChars = 4_194_304 )
const ( MinEasyPrivacyListBytes = 200 * 1024 MaxEasyPrivacyListBytes = 10 * 1024 * 1024 MinEasyPrivacyHostCount = 5_000 MaxEasyPrivacyHostCount = 200_000 MaxEasyPrivacyHostDeltaRatio = 0.2 )
const ( // DefaultWikipediaMaxAgeMs is the default 24-hour cache freshness window for Wikipedia articles. DefaultWikipediaMaxAgeMs = 24 * 60 * 60_000 // DefaultWikipediaHourlyArticleLimit is the polite single-article ceiling per caller per Wikimedia host per hour. DefaultWikipediaHourlyArticleLimit = 200 )
const (
// FrameworkDetectWindowChars bounds framework/platform detection to the first 64 KiB (65,536 UTF-16 code units).
FrameworkDetectWindowChars = 65_536
)
Variables ¶
var SafeResponseHeaderAllowlist = []string{
"server",
"powered-by",
"x-powered-by",
"x-generator",
"x-shopid",
"x-shopify-stage",
"x-wix-request-id",
"x-drupal-cache",
"x-drupal-dynamic-cache",
"x-nextjs-cache",
"x-remix-response",
"x-vercel-id",
"x-nf-request-id",
"x-github-request-id",
"x-hs-hub-id",
"x-typo3-parsetime",
"cf-ray",
"cf-cache-status",
"cf-mitigated",
"via",
"vary",
"link",
"x-robots-tag",
"content-signal",
"x-markdown-tokens",
"cache-control",
}
SafeResponseHeaderAllowlist lists response headers safe for framework/platform detection without leaking secrets like set-cookie.
Functions ¶
func BuildWikimediaRobotsSuggestion ¶ added in v2.8.0
BuildWikimediaRobotsSuggestion returns an actionable RFC 9309-compliant guidance message when a caller hits robots-disallowed Wikimedia search or API paths.
func BuildWikipediaDirectTitleGuessURL ¶ added in v2.8.0
BuildWikipediaDirectTitleGuessURL builds a direct-title guess URL (`https://<lang>.wikipedia.org/wiki/<Title>`) only when rawQuery looks like a concise article title (`<= 6` words, `<= 120` chars, no search operators or disallowed namespaces).
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 CheckApprovedWildcardDomains ¶ added in v2.8.0
func CheckApprovedWildcardDomains(m *DeclarativeAdapterManifest) error
CheckApprovedWildcardDomains verifies that every wildcard domain pattern in m is on the pinned M2 allowlist.
func CleanFenceInfoString ¶ added in v2.8.0
CleanFenceInfoString sanitizes fenced code block info strings in linear time.
func CleanMediaWikiMarkdown ¶ added in v2.8.0
CleanMediaWikiMarkdown performs fence-aware linear O(N) cleanup of MediaWiki Markdown (`< 5ms` on 2 MiB), stripping `[ ]` checkboxes, `"Edit links"`, Wikidata sitelinks, `[1][2]` footnote markers, `[edit]` links, Vector 2022 UI chrome, reference back-link letter chains, and trailing navigation menus while preserving tables and code fences.
func CleanPDFMarkdown ¶ added in v2.8.0
CleanPDFMarkdown normalizes Poppler / OCR PDF layout whitespace (column-alignment spaces and line-wrap hyphenations) while leaving fenced code blocks untouched.
func CollapseAnimatedCounterTickers ¶ added in v2.8.0
CollapseAnimatedCounterTickers dedupes animated slot/ticker counter clones (`"382,831,172 3 8 2, 8 3 1, 1 7 2"` -> `"382,831,172"`) in linear O(N) time.
func DecodeBasicEntities ¶ added in v2.8.0
DecodeBasicEntities decodes basic named HTML entities (`&`, `<`, `>`, `"`, `'`, `'`, ` `) and valid Unicode scalar numeric character references (`1..0x10FFFF` excluding surrogates), leaving invalid/NUL numeric entities intact.
func DecodeHTMLEntities ¶ added in v2.8.0
DecodeHTMLEntities decodes decimal (`{`), hexadecimal (`😀`), and named (`&`, `<`, `—`, etc.) HTML entities in linear O(N) time.
func DecodeMarkdownEntities ¶ added in v2.8.0
DecodeMarkdownEntities decodes HTML entities in Markdown prose segments while leaving fenced code blocks untouched.
func DereferenceNuxtDevaluePayload ¶ added in v2.8.0
DereferenceNuxtDevaluePayload safely dereferences a Nuxt 3/4 `devalue` flat slot table into a bounded (`maxNodes`, `maxDepth = 12`), cycle-free plain Go tree while blocking prototype-pollution keys.
func DeriveQuickMarkdownFromRawBytes ¶ added in v2.8.0
DeriveQuickMarkdownFromRawBytes synchronously derives clean Markdown from raw UTF-8 payload bytes (HTML, vCard, iCalendar, RSS/Atom XML, JSON/Jupyter/OpenAPI, CSV/TSV, Git patch, raw source code, or Markdown).
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 DetectUnsupportedBinaryPayload ¶ added in v2.8.0
func DetectUnsupportedBinaryPayload(data []byte, contentType, urlStr string) (unsupported bool, mimeLabel, reason string)
DetectUnsupportedBinaryPayload inspects `contentType`, magic headers, UTF-8/control-byte ratios, and URL extensions to reject binary archives, images, audio/video, fonts, and executables from Markdown text extraction.
func DiscoverWordPressRestTwinURL ¶ added in v2.8.0
DiscoverWordPressRestTwinURL linearly scans `<head>` (`<= 96 KiB`) for WordPress's canonical per-post/page REST JSON `<link rel="alternate" type="application/json">` tag, enforcing strict same-origin `https://` port 443, `/wp-json/wp/v2/(posts|pages)/<digits>` path format, and SSRF-safe public hostname validation.
func DistillStructuredRecordsFromJSONTree ¶ added in v2.8.0
func DistillStructuredRecordsFromJSONTree(root any, baseURL string, maxRecords int) []map[string]any
DistillStructuredRecordsFromJSONTree walks an arbitrary JSON state or XHR payload tree (`maxVisited = 2_500`, `maxDepth = 12`) to extract the highest-confidence homogeneous data record array (`>= 3` items, capped at `maxRecords`), rejecting nav/menu chrome and returning `nil` when none matches.
func EscapeAllResidualLtInProse ¶ added in v2.8.0
EscapeAllResidualLtInProse escapes every `<` to `<` outside verified standalone PDF page markers.
func EscapeGfmTaskListCheckboxes ¶ added in v2.8.0
EscapeGfmTaskListCheckboxes escapes GFM task-list checkboxes (`- [ ] `, `* [x] `, `1. [X] `) in linear O(N) time.
func ExtractBalancedJSONAt ¶ added in v2.8.0
func ExtractBalancedJSONAt(src string, startIdx, maxScanChars int) (rawJSON string, endIdx int, ok bool)
ExtractBalancedJSONAt extracts a balanced `{...}` or `[...]` JSON slice starting at or after `startIdx` (skipping leading whitespace and `=`) within `maxScanChars` bytes in linear O(N) time.
func ExtractInertiaPageProps ¶ added in v2.8.0
ExtractInertiaPageProps linearly extracts Inertia.js `data-page="{"component":...}"` serialized page props within maxScanChars (default 512 KiB), returning nil when absent, malformed, or missing a string `component`.
func ExtractJSONLDObjects ¶ added in v2.8.0
ExtractJSONLDObjects extracts flattened JSON-LD objects (including `@graph` entries) from `<script type="application/ld+json">` blocks in linear O(N) time (`H1`).
func ExtractLargestURLFromSrcset ¶ added in v2.8.0
ExtractLargestURLFromSrcset selects the highest-resolution candidate URL from an HTML `srcset` attribute (`1200w`, `2x`, etc.), preserving commas inside CDN transform paths (e.g. Cloudinary `w_800,q_auto`) that lack post-comma whitespace.
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 ExtractPDFTitle ¶ added in v2.8.0
ExtractPDFTitle derives a clean document title from extracted PDF Markdown, skipping copyright/conference boilerplate and falling back to the URL filename when needed.
func ExtractStructuredJSONFromPageWithDiagnostics ¶ added in v2.8.0
func ExtractStructuredJSONFromPageWithDiagnostics( rawHTML string, doc ExtractedDocumentFull, schema map[string]any, prompt string, ) (result map[string]any, matchedFields []string, unfilledFields []string)
ExtractStructuredJSONFromPageWithDiagnostics performs deterministic, keyless schema-guided structured extraction over JSON-LD (`application/ld+json`), document metadata, and GFM Markdown structure, returning the extracted map alongside matched and unfilled schema property names.
func ExtractStructuredProduct ¶ added in v2.8.0
func ExtractStructuredProduct(rawBody, finalURL, fallbackTitle, fallbackDescription string) map[string]any
ExtractStructuredProduct extracts normalized e-commerce product metadata across Schema.org JSON-LD `Product`, OpenGraph `product:*` / `og:*` meta tags, and barcode / H1 fallbacks (`scrape-advanced.ts:3089-3244`).
func ExtractWikipediaLangFromHost ¶ added in v2.8.0
ExtractWikipediaLangFromHost extracts the canonical language edition code from `<lang>.wikipedia.org` or `<lang>.m.wikipedia.org`, returning `""` for non-edition hosts (`www`, `meta`, `commons`, etc.).
func ExtractYouTubeTranscriptFromHTML ¶ added in v2.8.0
ExtractYouTubeTranscriptFromHTML extracts timed caption/transcript segments from rendered YouTube transcript DOM elements.
func FilterSafeResponseHeaders ¶ added in v2.8.0
FilterSafeResponseHeaders filters rawHeaders down to SafeResponseHeaderAllowlist (case-insensitively), trimming values to 512 chars and returning nil when no allowlisted headers are present.
func FinalizeScrapedMarkdown ¶ added in v2.8.0
func FinalizeScrapedMarkdown(md, baseURL string, opts FullExtractOptions) (finalMD string, totalChars, returnedChars int, truncated bool, nextOffset *int)
FinalizeScrapedMarkdown strips frontmatter, sanitizes inline HTML and unsafe Markdown links, collapses animated counter tickers, optionally normalizes PDF layout whitespace, and applies offset/maxChars pagination with automatic code-fence / code-span closure.
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 HasRawOrEncodedUnicodeTag ¶ added in v2.8.0
HasRawOrEncodedUnicodeTag detects literal, JSON-escaped (`\udb40\udc69`, `\u{e0069}`), or HTML-entity-encoded (`󠁩`, `󠁩`, `&#xE0069;`) Unicode Tag smuggling (`U+E0000..U+E007F`) in linear O(N) time with zero tree-node budget (`NEW-HIGH-1`).
func InspectRawSchemaOrgJSONLD ¶ added in v2.8.0
InspectRawSchemaOrgJSONLD walks all `<script type="application/ld+json">` string leaves up to depth 20 and 1.5 MiB for prompt-injection screening (`checkPromptInjection: true`), preserving smuggled Unicode Tags (`HIGH-3`).
func IsDisallowedMarkdownLinkDestination ¶ added in v2.8.0
IsDisallowedMarkdownLinkDestination reports whether rawHref violates the strict fail-closed URI allowlist.
func IsDisallowedWikipediaTitle ¶ added in v2.8.0
IsDisallowedWikipediaTitle reports whether decodedTitle is empty, contains unsafe path segments, or targets a non-article MediaWiki namespace (`Special:`, `Talk:`, `User:`, `Wikipedia:`, `File:`, localized equivalents, etc.).
func IsJSONLDScriptAttr ¶ added in v2.8.0
IsJSONLDScriptAttr matches `<script type="application/ld+json">` attribute strings (quoted or unquoted, with optional MIME parameters such as `;charset=utf-8`) in linear O(N) time (`HIGH-3`).
func IsNuxtDevalueFlatArray ¶ added in v2.8.0
IsNuxtDevalueFlatArray detects whether a parsed JSON value is a Nuxt 3/4 `devalue` flat index-pointer array.
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 IsSafeDeclarativeTwinURL ¶ added in v2.8.0
IsSafeDeclarativeTwinURL reports whether raw is a safe public HTTPS declarative twin URL.
func IsWikimediaHost ¶ added in v2.8.0
IsWikimediaHost reports whether rawHost belongs to Wikipedia or a sister Wikimedia project domain.
func IsWikipediaHost ¶ added in v2.8.0
IsWikipediaHost reports whether rawHost is wikipedia.org or a subdomain of wikipedia.org.
func LookupKnownRegistrableDomain ¶ added in v2.8.0
LookupKnownRegistrableDomain resolves the eTLD+1 registrable domain ONLY when the host's public suffix is explicitly recognized in the Mozilla Public Suffix List (or RFC 2606 reserved `.test` / `.example` TLDs) and is NOT a PSL PRIVATE DOMAINS shared-hosting suffix. When `ok` is false (shared-hosting suffix, unknown/unlisted TLD suffix, IP literal, dotless host, or bare suffix), third-party subresource tracker blocking must fail open and not block.
func MakeSafeCodeFence ¶ added in v2.8.0
MakeSafeCodeFence wraps `code` in a CommonMark backtick (or tilde when `preferTilde` is true) code fence guaranteed to exceed any interior run of fence characters.
func MatchDeclarativeRouteURL ¶ added in v2.8.0
func MatchDeclarativeRouteURL(spec DeclarativeMatchSpec, rawURL string) (map[string]string, bool)
MatchDeclarativeRouteURL matches a DeclarativeMatchSpec against a raw URL string.
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 NeutralizeAllUnsafeMarkdownLinks ¶ added in v2.8.0
NeutralizeAllUnsafeMarkdownLinks neutralizes disallowed inline `](...)` destinations, `[id]: ...` reference definitions, and bare `//host.tld` protocol-relative URLs in linear O(N) time.
func NormalizeTrackerHostCandidate ¶ added in v2.8.1
NormalizeTrackerHostCandidate normalizes a candidate domain host per RFC 1123 (rejecting IPv4 literals and numeric-only TLDs).
func NormalizeWikipediaLang ¶ added in v2.8.0
NormalizeWikipediaLang validates and normalizes a Wikipedia language code, returning fallback (default "en") when invalid.
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 ParseMarkdownFrontmatter ¶ added in v2.8.0
ParseMarkdownFrontmatter parses and strips a leading YAML `---` frontmatter block (up to 4 KiB), returning sanitized `title`, `description`, and remaining `body`.
func PercentEncodeUnsafeRecordURLChars ¶ added in v2.8.0
PercentEncodeUnsafeRecordURLChars percent-encodes characters that can break Markdown link syntax or inject raw tags (`(`, `)`, `[`, `]`, `<`, `>`, `\`, and ASCII whitespace).
func RecognizeAndHardenMarkdownFences ¶ added in v2.8.0
func RecognizeAndHardenMarkdownFences(rawMD string, opts RecognizeMarkdownFencesOptions) (hardened string, segments []string)
RecognizeAndHardenMarkdownFences runs the single canonical CommonMark fence recognizer & hardener (`stepCanonicalMarkdownFenceLineGo` in `sanitize.go`), returning the hardened document and alternating `[prose, fence, prose, ...]` segments.
func RedactPII ¶
RedactPII replaces email addresses, SSNs, phone numbers, and Luhn-valid payment card numbers with `[REDACTED_*]`.
func RedactPIIMarkdownSafe ¶ added in v2.8.0
RedactPIIMarkdownSafe redacts email, SSN, phone, and Luhn-valid payment cards while escaping adjacent Markdown link delimiters (`[REDACTED_EMAIL]\(javascript:...)`) so redaction never synthesizes links.
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 ResolveGatsbyPageDataTwinURL ¶ added in v2.8.0
ResolveGatsbyPageDataTwinURL builds Gatsby's static `/page-data/<pathname>/page-data.json` URL for thin `id="___gatsby"` shells while rejecting dot-traversal, encoded slashes, credentials, and SSRF hosts.
func ResolveWikipediaCanonicalFinalURL ¶ added in v2.8.0
ResolveWikipediaCanonicalFinalURL resolves the canonical `https://<lang>.wikipedia.org/wiki/<Title>` URL from requestedURL and responseFinalURL.
func ResolveWikipediaCanonicalFinalURLFull ¶ added in v2.8.0
func ResolveWikipediaCanonicalFinalURLFull(requestedURL, storedFinalURL, title, markdown string) string
ResolveWikipediaCanonicalFinalURLFull resolves the canonical Wikipedia article URL from requestedURL, storedFinalURL, cached title, and cached Markdown H1 (upgrading `oldid`/`curid` or redirect hits to canonical `/wiki/<Title>`).
func SanitizeFullMarkdownDocumentForArtifact ¶ added in v2.8.0
SanitizeFullMarkdownDocumentForArtifact sanitizes an entire Markdown document in linear O(N) time prior to R2 artifact caching and page-boundary slicing.
func SanitizeMarkdown ¶ added in v2.7.2
SanitizeMarkdown enforces the fail-closed Markdown sanitization contract (`R11-S1` / `R11-S3`):
- ONLY top-level CommonMark fenced code blocks (`0..3` spaces, zero tabs, zero open containers) preceded by a blank line or start of document keep raw content.
- Outside those top-level fences (including inside any container/list/blockquote fence or inline backtick code span), EVERY residual `<` is escaped to `<` and EVERY disallowed inline `](...)` or reference `[id]: ...` link destination is neutralized.
- Runs in strictly O(N) linear time (<40ms on 7M `[` / 3.5M `](` / 2M `<`).
func SanitizeMarkdownPageSlice ¶ added in v2.8.0
func SanitizeMarkdownPageSlice( rawFullMD string, safeOffset int, rawSliceInput string, allowPdfPageMarkers bool, checkpoints []MarkdownSliceCheckpoint, ) string
SanitizeMarkdownPageSlice sanitizes an arbitrary byte-offset slice of rawFullMD while preserving CommonMark fence polarity, container-prefixed untrusted fence state, CRLF boundaries, and inline code spans.
func SanitizeMarkdownPageSliceUTF16 ¶ added in v2.8.0
func SanitizeMarkdownPageSliceUTF16( rawFullMD string, utf16Offset int, rawSliceInput string, allowPdfPageMarkers bool, checkpoints []MarkdownSliceCheckpoint, ) string
SanitizeMarkdownPageSliceUTF16 converts a JavaScript UTF-16 code-unit offset to a UTF-8 byte offset and delegates to SanitizeMarkdownPageSlice for 100% parity on CJK, emoji, and astral Unicode inputs.
func SanitizeMarkdownWithOptions ¶ added in v2.7.2
SanitizeMarkdownWithOptions sanitizes Markdown with optional PDF page marker preservation.
func SanitizePlainMetadataText ¶ added in v2.8.0
SanitizePlainMetadataText strips smuggling/control characters, normalizes whitespace, caps length to maxLen, neutralizes unsafe Markdown links, and escapes `<` to `<` (returning `""` when empty).
func SanitizeSchemaHTTPSURL ¶ added in v2.8.0
SanitizeSchemaHTTPSURL resolves `raw` against `baseURL`, enforces public `https://` on port 443 without credentials or private/loopback/rebinding hosts, and percent-encodes unsafe Markdown link characters.
func SanitizeSchemaPlainField ¶ added in v2.8.0
SanitizeSchemaPlainField sanitizes a single-line Schema.org / hydration metadata scalar, stripping invisible characters before and after HTML entity decoding, stripping HTML tags, neutralizing unsafe Markdown links, and escaping `<` and `>`.
func SanitizeSchemaRichMarkdown ¶ added in v2.8.0
func SanitizeSchemaRichMarkdown(raw any, baseURL string, htmlToMD func(frag, base string) (string, []string), maxChars int) string
SanitizeSchemaRichMarkdown converts HTML or plain Schema.org body text into sanitized Markdown.
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 SanitizeScrapedMetadataField ¶ added in v2.8.0
SanitizeScrapedMetadataField sanitizes single-line metadata fields (`Title`, `Description`, `Author`, `SiteName`), stripping invisible smuggling characters, collapsing newlines/tabs, neutralizing unsafe Markdown links, and escaping `<` -> `<`.
func SanitizeScrapedTimestampField ¶ added in v2.8.0
SanitizeScrapedTimestampField sanitizes ISO/human timestamp metadata fields, neutralizing Markdown/HTML syntax.
func ScanGeneratorMetaTags ¶ added in v2.8.0
ScanGeneratorMetaTags linearly scans `<meta ...>` tags inside the first maxChars (default 65,536) and returns every `<meta name="generator">` content value in document order, regardless of quote style, case, or attribute order.
func ScanJSONStringLiteralAt ¶ added in v2.8.0
func ScanJSONStringLiteralAt(src string, openQuoteIdx, maxEnd int) (decoded string, nextIdx int, ok bool)
ScanJSONStringLiteralAt scans a double-quoted JSON string literal starting at `src[openQuoteIdx] == '"'` up to `maxEnd` in linear O(N) time and returns `(decoded, nextIdx, ok)` where `nextIdx` is always the scan stop offset so callers can advance past malformed or unclosed string literals without quadratic rescanning.
func SplitMarkdownByCodeFences ¶ added in v2.8.0
SplitMarkdownByCodeFences splits Markdown into alternating `[prose, codeFence, prose, codeFence, ...]` segments (`idx % 2 == 1` is always a recognized top-level CommonMark fenced code block).
func SplitPDFPagesAndMarkers ¶ added in v2.8.0
SplitPDFPagesAndMarkers splits form-feed (`\f`) separated PDF text into trimmed non-empty pages (capped at maxPages when maxPages > 0) and constructs `<!-- page N -->` marked Markdown.
func StripInvisibleSchemaChars ¶ added in v2.8.0
StripInvisibleSchemaChars strips ANSI CSI sequences, ASCII/C1 control codes, soft hyphens, zero-width characters, Bidi overrides, line/paragraph separators, Unicode Tags (`U+E0000..U+E007F`), and variation selectors (`U+E0100..U+E01EF`).
func StripInvisibleSmugglingChars ¶ added in v2.8.0
StripInvisibleSmugglingChars strips invisible Unicode Tag smuggling, variation selectors, bidi controls, zero-width characters, ANSI CSI sequences, and raw C0/C1 control bytes.
func StripMarkdownTableDividerLinesLinear ¶ added in v2.8.0
StripMarkdownTableDividerLinesLinear replaces GFM table alignment divider lines (`/^\|?[ \t:-]+\|[ \t|:-]*$/gm`) with `' '` in strictly linear O(N) time without regular-expression backtracking.
func UTF16Len ¶ added in v2.8.0
UTF16Len returns the number of UTF-16 code units in s in O(N) time with an ASCII fast path.
func UTF16OffsetToByteOffset ¶ added in v2.8.0
UTF16OffsetToByteOffset converts a JavaScript/UTF-16 code-unit offset into a valid UTF-8 byte offset in s.
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 AttrSelectorItem ¶ added in v2.8.0
type AttrSelectorItem struct {
Selector string `json:"selector"`
Attribute string `json:"attribute"`
Values []string `json:"values"`
}
AttrSelectorItem holds extracted HTML attribute values matching an AttrSelectorSpec.
func ExtractHTMLAttributesBySelectors ¶ added in v2.8.0
func ExtractHTMLAttributesBySelectors(rawHTML string, selectors []AttrSelectorSpec) []AttrSelectorItem
ExtractHTMLAttributesBySelectors extracts HTML attribute values matching up to 25 CSS selectors across up to 25,000 open tags (up to 200 values per selector) in linear O(N) time.
type AttrSelectorSpec ¶ added in v2.8.0
type AttrSelectorSpec struct {
Selector string `json:"selector"`
Attribute string `json:"attribute"`
}
AttrSelectorSpec specifies a CSS selector and target HTML attribute name for ExtractHTMLAttributesBySelectors.
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 BrowserFrameworkGlobals ¶ added in v2.8.0
type BrowserFrameworkGlobals struct {
Next bool `json:"next,omitempty"`
Nuxt bool `json:"nuxt,omitempty"`
Remix bool `json:"remix,omitempty"`
ReactRouter bool `json:"reactRouter,omitempty"`
SvelteKit bool `json:"sveltekit,omitempty"`
Angular bool `json:"angular,omitempty"`
Qwik bool `json:"qwik,omitempty"`
Solid bool `json:"solid,omitempty"`
Shopify bool `json:"shopify,omitempty"`
WP bool `json:"wp,omitempty"`
Webflow bool `json:"webflow,omitempty"`
Squarespace bool `json:"squarespace,omitempty"`
Wix bool `json:"wix,omitempty"`
}
BrowserFrameworkGlobals captures optional client-side framework globals observed during CDP browser rendering.
type CMSAutoTwinFormatted ¶ added in v2.8.0
type CMSAutoTwinFormatted struct {
ExtractorID string `json:"extractorId,omitempty"`
TwinURL string `json:"twinUrl,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
PublishedTime string `json:"publishedTime,omitempty"`
ModifiedTime string `json:"modifiedTime,omitempty"`
Markdown string `json:"markdown"`
Structured map[string]any `json:"structured,omitempty"`
Records []map[string]any `json:"records,omitempty"`
Returned int `json:"returned,omitempty"`
Total int `json:"total,omitempty"`
Truncated bool `json:"truncated,omitempty"`
NextCursor string `json:"nextCursor,omitempty"`
RawDecodedStringsForPICheck string `json:"rawDecodedStringsForPiCheck"`
}
CMSAutoTwinFormatted holds formatted Markdown, structured metadata, optional records, and prompt-injection screening text from WordPress REST or Gatsby `page-data.json` twins (`cms-twins.ts` parity).
func FormatGatsbyPageDataJSON ¶ added in v2.8.0
func FormatGatsbyPageDataJSON(rawJSON, baseURL string, htmlToMD func(frag, base string) (string, []string)) *CMSAutoTwinFormatted
FormatGatsbyPageDataJSON converts a Gatsby static `/page-data/.../page-data.json` payload into sanitized Markdown, optional structured `records[]`, metadata, and decoded PI inspection text.
func FormatWordPressRestPostJSON ¶ added in v2.8.0
func FormatWordPressRestPostJSON(rawJSON, baseURL string, htmlToMD func(frag, base string) (string, []string)) *CMSAutoTwinFormatted
FormatWordPressRestPostJSON converts a WordPress REST `/wp-json/wp/v2/(posts|pages)/<id>` JSON payload into sanitized Markdown, metadata, and decoded prompt-injection inspection text.
type CapturedJSONPayloadInput ¶ added in v2.8.0
type CapturedJSONPayloadInput struct {
URL string `json:"url,omitempty"`
Method string `json:"method,omitempty"`
Status int `json:"status,omitempty"`
Body string `json:"body"`
}
CapturedJSONPayloadInput represents a network response captured during Chromium CDP rendering.
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 LookupBuiltInManifest ¶ added in v2.8.0
func LookupBuiltInManifest(id string) *DeclarativeAdapterManifest
LookupBuiltInManifest returns the pre-validated built-in DeclarativeAdapterManifest by exact id in O(1) time.
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 DeclarativeExactSegments ¶ added in v2.8.0
DeclarativeExactSegments accepts either a boolean (`exactSegments: false` alongside `pathSegments`) or a non-negative segment count (`exactSegments: 1`).
func (DeclarativeExactSegments) MarshalJSON ¶ added in v2.8.0
func (e DeclarativeExactSegments) MarshalJSON() ([]byte, error)
MarshalJSON encodes DeclarativeExactSegments as an integer count when Count is set, or a boolean otherwise.
func (*DeclarativeExactSegments) UnmarshalJSON ¶ added in v2.8.0
func (e *DeclarativeExactSegments) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes either a boolean or a non-negative integer segment count.
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"`
Records []map[string]any `json:"records,omitempty"`
Total *int `json:"total,omitempty"`
Returned *int `json:"returned,omitempty"`
Truncated *bool `json:"truncated,omitempty"`
NextCursor string `json:"nextCursor,omitempty"`
}
DeclarativeFormattedDoc holds the structured Markdown and metadata produced from a declarative twin payload.
func FormatDeclarativeTwinByURL ¶ added in v2.8.0
func FormatDeclarativeTwinByURL(requestURL, rawBody, origURL string) (*DeclarativeFormattedDoc, bool)
FormatDeclarativeTwinByURL resolves the declarative twin for requestURL, overrides origURL when non-empty, and formats rawBody.
func FormatJSONWithExtractSpec ¶ added in v2.8.0
func FormatJSONWithExtractSpec(rawBody string, ext DeclarativeExtractSpec, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatJSONWithExtractSpec formats a raw JSON/Inertia twin payload against an explicit DeclarativeExtractSpec and route params.
func FormatTwinOnManifest ¶ added in v2.8.0
func FormatTwinOnManifest(m *DeclarativeAdapterManifest, requestURL, rawBody, origURL string) (*DeclarativeFormattedDoc, bool)
FormatTwinOnManifest resolves and formats a twin body against an explicit DeclarativeAdapterManifest.
func FormatTwinOnValidatedManifest ¶ added in v2.8.0
func FormatTwinOnValidatedManifest(m *DeclarativeAdapterManifest, requestURL, rawBody, origURL string) (*DeclarativeFormattedDoc, bool)
FormatTwinOnValidatedManifest resolves and formats a twin body against an already-validated DeclarativeAdapterManifest.
func FormatYAMLFrontmatterCard ¶ added in v2.8.0
func FormatYAMLFrontmatterCard(rawMD, fallbackTitle string) *DeclarativeFormattedDoc
FormatYAMLFrontmatterCard parses YAML model/dataset card frontmatter (e.g. Hugging Face README.md) into a sanitized GFM metadata table + Markdown body.
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 *DeclarativeExactSegments `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 DeclarativePostFetchResult ¶ added in v2.8.0
type DeclarativePostFetchResult struct {
ExtractorID string `json:"extractorId"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Author string `json:"author,omitempty"`
PublishedTime string `json:"publishedTime,omitempty"`
Markdown string `json:"markdown"`
Links []string `json:"links,omitempty"`
Records []map[string]any `json:"records,omitempty"`
Total *int `json:"total,omitempty"`
Returned *int `json:"returned,omitempty"`
Truncated *bool `json:"truncated,omitempty"`
NextCursor string `json:"nextCursor,omitempty"`
}
DeclarativePostFetchResult holds the structured output produced by a post-fetch declarative HTML site adapter.
func ApplyDeclarativeHTMLExtractor ¶ added in v2.8.0
func ApplyDeclarativeHTMLExtractor( rawHTML, baseURL, currentMD string, htmlToMD func(frag, base string) (string, []string), ) (*DeclarativePostFetchResult, bool)
ApplyDeclarativeHTMLExtractor runs matching post-fetch declarative htmlRoutes for baseURL across all embedded manifests.
func ExtractHTMLOnManifest ¶ added in v2.8.0
func ExtractHTMLOnManifest(m *DeclarativeAdapterManifest, rawHTML, baseURL, currentMD string, htmlToMD func(frag, base string) (string, []string)) (*DeclarativePostFetchResult, bool)
ExtractHTMLOnManifest executes HTMLRoutes against an explicit DeclarativeAdapterManifest.
func ExtractHTMLOnValidatedManifest ¶ added in v2.8.0
func ExtractHTMLOnValidatedManifest(cp *DeclarativeAdapterManifest, rawHTML, baseURL, currentMD string, htmlToMD func(frag, base string) (string, []string)) (*DeclarativePostFetchResult, bool)
ExtractHTMLOnValidatedManifest executes HTMLRoutes against an already-validated DeclarativeAdapterManifest.
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) MarshalJSON ¶ added in v2.8.0
func (s DeclarativeSegmentSpec) MarshalJSON() ([]byte, error)
MarshalJSON encodes a literal segment as a JSON string and a parameter segment as a JSON object.
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 ResolveTwinOnManifest ¶ added in v2.8.0
func ResolveTwinOnManifest(m *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool)
ResolveTwinOnManifest evaluates twin resolution against an explicit (ad-hoc or custom) DeclarativeAdapterManifest.
func ResolveTwinOnValidatedManifest ¶ added in v2.8.0
func ResolveTwinOnValidatedManifest(cp *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool)
ResolveTwinOnValidatedManifest evaluates twin resolution against an already-validated DeclarativeAdapterManifest.
func (*DeclarativeTwinMatch) CommerceMode ¶ added in v2.8.0
func (m *DeclarativeTwinMatch) CommerceMode() string
CommerceMode returns the matched route's commerceMode (if any).
func (*DeclarativeTwinMatch) EffectiveMaxBytes ¶ added in v2.8.1
func (m *DeclarativeTwinMatch) EffectiveMaxBytes() int
EffectiveMaxBytes returns the adapter route's configured twin maxBytes ceiling, defaulting to 2 MiB for JSON twins and 4 MiB for text/XML/patch twins so every built-in and community adapter inherits a safe edge WASM memory ceiling automatically.
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) RawAccept ¶ added in v2.8.0
func (m *DeclarativeTwinMatch) RawAccept() string
RawAccept returns the raw un-normalized Accept string declared on the matched twin route.
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"`
MaxBytes int `json:"maxBytes,omitempty"`
}
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 DetectSiteFrameworkParams ¶ added in v2.8.0
type DetectSiteFrameworkParams struct {
URL string `json:"url,omitempty"`
Body string `json:"body,omitempty"`
ContentSource string `json:"contentSource,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Globals *BrowserFrameworkGlobals `json:"globals,omitempty"`
}
DetectSiteFrameworkParams configures bounded 64 KiB framework and platform detection.
type DetectedSiteStack ¶ added in v2.8.0
type DetectedSiteStack struct {
Source string `json:"source"`
Platform string `json:"platform,omitempty"`
Framework string `json:"framework,omitempty"`
Generators []string `json:"generators"`
Signals []string `json:"signals"`
ContentFlags []string `json:"contentFlags,omitempty"`
}
DetectedSiteStack summarizes the detected CMS/commerce/docs platform and frontend framework for a response.
func DetectSiteFramework ¶ added in v2.8.0
func DetectSiteFramework(p DetectSiteFrameworkParams) DetectedSiteStack
DetectSiteFramework detects the site platform and frontend framework from bounded 64 KiB HTML or origin-markdown text, allowlisted response headers, hostname suffixes, and optional CDP browser globals.
type DistilledRecordsResult ¶ added in v2.8.0
type DistilledRecordsResult struct {
Records []map[string]any `json:"records"`
Markdown string `json:"markdown"`
Returned int `json:"returned"`
Total *int `json:"total,omitempty"`
Truncated bool `json:"truncated,omitempty"`
NextCursor string `json:"nextCursor,omitempty"`
}
DistilledRecordsResult holds structured records, GFM Markdown table, and pagination metadata distilled from a JSON tree.
func DistillStructuredRecordsFull ¶ added in v2.8.0
func DistillStructuredRecordsFull(root any, baseURL string, maxRecords int) *DistilledRecordsResult
DistillStructuredRecordsFull walks an arbitrary JSON state or XHR payload tree (`maxVisited = 2_500`, `maxDepth = 12`) and returns the full DistilledRecordsResult (records + GFM Markdown + pagination metadata), or nil when none matches.
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 ExtractedDocumentFull ¶ added in v2.8.0
type ExtractedDocumentFull struct {
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Author string `json:"author,omitempty"`
PublishedTime string `json:"publishedTime,omitempty"`
ModifiedTime string `json:"modifiedTime,omitempty"`
SiteName string `json:"siteName,omitempty"`
WordCount int `json:"wordCount,omitempty"`
Language string `json:"language,omitempty"`
Favicon string `json:"favicon,omitempty"`
OGImage string `json:"ogImage,omitempty"`
CanonicalURL string `json:"canonicalUrl,omitempty"`
MarkdownAlternateURL string `json:"markdownAlternateUrl,omitempty"`
RobotsMeta string `json:"robotsMeta,omitempty"`
ExtractorID string `json:"extractorId,omitempty"`
Records []map[string]any `json:"records,omitempty"`
Total *int `json:"total,omitempty"`
Returned *int `json:"returned,omitempty"`
NextCursor string `json:"nextCursor,omitempty"`
InertiaHydrated bool `json:"inertiaHydrated,omitempty"`
Markdown string `json:"markdown"`
RawSanitizedMarkdown string `json:"rawSanitizedMarkdown,omitempty"`
Text string `json:"text,omitempty"`
Links []string `json:"links"`
Images []ImageInfo `json:"images"`
Branding BrandingProfile `json:"branding"`
StructuredData []map[string]any `json:"structuredData,omitempty"`
TotalChars int `json:"totalChars"`
ReturnedChars int `json:"returnedChars"`
Truncated bool `json:"truncated,omitempty"`
NextOffset *int `json:"nextOffset,omitempty"`
}
ExtractedDocumentFull holds the full-fidelity Markdown, metadata, links, images, branding, structured JSON-LD entities, and pagination state extracted from an HTML document.
func ExtractHTMLDocumentFull ¶ added in v2.8.0
func ExtractHTMLDocumentFull(rawHTML string, opts FullExtractOptions) ExtractedDocumentFull
ExtractHTMLDocumentFull extracts clean GFM Markdown, metadata, links, images, branding, structured JSON-LD data, and optional paginated slices from raw HTML without external DOM dependencies.
type FormattedPayloadDoc ¶ added in v2.8.0
type FormattedPayloadDoc struct {
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Markdown string `json:"markdown"`
Structured any `json:"structured,omitempty"`
}
FormattedPayloadDoc holds the formatted Markdown, extracted title/description metadata, and optional parsed structured representation of a non-HTML payload (JSON, OpenAPI, Jupyter, vCard, iCalendar, Feed, CSV, Patch, Source).
func FormatDelimitedTableToMarkdown ¶ added in v2.8.0
func FormatDelimitedTableToMarkdown(raw, sep, titleHint string) *FormattedPayloadDoc
FormatDelimitedTableToMarkdown formats RFC 4180 CSV and TSV payloads into a clean GFM Markdown table with column preview and row count summary.
func FormatFeedXMLToMarkdown ¶ added in v2.8.0
func FormatFeedXMLToMarkdown(raw, baseURL string) (doc *FormattedPayloadDoc, links []string)
FormatFeedXMLToMarkdown formats RSS 2.0, RDF, and Atom XML feeds into structured Markdown with per-item headings, public HTTPS links, publication dates, and summaries.
func FormatGitPatchToMarkdown ¶ added in v2.8.0
func FormatGitPatchToMarkdown(raw, urlStr string) *FormattedPayloadDoc
FormatGitPatchToMarkdown formats `git format-patch` and unified `.patch`/`.diff` payloads into clean Markdown with commit metadata bullets and a 4-tilde `diff` code fence.
func FormatICalendarToMarkdown ¶ added in v2.8.0
func FormatICalendarToMarkdown(raw string) *FormattedPayloadDoc
FormatICalendarToMarkdown formats RFC 5545 iCalendar (`BEGIN:VCALENDAR`) feeds into structured Markdown event summaries.
func FormatInertiaPagePropsToMarkdown ¶ added in v2.8.0
func FormatInertiaPagePropsToMarkdown(props map[string]any, pageURL string) *FormattedPayloadDoc
FormatInertiaPagePropsToMarkdown renders an Inertia.js `data-page` payload (`{ component, props, url, version }`) into a clean GFM summary of the component and its non-boilerplate props.
func FormatJupyterNotebookToMarkdown ¶ added in v2.8.0
func FormatJupyterNotebookToMarkdown(raw, urlStr string) *FormattedPayloadDoc
FormatJupyterNotebookToMarkdown converts a Jupyter Notebook (`.ipynb`) JSON string into clean Markdown, rendering Markdown cells natively, wrapping code cells in kernel-language fences, and keeping concise text/error outputs.
func FormatOpenAPISpecToMarkdown ¶ added in v2.8.0
func FormatOpenAPISpecToMarkdown(raw, urlStr string) *FormattedPayloadDoc
FormatOpenAPISpecToMarkdown formats OpenAPI 3.x and Swagger 2.0 specifications (in either JSON or YAML format via `YAMLToJSON`) into a compact, navigable GFM Markdown API reference.
func FormatSourceCodeURLToMarkdown ¶ added in v2.8.0
func FormatSourceCodeURLToMarkdown(raw, urlStr, contentType string) *FormattedPayloadDoc
FormatSourceCodeURLToMarkdown wraps raw source-code and configuration files (`Cargo.toml`, `.yaml`, `.rs`, `.go`, `.py`, `.ts`, `Dockerfile`, `Makefile`, etc.) served as plain text into fenced Markdown code blocks with accurate filename/package titles.
func FormatVCardToMarkdown ¶ added in v2.8.0
func FormatVCardToMarkdown(raw string) *FormattedPayloadDoc
FormatVCardToMarkdown formats RFC 6350 vCard (`BEGIN:VCARD`) contact payloads into clean Markdown.
func TryParseJSONPayloadForScrape ¶ added in v2.8.0
func TryParseJSONPayloadForScrape(raw, urlStr string) *FormattedPayloadDoc
TryParseJSONPayloadForScrape parses JSON scrape payloads, upgrading Jupyter `.ipynb` notebooks and OpenAPI/Swagger specs to native GFM Markdown and formatting generic JSON objects/arrays in pretty-printed `json` fences with sanitized metadata.
type FullExtractOptions ¶ added in v2.8.0
type FullExtractOptions struct {
BaseURL string `json:"baseUrl,omitempty"`
OnlyMainContent bool `json:"onlyMainContent,omitempty"`
IncludeImages bool `json:"includeImages,omitempty"`
IncludeTags []string `json:"includeTags,omitempty"`
ExcludeTags []string `json:"excludeTags,omitempty"`
MaxChars int `json:"maxChars,omitempty"`
Offset int `json:"offset,omitempty"`
RedactPII bool `json:"redactPii,omitempty"`
AllowPdfPageMarkers bool `json:"allowPdfPageMarkers,omitempty"`
IsPDF bool `json:"isPdf,omitempty"`
PreserveOriginMD bool `json:"preserveOriginMarkdown,omitempty"`
IsFragment bool `json:"isFragment,omitempty"`
MaxScanChars int `json:"maxScanChars,omitempty"`
}
FullExtractOptions configures full-fidelity HTML document extraction and Markdown finalization.
type HTMLDoc ¶ added in v2.8.0
type HTMLDoc struct {
HTMLNode
}
HTMLDoc represents a parsed bounded HTML5 document ready for linear-time CSS querying.
func ParseHTMLDoc ¶ added in v2.8.0
ParseHTMLDoc parses rawHTML (capped at maxChars, defaulting to 2 MiB with a 4 MiB hard ceiling) into a linear-time queryable HTMLDoc.
type HTMLNode ¶ added in v2.8.0
type HTMLNode struct {
// contains filtered or unexported fields
}
HTMLNode wraps a bounded DOM element or document root with linear-time CSS selection and extraction helpers.
func (*HTMLNode) Attr ¶ added in v2.8.0
Attr returns the value of attribute name (case-insensitive) and whether it exists on this element.
func (*HTMLNode) AttrOf ¶ added in v2.8.0
AttrOf returns First(subSelector).AttrOrEmpty(name), or "" if absent.
func (*HTMLNode) AttrOrEmpty ¶ added in v2.8.0
AttrOrEmpty returns the value of attribute name (case-insensitive), or "" if absent.
func (*HTMLNode) DLMap ¶ added in v2.8.0
DLMap pairs <dt> -> following <dd> inside <dl> or wrapper containers, normalizing <dt> keys to lowercase trimmed strings with trailing colons stripped.
func (*HTMLNode) First ¶ added in v2.8.0
First returns the first matching descendant HTMLNode, or nil if none match.
func (*HTMLNode) HTML ¶ added in v2.8.0
HTML returns serialized inner HTML. When subSelector is provided, serializes the inner HTML of First(subSelector[0]).
func (*HTMLNode) Select ¶ added in v2.8.0
Select returns up to limit matching descendant HTMLNodes in DOM document order (capped at 5,000).
func (*HTMLNode) TableRows ¶ added in v2.8.0
TableRows extracts a 2D slice of cleaned cell text from <tr> -> <th>/<td> rows.
func (*HTMLNode) Tag ¶ added in v2.8.0
Tag returns the lowercase HTML tag name for element nodes, or "" for the document root.
type HydratedFrameworkStateResult ¶ added in v2.8.0
type HydratedFrameworkStateResult struct {
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Markdown string `json:"markdown"`
Framework string `json:"framework"`
Records []map[string]any `json:"records,omitempty"`
Structured map[string]any `json:"structured,omitempty"`
Total int `json:"total,omitempty"`
Returned int `json:"returned,omitempty"`
Truncated bool `json:"truncated,omitempty"`
NextCursor string `json:"nextCursor,omitempty"`
RawDecodedStringsForPICheck string `json:"rawDecodedStringsForPiCheck,omitempty"`
}
HydratedFrameworkStateResult holds rich prose and/or homogeneous structured records extracted from SSR hydration containers (`framework-hydration.ts` parity).
func DistillCapturedJSONResponses ¶ added in v2.8.0
func DistillCapturedJSONResponses(inputs []CapturedJSONPayloadInput, baseURL string, htmlToMD func(frag, base string) (string, []string)) *HydratedFrameworkStateResult
DistillCapturedJSONResponses distills same-origin `200 OK` `application/json` XHR/Fetch responses captured by Chromium CDP rendering into sanitized `records[]`, GFM Markdown, `structured` metadata, and decoded PI strings.
func ExtractFromParsedStateTree ¶ added in v2.8.0
func ExtractFromParsedStateTree(root any, framework, baseURL string, htmlToMD func(frag, base string) (string, []string), rawSourceHint string, hasUnicodeTag bool) *HydratedFrameworkStateResult
ExtractFromParsedStateTree walks a parsed framework state tree (Next.js, Nuxt, Remix, Angular, Wix, Squarespace, Substack, Gatsby, Inertia) to extract rich prose sections and/or homogeneous `records[]`.
func ExtractNextRSCFlight ¶ added in v2.8.0
func ExtractNextRSCFlight(rawHTML, baseURL string, htmlToMD func(frag, base string) (string, []string)) *HydratedFrameworkStateResult
ExtractNextRSCFlight extracts prose and structured records from Next.js App Router RSC Flight streams (`self.__next_f.push([1, "..."])`), including `$` Flight chunk reference resolution, in linear O(N) time.
func RecoverSSRHydrationContent ¶ added in v2.8.0
func RecoverSSRHydrationContent(rawHTML, baseURL string, htmlToMD func(frag, base string) (string, []string)) *HydratedFrameworkStateResult
RecoverSSRHydrationContent recovers rich prose and/or structured `records[]` from embedded SSR/SPA state containers: `__NEXT_DATA__`, `__NUXT_DATA__` (including Nuxt 3/4 `devalue`), Next App Router RSC `__next_f`, Inertia `data-page` (with `<` pre-escaping before entity decode), Angular `ng-state`, Remix `__remixContext`, Apollo `__APOLLO_STATE__`, Wix `wix-viewer-model`, Squarespace `SQUARESPACE_CONTEXT`, and Substack `window._preloads`.
type ImageInfo ¶
ImageInfo describes an image discovered on a page.
func ExtractMarkdownLinksAndImages ¶ added in v2.8.0
ExtractMarkdownLinksAndImages scans non-fenced Markdown prose in O(N) time and returns resolved HTTP/HTTPS links (up to 250) and non-decorative images (up to 60).
func ExtractMarkdownLinksImagesAndMeta ¶ added in v2.8.0
func ExtractMarkdownLinksImagesAndMeta(md, baseURL string, includeImages bool) (links []string, images []ImageInfo, title, description string)
ExtractMarkdownLinksImagesAndMeta extracts resolved links, optional images, and frontmatter/H1 title + description.
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 MarkdownFenceRecognizerState ¶ added in v2.8.0
type MarkdownFenceRecognizerState struct {
InFence bool
FenceChar string
FenceLen int
EffectiveFenceLen int
PrevLineWasAsciiBlank bool
PossiblyInList bool
EscapedUntrusted *MarkdownSliceEscapedUntrusted
}
MarkdownFenceRecognizerState represents the exported state of the canonical CommonMark fence recognizer.
type MarkdownSliceCheckpoint ¶ added in v2.8.0
type MarkdownSliceCheckpoint struct {
Pos int `json:"pos"`
UTF16Pos *int `json:"utf16Pos,omitempty"`
InFence bool `json:"inFence"`
FenceChar string `json:"fenceChar"`
FenceLen int `json:"fenceLen"`
EffectiveFenceLen int `json:"effectiveFenceLen"`
FenceIndent int `json:"fenceIndent"`
ActiveListIndent int `json:"activeListIndent"`
ListIndents []int `json:"listIndents,omitempty"`
PrevLineWasParagraph bool `json:"prevLineWasParagraph"`
PrevLineWasAsciiBlank bool `json:"prevLineWasAsciiBlank"`
PossiblyInList bool `json:"possiblyInList"`
EscapedUntrusted *MarkdownSliceEscapedUntrusted `json:"escapedUntrusted"`
}
MarkdownSliceCheckpoint stores canonical CommonMark fence-recognizer state at periodic offsets.
func ComputeMarkdownSliceCheckpoints ¶ added in v2.8.0
func ComputeMarkdownSliceCheckpoints(rawFullMD string, stepChars int) []MarkdownSliceCheckpoint
type MarkdownSliceEscapedUntrusted ¶ added in v2.8.0
type MarkdownSliceEscapedUntrusted struct {
Ch string `json:"ch"`
Len int `json:"len"`
NeedBlockquote bool `json:"needBlockquote"`
}
MarkdownSliceEscapedUntrusted records an escaped untrusted fence opener across slice checkpoints.
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.
type ParsedWikipediaArticle ¶ added in v2.8.0
type ParsedWikipediaArticle struct {
CanonicalURL string `json:"canonicalUrl"`
Host string `json:"host"`
Lang string `json:"lang"`
Title string `json:"title"`
EncodedTitle string `json:"encodedTitle"`
SectionAnchor string `json:"sectionAnchor,omitempty"`
CanonicalTitle string `json:"canonicalTitle,omitempty"`
UnderscoredTitle string `json:"underscoredTitle,omitempty"`
}
ParsedWikipediaArticle holds the normalized canonical components of a Wikipedia article URL.
func ParseWikipediaArticleURL ¶ added in v2.8.0
func ParseWikipediaArticleURL(rawURL string) *ParsedWikipediaArticle
ParseWikipediaArticleURL parses and canonicalizes a Wikipedia article URL (`https://<lang>.wikipedia.org/wiki/<Title>`, mobile `<lang>.m.wikipedia.org`, and `/w/index.php?title=` or `?oldid=`/`?curid=`), returning nil for non-Wikipedia URLs, credentials, `/w/api.php`, `/w/rest.php`, non-view/render actions, diffs, traversal paths, or disallowed namespaces.
type PromptInjectionResult ¶ added in v2.8.0
type PromptInjectionResult struct {
Detected bool `json:"detected"`
Triggers []string `json:"triggers"`
}
PromptInjectionResult reports whether indirect prompt-injection directives were detected.
func DetectPromptInjection ¶ added in v2.8.0
func DetectPromptInjection(markdown, rawHTML string) PromptInjectionResult
DetectPromptInjection scans extracted Markdown (including code spans and fenced/indented code blocks) and raw HTML for indirect prompt-injection payloads (`totalScore >= 3`) in linear O(N) time.
type RecognizeMarkdownFencesOptions ¶ added in v2.8.0
type RecognizeMarkdownFencesOptions struct {
Harden bool
PreserveCrLf bool
InitialReopenedFence *ReopenedMarkdownFence
InitialState *MarkdownFenceRecognizerState
SkipLeadingSeparatorEmptyLine bool
}
RecognizeMarkdownFencesOptions configures RecognizeAndHardenMarkdownFences.
type ReopenedMarkdownFence ¶ added in v2.8.0
type ReopenedMarkdownFence struct {
Ch string `json:"ch"`
Len int `json:"len"`
EffectiveLen int `json:"effectiveLen,omitempty"`
}
ReopenedMarkdownFence describes an open top-level fenced code block carried into a slice.
type UniversalSchemaOrgResult ¶ added in v2.8.0
type UniversalSchemaOrgResult struct {
ExtractorID string `json:"extractorId,omitempty"`
PrimaryType string `json:"primaryType,omitempty"`
SchemaType string `json:"schemaType,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Author string `json:"author,omitempty"`
PublishedTime string `json:"publishedTime,omitempty"`
ModifiedTime string `json:"modifiedTime,omitempty"`
SiteName string `json:"siteName,omitempty"`
Markdown string `json:"markdown,omitempty"`
HeaderMarkdown string `json:"headerMarkdown,omitempty"`
Structured map[string]any `json:"structured,omitempty"`
Records []map[string]any `json:"records,omitempty"`
Returned int `json:"returned,omitempty"`
Total int `json:"total,omitempty"`
Truncated bool `json:"truncated,omitempty"`
NextCursor string `json:"nextCursor,omitempty"`
RawJSONLDForPICheck string `json:"rawJsonLdForPiCheck,omitempty"`
}
UniversalSchemaOrgResult holds structured metadata, records, and synthesized Markdown extracted from `<script type="application/ld+json">` blocks (`schema-org.ts` parity).
func ExtractUniversalSchemaOrg ¶ added in v2.8.0
func ExtractUniversalSchemaOrg(rawHTML, baseURL string, htmlToMD func(frag, base string) (string, []string)) *UniversalSchemaOrgResult
ExtractUniversalSchemaOrg extracts rich Schema.org JSON-LD entities from HTML in linear O(N) time. Skips `JobPosting`, standalone `Product`, and `BreadcrumbList` so specialized extractors remain authoritative, and never emits `records: []` on empty/unmatched trees.
type ValidatedEasyPrivacyResult ¶ added in v2.8.1
type ValidatedEasyPrivacyResult struct {
OK bool `json:"ok"`
Reason string `json:"reason,omitempty"`
Version string `json:"version,omitempty"`
HeaderLastModified *string `json:"headerLastModified"`
RawParsedHostCount int `json:"rawParsedHostCount,omitempty"`
JoinedHosts string `json:"joinedHosts,omitempty"`
}
ValidatedEasyPrivacyResult holds the result of ParseAndValidateEasyPrivacyGo.
func ParseAndValidateEasyPrivacyGo ¶ added in v2.8.1
func ParseAndValidateEasyPrivacyGo(rawText string, byteLength int, previousHostCount int, extraNeverBlockHosts []string) ValidatedEasyPrivacyResult
ParseAndValidateEasyPrivacyGo parses and validates an EasyPrivacy list in a single native Go pass.
type YouTubeWatchMeta ¶ added in v2.8.0
type YouTubeWatchMeta struct {
VideoID string `json:"videoId,omitempty"`
Title string `json:"title"`
Author string `json:"author,omitempty"`
Description string `json:"description,omitempty"`
Duration string `json:"duration,omitempty"`
LengthSeconds int `json:"lengthSeconds,omitempty"`
ViewCount int64 `json:"viewCount,omitempty"`
URL string `json:"url,omitempty"`
Markdown string `json:"markdown"`
}
YouTubeWatchMeta holds structured video metadata and synthesized Markdown extracted from a YouTube watch page's `ytInitialPlayerResponse`.
func ExtractYouTubeWatchMetadataFromHTML ¶ added in v2.8.0
func ExtractYouTubeWatchMetadataFromHTML(rawHTML, urlStr string) *YouTubeWatchMeta
ExtractYouTubeWatchMetadataFromHTML extracts `ytInitialPlayerResponse.videoDetails` metadata and clean Markdown from a YouTube watch page HTML document without launching a browser.