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 ClampMaxAgeMsByPolicy(maxAgeMs int, urlStr, adapterID string) int
- 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 ExtractFirstRawElementHTML(rawHTML string, selectors ...RawElementSelector) (string, bool)
- func ExtractFirstRawElementOrBoundedHTML(rawHTML string, selectors ...RawElementSelector) (string, 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 ExtractMicrodataProduct(rawBody, finalURL, fallbackTitle, fallbackDescription string) map[string]any
- 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 ExtractSlugTitleFromURL(rawURL 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 FormatWave2cEconJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
- func FormatWave2cHealthTransportJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
- func FormatWave2cIpArchivesJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
- func FormatWave2cLawJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
- func FormatWave2cMoneyJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
- func FormatWave2cMoneyTextMode(mode string, rawBody string, params map[string]string, origURL string) (string, bool)
- func FormatWave2cScienceJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
- func FormatWave2dJobsJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
- func FormatWave2dLocalJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
- func FormatWave2dLocalTextMode(mode string, rawBody string, params map[string]string, origURL string) (string, bool)
- func FormatWave2dRetailJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
- func FormatWave2dRetailTextMode(mode string, rawBody string, params map[string]string, origURL string) (string, bool)
- func FormatWave2dSportsMiscJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
- func FormatWave2dSportsMiscTextMode(mode string, rawBody string, params map[string]string, origURL string) (string, bool)
- func GetRegistrableDomain(host string) string
- func HasPDFToText() bool
- func HasPrivateSharedHostingSuffix(host string) bool
- func HasRawOrEncodedUnicodeTag(raw string) bool
- func InspectRawSchemaOrgJSONLD(rawHTML string) string
- func IsBoschEbikeErrorCodeJSONMode(mode string) bool
- 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 IsSafePublicHostname(rawHost string) bool
- func IsValidUserAgentHeaderValue(ua string) bool
- func IsWave2cEconHTMLMode(mode string) bool
- func IsWave2cEconJSONMode(mode string) bool
- func IsWave2cHealthTransportHTMLMode(mode string) bool
- func IsWave2cHealthTransportJSONMode(mode string) bool
- func IsWave2cHealthTransportTextMode(mode string) bool
- func IsWave2cIpArchivesHTMLMode(mode string) bool
- func IsWave2cIpArchivesJSONMode(mode string) bool
- func IsWave2cLawHTMLMode(mode string) bool
- func IsWave2cLawJSONMode(mode string) bool
- func IsWave2cMoneyHTMLMode(mode string) bool
- func IsWave2cMoneyJSONMode(mode string) bool
- func IsWave2cMoneyTextMode(mode string) bool
- func IsWave2cScienceHTMLMode(mode string) bool
- func IsWave2cScienceJSONMode(mode string) bool
- func IsWave2cScienceTextMode(mode string) bool
- func IsWave2dDevHTMLMode(mode string) bool
- func IsWave2dDevJSONMode(mode string) bool
- func IsWave2dDevTextMode(mode string) bool
- func IsWave2dJobsHTMLMode(mode string) bool
- func IsWave2dJobsJSONMode(mode string) bool
- func IsWave2dLocalHTMLMode(mode string) bool
- func IsWave2dLocalJSONMode(mode string) bool
- func IsWave2dLocalTextMode(mode string) bool
- func IsWave2dMediaVideoHTMLMode(mode string) bool
- func IsWave2dMediaVideoJSONMode(mode string) bool
- func IsWave2dMediaVideoTextMode(mode string) bool
- func IsWave2dRetailHTMLMode(mode string) bool
- func IsWave2dRetailJSONMode(mode string) bool
- func IsWave2dRetailTextMode(mode string) bool
- func IsWave2dSportsMiscHTMLMode(mode string) bool
- func IsWave2dSportsMiscJSONMode(mode string) bool
- func IsWave2dSportsMiscTextMode(mode 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 NormalizeStrictGTIN(raw 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 RegisterExternalCommerceMode(mode string, ...)
- func RegisterExternalHTMLMode(mode string, ...)
- func RegisterExternalHTMLModeLazy(mode string, ...)
- func RerankPassages(doc, query string, maxChars int) string
- func ResolveEffectiveMinIntervalMs(reqMinIntervalMs int, host string) int
- func ResolveEffectiveUserAgent(profile, host, fallback string) string
- func ResolveGatsbyPageDataTwinURL(rawHTML, pageFinalURL, selfHost string) string
- func ResolveWikipediaCanonicalFinalURL(requestedURL, responseFinalURL string) string
- func ResolveWikipediaCanonicalFinalURLFull(requestedURL, storedFinalURL, title, markdown string) string
- func RunWave2cEconHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)
- func RunWave2cHealthTransportHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)
- func RunWave2cIpArchivesHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)
- func RunWave2cLawHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)
- func RunWave2cMoneyHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)
- func RunWave2cScienceHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)
- func RunWave2dJobsHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)
- func RunWave2dLocalHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)
- func RunWave2dRetailHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)
- func RunWave2dSportsMiscHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)
- 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 ScrubTwinURLSecrets(rawURL string) string
- 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 AdapterPolicy
- 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 DeclarativeDetectOnlySpec
- type DeclarativeDynamicKeyPath
- type DeclarativeExactSegments
- type DeclarativeExtractSpec
- type DeclarativeFindInArray
- type DeclarativeFindLangSpec
- type DeclarativeFormattedDoc
- func FormatBoschEbikeErrorCodeJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatDeclarativeTwinByURL(requestURL, rawBody, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatDeclarativeTwinByURLWithOptions(requestURL, rawBody, origURL string, opts DeclarativeResolveOptions) (*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 FormatTwinOnManifestWithOptions(m *DeclarativeAdapterManifest, requestURL, rawBody, origURL string, ...) (*DeclarativeFormattedDoc, bool)
- func FormatTwinOnValidatedManifest(m *DeclarativeAdapterManifest, requestURL, rawBody, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatTwinOnValidatedManifestWithOptions(m *DeclarativeAdapterManifest, requestURL, rawBody, origURL string, ...) (*DeclarativeFormattedDoc, bool)
- func FormatWave2aJSONPublic(mode string, rawBytes []byte, origURL string, ...) (*DeclarativeFormattedDoc, bool)
- func FormatWave2cHealthTransportJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatWave2cHealthTransportTextDoc(mode string, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatWave2cIpArchivesJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatWave2cMoneyJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatWave2cMoneyTextDoc(mode string, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatWave2cScienceJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatWave2cScienceTextDoc(mode string, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatWave2dDevJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatWave2dDevTextDoc(mode string, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatWave2dJobsJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatWave2dLocalJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatWave2dLocalTextDoc(mode string, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatWave2dMediaVideoJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatWave2dMediaVideoTextDoc(mode string, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatWave2dRetailJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatWave2dRetailTextDoc(mode string, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatWave2dSportsMiscJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
- func FormatWave2dSportsMiscTextDoc(mode string, rawBody string, params map[string]string, 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)
- func RunWave2cMoneyHTMLResult(mode string, rawHTML string, baseURL string, currentMD string, ...) (*DeclarativePostFetchResult, bool)
- func Wave2dDevRunHTML(mode string, rawHTML string, baseURL string, extractorID string) *DeclarativePostFetchResult
- func Wave2dJobsRunHTML(mode string, rawHTML string, baseURL string, extractorID string) *DeclarativePostFetchResult
- func Wave2dLocalRunHTML(mode string, ctx *htmlExtractContextDeclHTML, extractorID string) *DeclarativePostFetchResult
- func Wave2dMediaVideoRunHTML(mode string, rawHTML string, baseURL string, extractorID string) *DeclarativePostFetchResult
- func Wave2dRetailRunHTML(mode string, ctx *htmlExtractContextDeclHTML, extractorID string) *DeclarativePostFetchResult
- func Wave2dSportsMiscRunHTML(mode string, rawHTML string, baseURL string, extractorID string) *DeclarativePostFetchResult
- type DeclarativePreferWhereSpec
- type DeclarativeQueryParamSpec
- type DeclarativeReplaceSpec
- type DeclarativeResolveOptions
- type DeclarativeRouteSpec
- type DeclarativeScanSegmentSpec
- type DeclarativeSectionFilterSpec
- type DeclarativeSectionSpec
- type DeclarativeSegmentSpec
- type DeclarativeSortSpec
- type DeclarativeSplitSegmentSpec
- type DeclarativeSubFieldsJoin
- type DeclarativeTableColumn
- type DeclarativeTreeCommentsSpec
- type DeclarativeTwinMatch
- func ResolveDeclarativeTwin(rawURL string) (*DeclarativeTwinMatch, bool)
- func ResolveDeclarativeTwinWithOptions(rawURL string, opts DeclarativeResolveOptions) (*DeclarativeTwinMatch, bool)
- func ResolveTwinOnManifest(m *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool)
- func ResolveTwinOnManifestWithOptions(m *DeclarativeAdapterManifest, rawURL string, opts DeclarativeResolveOptions) (*DeclarativeTwinMatch, bool)
- func ResolveTwinOnValidatedManifest(cp *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool)
- func ResolveTwinOnValidatedManifestWithOptions(cp *DeclarativeAdapterManifest, rawURL string, opts DeclarativeResolveOptions) (*DeclarativeTwinMatch, bool)
- 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) IsDescendantOf(ancestor *HTMLNode) bool
- func (n *HTMLNode) NodeKey() any
- func (n *HTMLNode) OuterHTML() string
- func (n *HTMLNode) SameNode(other *HTMLNode) bool
- 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 PlatformTwinCandidate
- type PlatformTwinDiscoveryInput
- type PromptInjectionResult
- type RawElementSelector
- 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 DefaultPolicyUserAgent = "EdgeFetch/2.7 (bot@edgefetch.dev)"
DefaultPolicyUserAgent is the default honest EdgeFetch User-Agent header.
const (
// FrameworkDetectWindowChars bounds framework/platform detection to the first 64 KiB (65,536 UTF-16 code units).
FrameworkDetectWindowChars = 65_536
)
Variables ¶
var AllowlistedUserAgentProfiles = map[string]string{ "default": DefaultPolicyUserAgent, "weather-gov": "EdgeFetch/2.7 (bot@edgefetch.dev; weather-gov-client)", "openstreetmap": "EdgeFetch/2.7 (bot@edgefetch.dev; osm-polite-client)", "sec-edgar": "EdgeFetch/2.7 (bot@edgefetch.dev; sec-edgar-client)", "usajobs": "EdgeFetch/2.7 (bot@edgefetch.dev; usajobs-client)", }
AllowlistedUserAgentProfiles maps vetted User-Agent profile identifiers to compliant header values.
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.17
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.17
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.17
func CheckApprovedWildcardDomains(m *DeclarativeAdapterManifest) error
CheckApprovedWildcardDomains verifies that every wildcard domain pattern in m is on the pinned M2 allowlist.
func ClampMaxAgeMsByPolicy ¶ added in v2.8.29
ClampMaxAgeMsByPolicy clamps a requested maxAgeMs against URL and adapter-ID cache TTL ceilings.
func CleanFenceInfoString ¶ added in v2.8.17
CleanFenceInfoString sanitizes fenced code block info strings in linear time.
func CleanMediaWikiMarkdown ¶ added in v2.8.17
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.17
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.17
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.17
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.17
DecodeHTMLEntities decodes decimal (`{`), hexadecimal (`😀`), and named (`&`, `<`, `—`, etc.) HTML entities in linear O(N) time.
func DecodeMarkdownEntities ¶ added in v2.8.17
DecodeMarkdownEntities decodes HTML entities in Markdown prose segments while leaving fenced code blocks untouched.
func DereferenceNuxtDevaluePayload ¶ added in v2.8.17
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.17
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.17
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.17
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.17
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.17
EscapeAllResidualLtInProse escapes every `<` to `<` outside verified standalone PDF page markers.
func EscapeGfmTaskListCheckboxes ¶ added in v2.8.17
EscapeGfmTaskListCheckboxes escapes GFM task-list checkboxes (`- [ ] `, `* [x] `, `1. [X] `) in linear O(N) time.
func ExtractBalancedJSONAt ¶ added in v2.8.17
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 ExtractFirstRawElementHTML ¶ added in v2.8.17
func ExtractFirstRawElementHTML(rawHTML string, selectors ...RawElementSelector) (string, bool)
ExtractFirstRawElementHTML returns the raw outer HTML slice of the first balanced element matching any selector in selectors in document order (comment-aware, quote-aware, void-tag-safe, skipping <script>/<style>/<noscript>/<template>/<svg>). Returns ("", false) when no selector matches or tags are unbalanced.
func ExtractFirstRawElementOrBoundedHTML ¶ added in v2.8.17
func ExtractFirstRawElementOrBoundedHTML(rawHTML string, selectors ...RawElementSelector) (string, bool)
ExtractFirstRawElementOrBoundedHTML behaves like ExtractFirstRawElementHTML when the matched element is balanced, and on unbalanced inner tags slices raw HTML from the matched opening tag up to the next enclosing ancestor closing tag (e.g., </main>, </section>, </article>, </body>), structural sibling boundary (<footer, <aside), or bounded EOF, without x/net/html round-tripping.
func ExtractInertiaPageProps ¶ added in v2.8.17
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.17
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.17
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 ExtractMicrodataProduct ¶ added in v2.8.17
func ExtractMicrodataProduct(rawBody, finalURL, fallbackTitle, fallbackDescription string) map[string]any
ExtractMicrodataProduct extracts Schema.org Product Microdata (`itemscope`/`itemtype`/`itemprop`) from HTML, returning nil when no valid Product microdata scope is present.
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.17
ExtractPDFTitle derives a clean document title from extracted PDF Markdown, skipping copyright/conference boilerplate and falling back to the URL filename when needed.
func ExtractSlugTitleFromURL ¶ added in v2.8.29
ExtractSlugTitleFromURL derives an honest human-readable fallback title from the URL path slug or hostname.
func ExtractStructuredJSONFromPageWithDiagnostics ¶ added in v2.8.17
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.17
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.17
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.17
ExtractYouTubeTranscriptFromHTML extracts timed caption/transcript segments from rendered YouTube transcript DOM elements.
func FilterSafeResponseHeaders ¶ added in v2.8.17
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.17
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 FormatWave2cEconJSONMode ¶ added in v2.8.29
func FormatWave2cEconJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
FormatWave2cEconJSONMode formats a Category K Economy & Statistics JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.
func FormatWave2cHealthTransportJSONMode ¶ added in v2.8.29
func FormatWave2cHealthTransportJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
FormatWave2cHealthTransportJSONMode formats a Group A JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.
func FormatWave2cIpArchivesJSONMode ¶ added in v2.8.29
func FormatWave2cIpArchivesJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
FormatWave2cIpArchivesJSONMode formats a Group C JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.
func FormatWave2cLawJSONMode ¶ added in v2.8.29
func FormatWave2cLawJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
FormatWave2cLawJSONMode formats a raw JSON twin payload for Category I Federal Law & Courts adapters, returning a JSON-encoded DeclarativeFormattedDoc and true when matched and valid.
func FormatWave2cMoneyJSONMode ¶ added in v2.8.29
func FormatWave2cMoneyJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
FormatWave2cMoneyJSONMode formats a Category J JSON twin payload and returns rendered markdown.
func FormatWave2cMoneyTextMode ¶ added in v2.8.29
func FormatWave2cMoneyTextMode(mode string, rawBody string, params map[string]string, origURL string) (string, bool)
FormatWave2cMoneyTextMode formats a Category J text/XML twin payload (e.g. fpds_atom_xml) and returns rendered markdown.
func FormatWave2cScienceJSONMode ¶ added in v2.8.29
func FormatWave2cScienceJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
FormatWave2cScienceJSONMode formats a Group B JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.
func FormatWave2dJobsJSONMode ¶ added in v2.8.29
func FormatWave2dJobsJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
FormatWave2dJobsJSONMode formats a Category S JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.
func FormatWave2dLocalJSONMode ¶ added in v2.8.29
func FormatWave2dLocalJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
FormatWave2dLocalJSONMode formats a Category U JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.
func FormatWave2dLocalTextMode ¶ added in v2.8.29
func FormatWave2dLocalTextMode(mode string, rawBody string, params map[string]string, origURL string) (string, bool)
FormatWave2dLocalTextMode formats a Category U text/CSV payload and returns JSON-marshaled DeclarativeFormattedDoc.
func FormatWave2dRetailJSONMode ¶ added in v2.8.29
func FormatWave2dRetailJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
FormatWave2dRetailJSONMode formats a Category P JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.
func FormatWave2dRetailTextMode ¶ added in v2.8.29
func FormatWave2dRetailTextMode(mode string, rawBody string, params map[string]string, origURL string) (string, bool)
FormatWave2dRetailTextMode formats a Category P XML/Atom feed payload and returns JSON-marshaled DeclarativeFormattedDoc.
func FormatWave2dSportsMiscJSONMode ¶ added in v2.8.29
func FormatWave2dSportsMiscJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)
FormatWave2dSportsMiscJSONMode formats a Category V JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.
func FormatWave2dSportsMiscTextMode ¶ added in v2.8.29
func FormatWave2dSportsMiscTextMode(mode string, rawBody string, params map[string]string, origURL string) (string, bool)
FormatWave2dSportsMiscTextMode formats a Category V text/CSV payload and returns JSON-marshaled DeclarativeFormattedDoc.
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.17
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.17
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 IsBoschEbikeErrorCodeJSONMode ¶ added in v2.8.31
IsBoschEbikeErrorCodeJSONMode reports whether mode is the Bosch eBike Help Center error-code formatter.
func IsDisallowedMarkdownLinkDestination ¶ added in v2.8.17
IsDisallowedMarkdownLinkDestination reports whether rawHref violates the strict fail-closed URI allowlist.
func IsDisallowedWikipediaTitle ¶ added in v2.8.17
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.17
IsJSONLDScriptAttr matches `<script type="application/ld+json">` attribute strings (quoted or unquoted, with optional MIME parameters such as `;charset=utf-8` or entity-encoded `+`) in linear O(N) time (`HIGH-3`).
func IsNuxtDevalueFlatArray ¶ added in v2.8.17
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.17
IsSafeDeclarativeTwinURL reports whether raw is a safe public HTTPS declarative twin URL.
func IsSafePublicHostname ¶ added in v2.8.17
IsSafePublicHostname validates that rawHost is a safe public DNS hostname (rejecting localhost, .localhost.localdomain, local/internal/DNS-rebinding suffixes, IP literals, and bare public suffixes).
func IsValidUserAgentHeaderValue ¶ added in v2.8.29
IsValidUserAgentHeaderValue verifies that a User-Agent string is 1..256 printable ASCII characters.
func IsWave2cEconHTMLMode ¶ added in v2.8.29
IsWave2cEconHTMLMode reports whether mode is handled by the Category K Economy & Statistics HTML extractor.
func IsWave2cEconJSONMode ¶ added in v2.8.29
IsWave2cEconJSONMode reports whether mode is handled by the Category K Economy & Statistics JSON formatter.
func IsWave2cHealthTransportHTMLMode ¶ added in v2.8.29
IsWave2cHealthTransportHTMLMode reports whether mode is handled by Group A Health & Transport HTML extractors.
func IsWave2cHealthTransportJSONMode ¶ added in v2.8.29
IsWave2cHealthTransportJSONMode reports whether mode is handled by Group A Health & Transport JSON formatters.
func IsWave2cHealthTransportTextMode ¶ added in v2.8.29
IsWave2cHealthTransportTextMode reports whether mode is handled by Group A Health & Transport text/XML formatters.
func IsWave2cIpArchivesHTMLMode ¶ added in v2.8.29
IsWave2cIpArchivesHTMLMode reports whether mode is handled by Group C IP, Archives & Culture HTML extractors.
func IsWave2cIpArchivesJSONMode ¶ added in v2.8.29
IsWave2cIpArchivesJSONMode reports whether mode is handled by Group C IP, Archives & Culture JSON formatters.
func IsWave2cLawHTMLMode ¶ added in v2.8.29
IsWave2cLawHTMLMode reports whether mode is handled by Category I Federal Law & Courts HTML extractors.
func IsWave2cLawJSONMode ¶ added in v2.8.29
IsWave2cLawJSONMode reports whether mode is handled by Category I Federal Law & Courts JSON extractors.
func IsWave2cMoneyHTMLMode ¶ added in v2.8.29
IsWave2cMoneyHTMLMode reports whether mode is handled by Category J HTML fallback dispatch.
func IsWave2cMoneyJSONMode ¶ added in v2.8.29
IsWave2cMoneyJSONMode reports whether mode is handled by Category J (Money, Elections & Contracts) JSON dispatch.
func IsWave2cMoneyTextMode ¶ added in v2.8.29
IsWave2cMoneyTextMode reports whether mode is handled by Category J text/XML dispatch.
func IsWave2cScienceHTMLMode ¶ added in v2.8.29
IsWave2cScienceHTMLMode reports whether mode is handled by the Group B HTML fallback extractor.
func IsWave2cScienceJSONMode ¶ added in v2.8.29
IsWave2cScienceJSONMode reports whether mode is handled by the Group B Science, Weather & Places JSON formatter.
func IsWave2cScienceTextMode ¶ added in v2.8.29
IsWave2cScienceTextMode reports whether mode is handled by the Group B text formatter (e.g. usgs_water_rdb).
func IsWave2dDevHTMLMode ¶ added in v2.8.29
IsWave2dDevHTMLMode reports whether mode is handled by M4B Group A HTML extractors.
func IsWave2dDevJSONMode ¶ added in v2.8.29
IsWave2dDevJSONMode reports whether mode is handled by M4B Group A (Developer Ecosystem) JSON formatters.
func IsWave2dDevTextMode ¶ added in v2.8.29
IsWave2dDevTextMode reports whether mode is handled by M4B Group A text/XML formatters.
func IsWave2dJobsHTMLMode ¶ added in v2.8.29
IsWave2dJobsHTMLMode reports whether mode is handled by Category S US Jobs HTML extractors (#163-#168).
func IsWave2dJobsJSONMode ¶ added in v2.8.29
IsWave2dJobsJSONMode reports whether mode is handled by Category S US Jobs JSON formatters (#163-#166).
func IsWave2dLocalHTMLMode ¶ added in v2.8.29
IsWave2dLocalHTMLMode reports whether mode is handled by Wave 2D Category U HTML extractors (#186-189, #191-192).
func IsWave2dLocalJSONMode ¶ added in v2.8.29
IsWave2dLocalJSONMode reports whether mode is handled by Wave 2D Category U (Local & Events) JSON formatters (#183-187, #192).
func IsWave2dLocalTextMode ¶ added in v2.8.29
IsWave2dLocalTextMode reports whether mode is handled by Wave 2D Category U text/CSV formatters (#192).
func IsWave2dMediaVideoHTMLMode ¶ added in v2.8.29
IsWave2dMediaVideoHTMLMode reports whether mode is handled by M4A Group B HTML fallback extractors.
func IsWave2dMediaVideoJSONMode ¶ added in v2.8.29
IsWave2dMediaVideoJSONMode reports whether mode is handled by M4A Group B (US News & Video) JSON formatters.
func IsWave2dMediaVideoTextMode ¶ added in v2.8.29
IsWave2dMediaVideoTextMode reports whether mode is handled by M4A Group B text/XML formatters.
func IsWave2dRetailHTMLMode ¶ added in v2.8.29
IsWave2dRetailHTMLMode reports whether mode is handled by Wave 2D Category P HTML extractors (#137, #139-142).
func IsWave2dRetailJSONMode ¶ added in v2.8.29
IsWave2dRetailJSONMode reports whether mode is handled by Wave 2D Category P JSON formatters (#131-135).
func IsWave2dRetailTextMode ¶ added in v2.8.29
IsWave2dRetailTextMode reports whether mode is handled by Wave 2D Category P XML/Atom feed formatters (#143-144).
func IsWave2dSportsMiscHTMLMode ¶ added in v2.8.29
IsWave2dSportsMiscHTMLMode reports whether mode is handled by Category V Sports & Misc HTML extractors (#193-#200).
func IsWave2dSportsMiscJSONMode ¶ added in v2.8.29
IsWave2dSportsMiscJSONMode reports whether mode is handled by Category V Sports & Misc JSON formatters (#193-#200).
func IsWave2dSportsMiscTextMode ¶ added in v2.8.29
IsWave2dSportsMiscTextMode reports whether mode is handled by Category V Sports & Misc text/CSV formatters (#198).
func IsWikimediaHost ¶ added in v2.8.17
IsWikimediaHost reports whether rawHost belongs to Wikipedia or a sister Wikimedia project domain.
func IsWikipediaHost ¶ added in v2.8.17
IsWikipediaHost reports whether rawHost is wikipedia.org or a subdomain of wikipedia.org.
func LookupKnownRegistrableDomain ¶ added in v2.8.17
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.17
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.17
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.17
NeutralizeAllUnsafeMarkdownLinks neutralizes disallowed inline `](...)` destinations, `[id]: ...` reference definitions, and bare `//host.tld` protocol-relative URLs in linear O(N) time.
func NormalizeStrictGTIN ¶ added in v2.8.29
NormalizeStrictGTIN validates and returns a canonical GTIN consisting solely of 8, 12, 13, or 14 ASCII digits (`^(?:[0-9]{8}|[0-9]{12,14})$`), rejecting store IDs, hex strings, SKUs, 9/10/11-digit codes, and ISBN-10s.
func NormalizeTrackerHostCandidate ¶ added in v2.8.17
NormalizeTrackerHostCandidate normalizes a candidate domain host per RFC 1123 (rejecting IPv4 literals and numeric-only TLDs).
func NormalizeWikipediaLang ¶ added in v2.8.17
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.17
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.17
PercentEncodeUnsafeRecordURLChars percent-encodes characters that can break Markdown link syntax or inject raw tags (`(`, `)`, `[`, `]`, `<`, `>`, `\`, and ASCII whitespace).
func RecognizeAndHardenMarkdownFences ¶ added in v2.8.17
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.17
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 RegisterExternalCommerceMode ¶ added in v2.8.17
func RegisterExternalCommerceMode(mode string, fn func(rawBytes []byte, origURL string) (*DeclarativeFormattedDoc, bool))
RegisterExternalCommerceMode registers an external commerce twin formatter (e.g. from internal/catalog) without creating a Go package import cycle.
func RegisterExternalHTMLMode ¶ added in v2.8.17
func RegisterExternalHTMLMode(mode string, fn func(rawHTML, baseURL, currentMD, extractorID string) *DeclarativePostFetchResult)
RegisterExternalHTMLMode registers an external HTML extractor mode (e.g. from internal/catalog) without creating a Go package import cycle.
func RegisterExternalHTMLModeLazy ¶ added in v2.8.29
func RegisterExternalHTMLModeLazy(mode string, fn func(rawHTML, baseURL string, getCurrentMD func() string, extractorID string) *DeclarativePostFetchResult)
RegisterExternalHTMLModeLazy registers an external HTML extractor mode that receives a lazy getter for currentMD, avoiding generic Readability+Markdown work when currentMD is unused.
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 ResolveEffectiveMinIntervalMs ¶ added in v2.8.29
ResolveEffectiveMinIntervalMs returns the effective pacing floor for a host in milliseconds.
func ResolveEffectiveUserAgent ¶ added in v2.8.29
ResolveEffectiveUserAgent resolves an allowlisted User-Agent profile override for a request/host, never accepting arbitrary unvetted caller User-Agent strings.
func ResolveGatsbyPageDataTwinURL ¶ added in v2.8.17
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.17
ResolveWikipediaCanonicalFinalURL resolves the canonical `https://<lang>.wikipedia.org/wiki/<Title>` URL from requestedURL and responseFinalURL.
func ResolveWikipediaCanonicalFinalURLFull ¶ added in v2.8.17
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 RunWave2cEconHTMLMode ¶ added in v2.8.29
RunWave2cEconHTMLMode executes a Category K HTML fallback extractor and returns JSON-marshaled DeclarativePostFetchResult.
func RunWave2cHealthTransportHTMLMode ¶ added in v2.8.29
RunWave2cHealthTransportHTMLMode executes a Group A HTML fallback extractor and returns JSON-marshaled DeclarativePostFetchResult.
func RunWave2cIpArchivesHTMLMode ¶ added in v2.8.29
RunWave2cIpArchivesHTMLMode executes a Group C HTML fallback extractor and returns JSON-marshaled DeclarativePostFetchResult.
func RunWave2cLawHTMLMode ¶ added in v2.8.29
RunWave2cLawHTMLMode runs a post-fetch HTML extractor for Category I Federal Law & Courts adapters, returning a JSON-encoded DeclarativePostFetchResult and true when matched and valid.
func RunWave2cMoneyHTMLMode ¶ added in v2.8.29
RunWave2cMoneyHTMLMode runs a Category J HTML fallback extractor and returns rendered markdown.
func RunWave2cScienceHTMLMode ¶ added in v2.8.29
RunWave2cScienceHTMLMode executes a Group B HTML fallback extractor and returns JSON-marshaled DeclarativePostFetchResult.
func RunWave2dJobsHTMLMode ¶ added in v2.8.29
RunWave2dJobsHTMLMode executes a Category S HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.
func RunWave2dLocalHTMLMode ¶ added in v2.8.29
RunWave2dLocalHTMLMode executes a Category U HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.
func RunWave2dRetailHTMLMode ¶ added in v2.8.29
RunWave2dRetailHTMLMode executes a Category P HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.
func RunWave2dSportsMiscHTMLMode ¶ added in v2.8.29
RunWave2dSportsMiscHTMLMode executes a Category V HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.
func SanitizeFullMarkdownDocumentForArtifact ¶ added in v2.8.17
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.17
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.17
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.17
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.17
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.17
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.17
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.17
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.17
SanitizeScrapedTimestampField sanitizes ISO/human timestamp metadata fields, neutralizing Markdown/HTML syntax.
func ScanGeneratorMetaTags ¶ added in v2.8.17
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.17
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 ScrubTwinURLSecrets ¶ added in v2.8.29
ScrubTwinURLSecrets strips credential/key query parameters (`api_key`, `apikey`, `api_token`, `appkey`, `passkey`, `x-algolia-api-key`, `x-publishable-api-key`, `publishable_api_key`, `x-key`, `token`, `auth_key`, `access_token`, `key`) from twin URLs before returning `alternateMarkdownUrl` or response metadata.
func SplitMarkdownByCodeFences ¶ added in v2.8.17
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.17
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.17
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.17
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.17
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.17
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.17
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 AdapterPolicy ¶ added in v2.8.29
type AdapterPolicy struct {
AdapterID string `json:"adapterId,omitempty"`
UserAgentProfile string `json:"userAgentProfile,omitempty"`
MinIntervalMs int `json:"minIntervalMs,omitempty"`
MaxCacheTtlMs int `json:"maxCacheTtlMs,omitempty"`
MaxConcurrent int `json:"maxConcurrent,omitempty"`
StrictRobots bool `json:"strictRobots,omitempty"`
}
AdapterPolicy describes per-adapter politeness, User-Agent profile, host pacing, concurrency, strict robots, and cache TTL rules.
func ResolveAdapterPolicyByID ¶ added in v2.8.29
func ResolveAdapterPolicyByID(adapterID string) AdapterPolicy
ResolveAdapterPolicyByID resolves merged manifest + built-in policy metadata for an adapter ID.
func ResolveAdapterPolicyForURL ¶ added in v2.8.29
func ResolveAdapterPolicyForURL(urlStr string) AdapterPolicy
ResolveAdapterPolicyForURL resolves merged built-in host policy + non-universal manifest policy for a URL.
func ResolveHostPolicyDefaults ¶ added in v2.8.29
func ResolveHostPolicyDefaults(host string) AdapterPolicy
ResolveHostPolicyDefaults returns built-in Wave 2 host guardrail rules for weather.gov, OSM/Overpass, Yelp, and strict cycling hosts.
type AttrSelectorItem ¶ added in v2.8.17
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.17
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.17
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.17
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.17
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.17
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.17
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.17
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"`
AuthMode string `json:"auth_mode,omitempty"`
RequiresPageKeyOptIn bool `json:"requires_page_key_opt_in,omitempty"`
UserAgentProfile string `json:"user_agent_profile,omitempty"`
MinIntervalMs int `json:"min_interval_ms,omitempty"`
MaxCacheTtlMs int `json:"max_cache_ttl_ms,omitempty"`
MaxConcurrent int `json:"max_concurrent,omitempty"`
StrictRobots bool `json:"strict_robots,omitempty"`
DetectOnly *DeclarativeDetectOnlySpec `json:"detect_only,omitempty"`
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.17
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"`
AuthMode string `json:"authMode,omitempty"`
RequiresPageKeyOptIn bool `json:"requiresPageKeyOptIn,omitempty"`
UserAgentProfile string `json:"userAgentProfile,omitempty"`
MinIntervalMs int `json:"minIntervalMs,omitempty"`
MaxCacheTtlMs int `json:"maxCacheTtlMs,omitempty"`
MaxConcurrent int `json:"maxConcurrent,omitempty"`
StrictRobots bool `json:"strictRobots,omitempty"`
}
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 DeclarativeDetectOnlySpec ¶ added in v2.8.29
type DeclarativeDetectOnlySpec struct {
OfficialAPI string `json:"official_api,omitempty"`
RecommendedMCP string `json:"recommended_mcp,omitempty"`
HandoffAdapter string `json:"handoff_adapter,omitempty"`
AllowJSONLDFallback bool `json:"allow_json_ld_fallback,omitempty"`
Reason string `json:"reason,omitempty"`
Guidance string `json:"guidance,omitempty"`
}
DeclarativeDetectOnlySpec describes structured guidance for detect-only / official-API-only targets.
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.17
DeclarativeExactSegments accepts either a boolean (`exactSegments: false` alongside `pathSegments`) or a non-negative segment count (`exactSegments: 1`).
func (DeclarativeExactSegments) MarshalJSON ¶ added in v2.8.17
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.17
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"`
JSONMode string `json:"jsonMode,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"`
RecordFields map[string]string `json:"recordFields,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 FormatBoschEbikeErrorCodeJSONDoc ¶ added in v2.8.31
func FormatBoschEbikeErrorCodeJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatBoschEbikeErrorCodeJSONDoc formats a /v2/error_code response into a per-generation code / severity / description / remedy document with one record per generation entry.
func FormatDeclarativeTwinByURL ¶ added in v2.8.17
func FormatDeclarativeTwinByURL(requestURL, rawBody, origURL string) (*DeclarativeFormattedDoc, bool)
FormatDeclarativeTwinByURL resolves the declarative twin for requestURL (with `page-key` twins off by default), overrides origURL when non-empty, and formats rawBody.
func FormatDeclarativeTwinByURLWithOptions ¶ added in v2.8.29
func FormatDeclarativeTwinByURLWithOptions(requestURL, rawBody, origURL string, opts DeclarativeResolveOptions) (*DeclarativeFormattedDoc, bool)
FormatDeclarativeTwinByURLWithOptions resolves the declarative twin for requestURL using the given options and formats rawBody.
func FormatJSONWithExtractSpec ¶ added in v2.8.17
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.17
func FormatTwinOnManifest(m *DeclarativeAdapterManifest, requestURL, rawBody, origURL string) (*DeclarativeFormattedDoc, bool)
FormatTwinOnManifest resolves and formats a twin body against an explicit DeclarativeAdapterManifest.
func FormatTwinOnManifestWithOptions ¶ added in v2.8.29
func FormatTwinOnManifestWithOptions(m *DeclarativeAdapterManifest, requestURL, rawBody, origURL string, opts DeclarativeResolveOptions) (*DeclarativeFormattedDoc, bool)
FormatTwinOnManifestWithOptions resolves and formats a twin body against an explicit DeclarativeAdapterManifest under the given options.
func FormatTwinOnValidatedManifest ¶ added in v2.8.17
func FormatTwinOnValidatedManifest(m *DeclarativeAdapterManifest, requestURL, rawBody, origURL string) (*DeclarativeFormattedDoc, bool)
FormatTwinOnValidatedManifest resolves and formats a twin body against an already-validated DeclarativeAdapterManifest.
func FormatTwinOnValidatedManifestWithOptions ¶ added in v2.8.29
func FormatTwinOnValidatedManifestWithOptions(m *DeclarativeAdapterManifest, requestURL, rawBody, origURL string, opts DeclarativeResolveOptions) (*DeclarativeFormattedDoc, bool)
FormatTwinOnValidatedManifestWithOptions resolves and formats a twin body against an already-validated DeclarativeAdapterManifest under the given options.
func FormatWave2aJSONPublic ¶ added in v2.8.29
func FormatWave2aJSONPublic(mode string, rawBytes []byte, origURL string, htmlToMD func(frag, base string) (string, []string)) (*DeclarativeFormattedDoc, bool)
FormatWave2aJSONPublic exposes Wave 2A jsonMode formatting for companion twin pipelines.
func FormatWave2cHealthTransportJSONDoc ¶ added in v2.8.29
func FormatWave2cHealthTransportJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2cHealthTransportJSONDoc formats a Group A Health & Transport JSON payload into a DeclarativeFormattedDoc.
func FormatWave2cHealthTransportTextDoc ¶ added in v2.8.29
func FormatWave2cHealthTransportTextDoc(mode string, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2cHealthTransportTextDoc formats a Group A Health & Transport XML/text twin payload into a DeclarativeFormattedDoc.
func FormatWave2cIpArchivesJSONDoc ¶ added in v2.8.29
func FormatWave2cIpArchivesJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2cIpArchivesJSONDoc formats a Group C JSON twin payload into a DeclarativeFormattedDoc.
func FormatWave2cMoneyJSONDoc ¶ added in v2.8.29
func FormatWave2cMoneyJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2cMoneyJSONDoc formats a Category J JSON twin payload into a full DeclarativeFormattedDoc.
func FormatWave2cMoneyTextDoc ¶ added in v2.8.29
func FormatWave2cMoneyTextDoc(mode string, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2cMoneyTextDoc formats a Category J text/XML twin payload into a full DeclarativeFormattedDoc.
func FormatWave2cScienceJSONDoc ¶ added in v2.8.29
func FormatWave2cScienceJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2cScienceJSONDoc formats a Group B JSON/GeoJSON payload into a DeclarativeFormattedDoc.
func FormatWave2cScienceTextDoc ¶ added in v2.8.29
func FormatWave2cScienceTextDoc(mode string, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2cScienceTextDoc formats a Group B text payload (usgs_water_rdb) into a DeclarativeFormattedDoc.
func FormatWave2dDevJSONDoc ¶ added in v2.8.29
func FormatWave2dDevJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2dDevJSONDoc formats an M4B Group A JSON twin payload into a DeclarativeFormattedDoc.
func FormatWave2dDevTextDoc ¶ added in v2.8.29
func FormatWave2dDevTextDoc(mode string, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2dDevTextDoc formats an M4B Group A text/XML payload into a DeclarativeFormattedDoc.
func FormatWave2dJobsJSONDoc ¶ added in v2.8.29
func FormatWave2dJobsJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2dJobsJSONDoc formats a Category S US Jobs JSON payload into a DeclarativeFormattedDoc.
func FormatWave2dLocalJSONDoc ¶ added in v2.8.29
func FormatWave2dLocalJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2dLocalJSONDoc formats a Category U local/events/housing API JSON payload into a DeclarativeFormattedDoc.
func FormatWave2dLocalTextDoc ¶ added in v2.8.29
func FormatWave2dLocalTextDoc(mode string, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2dLocalTextDoc formats a Category U text/CSV payload into a DeclarativeFormattedDoc.
func FormatWave2dMediaVideoJSONDoc ¶ added in v2.8.29
func FormatWave2dMediaVideoJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2dMediaVideoJSONDoc formats an M4A Group B JSON twin payload (including Medium linear anti-XSSI stripping).
func FormatWave2dMediaVideoTextDoc ¶ added in v2.8.29
func FormatWave2dMediaVideoTextDoc(mode string, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2dMediaVideoTextDoc formats an M4A Group B text/XML payload into a DeclarativeFormattedDoc.
func FormatWave2dRetailJSONDoc ¶ added in v2.8.29
func FormatWave2dRetailJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2dRetailJSONDoc formats a Category P retail API JSON payload into a DeclarativeFormattedDoc.
func FormatWave2dRetailTextDoc ¶ added in v2.8.29
func FormatWave2dRetailTextDoc(mode string, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2dRetailTextDoc formats a Category P XML/Atom/RSS feed payload into a DeclarativeFormattedDoc.
func FormatWave2dSportsMiscJSONDoc ¶ added in v2.8.29
func FormatWave2dSportsMiscJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2dSportsMiscJSONDoc formats a Category V Sports & Misc JSON payload into a DeclarativeFormattedDoc.
func FormatWave2dSportsMiscTextDoc ¶ added in v2.8.29
func FormatWave2dSportsMiscTextDoc(mode string, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)
FormatWave2dSportsMiscTextDoc formats a Category V text/CSV payload into a DeclarativeFormattedDoc.
func FormatYAMLFrontmatterCard ¶ added in v2.8.17
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.17
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"`
ReplaceLinks bool `json:"-"`
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.17
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.17
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.17
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.
func RunWave2cMoneyHTMLResult ¶ added in v2.8.29
func RunWave2cMoneyHTMLResult( mode string, rawHTML string, baseURL string, currentMD string, htmlToMD func(frag, base string) (string, []string), extractorID string, ) (*DeclarativePostFetchResult, bool)
RunWave2cMoneyHTMLResult runs a Category J HTML fallback extractor and returns a full DeclarativePostFetchResult.
func Wave2dDevRunHTML ¶ added in v2.8.29
func Wave2dDevRunHTML(mode string, rawHTML string, baseURL string, extractorID string) *DeclarativePostFetchResult
Wave2dDevRunHTML executes an M4B Group A post-fetch HTML extractor.
func Wave2dJobsRunHTML ¶ added in v2.8.29
func Wave2dJobsRunHTML(mode string, rawHTML string, baseURL string, extractorID string) *DeclarativePostFetchResult
Wave2dJobsRunHTML executes a Category S HTML extractor and returns a DeclarativePostFetchResult.
func Wave2dLocalRunHTML ¶ added in v2.8.29
func Wave2dLocalRunHTML(mode string, ctx *htmlExtractContextDeclHTML, extractorID string) *DeclarativePostFetchResult
Wave2dLocalRunHTML executes a Category U post-fetch HTML extractor and returns DeclarativePostFetchResult.
func Wave2dMediaVideoRunHTML ¶ added in v2.8.29
func Wave2dMediaVideoRunHTML(mode string, rawHTML string, baseURL string, extractorID string) *DeclarativePostFetchResult
Wave2dMediaVideoRunHTML executes an M4A Group B post-fetch HTML extractor.
func Wave2dRetailRunHTML ¶ added in v2.8.29
func Wave2dRetailRunHTML(mode string, ctx *htmlExtractContextDeclHTML, extractorID string) *DeclarativePostFetchResult
Wave2dRetailRunHTML executes a Category P HTML extractor and returns DeclarativePostFetchResult.
func Wave2dSportsMiscRunHTML ¶ added in v2.8.29
func Wave2dSportsMiscRunHTML(mode string, rawHTML string, baseURL string, extractorID string) *DeclarativePostFetchResult
Wave2dSportsMiscRunHTML executes a Category V Sports & Misc HTML extractor and returns a DeclarativePostFetchResult.
type DeclarativePreferWhereSpec ¶ added in v2.8.17
type DeclarativePreferWhereSpec struct {
Path string `json:"path"`
Equals string `json:"equals"`
FallbackEquals string `json:"fallbackEquals,omitempty"`
FallbackLast bool `json:"fallbackLast,omitempty"`
}
DeclarativePreferWhereSpec narrows an array value to the single element whose `Path` field equals `Equals` (e.g. a Wikidata claim with `rank: preferred`) before `subField` / `format` are applied. When no element matches, the first element whose `Path` equals `FallbackEquals` is used (the last one when `FallbackLast`); with no fallback match (or no `FallbackEquals`) the var resolves to empty rather than guessing.
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"`
AllowValues []string `json:"allowValues,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 DeclarativeResolveOptions ¶ added in v2.8.29
type DeclarativeResolveOptions struct {
AllowPageKeyTwins bool
}
DeclarativeResolveOptions controls opt-in twin resolution behavior (e.g. `page-key` twins default OFF).
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"`
ScanLast bool `json:"scanLast,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.17
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
FallbackFetchURL string
Kind classify.Kind
Accept string
Method string
RequestBody string
ContentType string
Headers map[string]string
RequiresPageKeyOptIn bool
AuthMode string
UserAgentProfile string
MinIntervalMs int
MaxCacheTtlMs int
MaxConcurrent int
StrictRobots bool
// 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 (with `page-key` opt-in twins disabled by default).
func ResolveDeclarativeTwinWithOptions ¶ added in v2.8.29
func ResolveDeclarativeTwinWithOptions(rawURL string, opts DeclarativeResolveOptions) (*DeclarativeTwinMatch, bool)
ResolveDeclarativeTwinWithOptions checks if `rawURL` matches any embedded declarative adapter under the given options.
func ResolveTwinOnManifest ¶ added in v2.8.17
func ResolveTwinOnManifest(m *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool)
ResolveTwinOnManifest evaluates twin resolution against an explicit (ad-hoc or custom) DeclarativeAdapterManifest.
func ResolveTwinOnManifestWithOptions ¶ added in v2.8.29
func ResolveTwinOnManifestWithOptions(m *DeclarativeAdapterManifest, rawURL string, opts DeclarativeResolveOptions) (*DeclarativeTwinMatch, bool)
ResolveTwinOnManifestWithOptions evaluates twin resolution against an explicit DeclarativeAdapterManifest under the given options.
func ResolveTwinOnValidatedManifest ¶ added in v2.8.17
func ResolveTwinOnValidatedManifest(cp *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool)
ResolveTwinOnValidatedManifest evaluates twin resolution against an already-validated DeclarativeAdapterManifest.
func ResolveTwinOnValidatedManifestWithOptions ¶ added in v2.8.29
func ResolveTwinOnValidatedManifestWithOptions(cp *DeclarativeAdapterManifest, rawURL string, opts DeclarativeResolveOptions) (*DeclarativeTwinMatch, bool)
ResolveTwinOnValidatedManifestWithOptions evaluates twin resolution against an already-validated DeclarativeAdapterManifest under the given options.
func (*DeclarativeTwinMatch) CommerceMode ¶ added in v2.8.17
func (m *DeclarativeTwinMatch) CommerceMode() string
CommerceMode returns the matched route's commerceMode (if any).
func (*DeclarativeTwinMatch) EffectiveMaxBytes ¶ added in v2.8.17
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.17
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"`
Method string `json:"method,omitempty"`
RequestBody string `json:"requestBody,omitempty"`
ContentType string `json:"contentType,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
MaxBytes int `json:"maxBytes,omitempty"`
RequiresPageKeyOptIn bool `json:"requires_page_key_opt_in,omitempty"`
AuthMode string `json:"auth_mode,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"`
PreferWhere *DeclarativePreferWhereSpec `json:"preferWhere,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.17
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.17
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.17
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.17
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.17
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.17
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"`
PreferRecordAvailability bool `json:"preferRecordAvailability,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.17
func ExtractHTMLDocumentFull(rawHTML string, opts FullExtractOptions) ExtractedDocumentFull
type FormattedPayloadDoc ¶ added in v2.8.17
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.17
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.17
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.17
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.17
func FormatICalendarToMarkdown(raw string) *FormattedPayloadDoc
FormatICalendarToMarkdown formats RFC 5545 iCalendar (`BEGIN:VCALENDAR`) feeds into structured Markdown event summaries.
func FormatInertiaPagePropsToMarkdown ¶ added in v2.8.17
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.17
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.17
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.17
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.17
func FormatVCardToMarkdown(raw string) *FormattedPayloadDoc
FormatVCardToMarkdown formats RFC 6350 vCard (`BEGIN:VCARD`) contact payloads into clean Markdown.
func TryParseJSONPayloadForScrape ¶ added in v2.8.17
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.17
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"`
// StripHiddenSubtrees removes hidden (hidden attr, display:none, aria-hidden, non-content role) subtrees even when
// OnlyMainContent is false. Full-page extraction otherwise keeps them; fragments always strip them.
StripHiddenSubtrees bool `json:"stripHiddenSubtrees,omitempty"`
// SkipUniversalExtractors skips the universal declarative HTML extractor sweep (used when the caller already
// dispatched a specific manifest route such as `textMode: html_document`).
SkipUniversalExtractors bool `json:"skipUniversalExtractors,omitempty"`
// SkipPlainText skips generating `Text` when the caller only needs `Markdown` and metadata.
SkipPlainText bool `json:"skipPlainText,omitempty"`
}
FullExtractOptions configures full-fidelity HTML document extraction and Markdown finalization.
type HTMLDoc ¶ added in v2.8.17
type HTMLDoc struct {
HTMLNode
}
HTMLDoc represents a parsed bounded HTML5 document ready for linear-time CSS querying.
func ParseHTMLDoc ¶ added in v2.8.17
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.17
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.17
Attr returns the value of attribute name (case-insensitive) and whether it exists on this element.
func (*HTMLNode) AttrOf ¶ added in v2.8.17
AttrOf returns First(subSelector).AttrOrEmpty(name), or "" if absent.
func (*HTMLNode) AttrOrEmpty ¶ added in v2.8.17
AttrOrEmpty returns the value of attribute name (case-insensitive), or "" if absent.
func (*HTMLNode) DLMap ¶ added in v2.8.17
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.17
First returns the first matching descendant HTMLNode, or nil if none match.
func (*HTMLNode) HTML ¶ added in v2.8.17
HTML returns serialized inner HTML. When subSelector is provided, serializes the inner HTML of First(subSelector[0]).
func (*HTMLNode) IsDescendantOf ¶ added in v2.8.17
IsDescendantOf reports whether n is a strict descendant of ancestor within the same parsed DOM.
func (*HTMLNode) NodeKey ¶ added in v2.8.17
NodeKey returns a comparable identity key for the underlying DOM node, or nil if n is nil. Multiple HTMLNode wrappers returned by separate Select/First calls for the same DOM element share the same NodeKey.
func (*HTMLNode) SameNode ¶ added in v2.8.17
SameNode reports whether n and other wrap the same underlying DOM node.
func (*HTMLNode) Select ¶ added in v2.8.17
Select returns up to limit matching descendant HTMLNodes in DOM document order (capped at 5,000).
func (*HTMLNode) TableRows ¶ added in v2.8.17
TableRows extracts a 2D slice of cleaned cell text from <tr> -> <th>/<td> rows.
func (*HTMLNode) Tag ¶ added in v2.8.17
Tag returns the lowercase HTML tag name for element nodes, or "" for the document root.
type HydratedFrameworkStateResult ¶ added in v2.8.17
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.17
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.17
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.17
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.17
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.17
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.17
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.17
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.17
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.17
func ComputeMarkdownSliceCheckpoints(rawFullMD string, stepChars int) []MarkdownSliceCheckpoint
type MarkdownSliceEscapedUntrusted ¶ added in v2.8.17
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.17
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.17
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 PlatformTwinCandidate ¶ added in v2.8.29
type PlatformTwinCandidate struct {
Matched bool `json:"matched"`
AdapterID string `json:"adapterId,omitempty"`
FetchURL string `json:"fetchUrl,omitempty"`
FallbackFetchURL string `json:"fallbackFetchUrl,omitempty"`
Method string `json:"method,omitempty"`
RequestBody string `json:"requestBody,omitempty"`
ContentType string `json:"contentType,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Accept string `json:"accept,omitempty"`
RequiresPageKeyOptIn bool `json:"requiresPageKeyOptIn,omitempty"`
FormatMode string `json:"formatMode,omitempty"`
}
PlatformTwinCandidate describes a discovered bounded companion twin endpoint.
func DiscoverPlatformCompanionTwin ¶ added in v2.8.29
func DiscoverPlatformCompanionTwin(rawHTML string, in PlatformTwinDiscoveryInput) PlatformTwinCandidate
DiscoverPlatformCompanionTwin inspects bounded HTML and headers to discover a safe companion twin endpoint. When `in.AllowPageKeyTwins` is false (default), `page-key` adapters (`algolia`, `bazaarvoice`, `powerreviews`, `yext-locator`) are NEVER scanned or returned.
type PlatformTwinDiscoveryInput ¶ added in v2.8.29
type PlatformTwinDiscoveryInput struct {
PageURL string `json:"pageUrl"`
AllowPageKeyTwins bool `json:"allowPageKeyTwins"`
Headers map[string]string `json:"headers,omitempty"`
SelfHost string `json:"selfHost,omitempty"`
ExistingExtractorID string `json:"existingExtractorId,omitempty"`
}
PlatformTwinDiscoveryInput configures post-HTML companion twin discovery.
type PromptInjectionResult ¶ added in v2.8.17
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.17
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 RawElementSelector ¶ added in v2.8.17
type RawElementSelector struct {
Tag string
ID string
Class string
Attr string
Val string
AttrSubstr string
}
RawElementSelector describes a simple tag/id/class/attribute selector for slicing raw HTML without decoding entities via x/net/html.
type RecognizeMarkdownFencesOptions ¶ added in v2.8.17
type RecognizeMarkdownFencesOptions struct {
Harden bool
PreserveCrLf bool
InitialReopenedFence *ReopenedMarkdownFence
InitialState *MarkdownFenceRecognizerState
SkipLeadingSeparatorEmptyLine bool
}
RecognizeMarkdownFencesOptions configures RecognizeAndHardenMarkdownFences.
type ReopenedMarkdownFence ¶ added in v2.8.17
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.17
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 ExtractDetectOnlyProductJSONLD ¶ added in v2.8.29
func ExtractDetectOnlyProductJSONLD(rawHTML, baseURL string, htmlToMD func(frag, base string) (string, []string)) *UniversalSchemaOrgResult
ExtractDetectOnlyProductJSONLD extracts bounded static Schema.org JSON-LD (`@type: Product`) for `detect-only` HTML pages with `allowJsonLdFallback: true` (e.g., `#136 target` product pages).
func ExtractUniversalSchemaOrg ¶ added in v2.8.17
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.17
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.17
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.17
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.17
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.
Source Files
¶
- bosch_ebike_error_code.go
- cms_twins.go
- declarative.go
- declarative_html.go
- doc.go
- extract.go
- formatters.go
- framework_detect.go
- html_doc_extract.go
- html_dom.go
- hydration.go
- json_fast_scan.go
- lazy_regexp.go
- llms.go
- m3_html_modes.go
- m4_extractors.go
- nuget.go
- pdf.go
- platform_twins.go
- policy.go
- prompt_injection.go
- psl.go
- sanitize.go
- sanitize_slice.go
- schema_org.go
- structured_product_html.go
- tracker_validate.go
- wave2a_extractors.go
- wave2b_communities.go
- wave2b_cycling.go
- wave2b_help_centers.go
- wave2b_search_reviews_locators.go
- wave2b_status_changelog_cms.go
- wave2c_econ.go
- wave2c_health_transport.go
- wave2c_ip_archives.go
- wave2c_law.go
- wave2c_money.go
- wave2c_science.go
- wave2d_dev.go
- wave2d_jobs.go
- wave2d_local.go
- wave2d_media_video.go
- wave2d_retail.go
- wave2d_sports_misc.go
- wikipedia.go
- yaml_subset.go