extract

package
v2.8.35 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 31 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

  1. Head metadata & branding signals (`<title>`, OpenGraph, canonical URL, favicon, CSS hex palette, fonts).
  2. Boilerplate & chrome removal (`<nav>`, `<footer>`, `<aside>`, `<script>`, `<style>`) with `<main>` / `<article>` focus when `OnlyMainContent` is enabled.
  3. Sentinel-protected `<pre><code>` and multi-backtick inline `<code>` conversion so generic type signatures (`Promise<void>`, `#include <stdio.h>`) survive HTML tag stripping intact.
  4. GFM table reconstruction, optional BM25 passage reranking (RerankPassages), and optional PII redaction (RedactPII).
  5. Streaming Poppler `pdftotext -layout` extraction with a pure-Go FlateDecode fallback (ExtractPDFText) for distroless Lite deployments.

Index

Examples

Constants

View Source
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
)
View Source
const (
	MinEasyPrivacyListBytes      = 200 * 1024
	MaxEasyPrivacyListBytes      = 10 * 1024 * 1024
	MinEasyPrivacyHostCount      = 5_000
	MaxEasyPrivacyHostCount      = 200_000
	MaxEasyPrivacyHostDeltaRatio = 0.2
)
View Source
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
)
View Source
const DefaultPolicyUserAgent = "EdgeFetch/2.7 (bot@edgefetch.dev)"

DefaultPolicyUserAgent is the default honest EdgeFetch User-Agent header.

View Source
const (
	// FrameworkDetectWindowChars bounds framework/platform detection to the first 64 KiB (65,536 UTF-16 code units).
	FrameworkDetectWindowChars = 65_536
)

Variables

View Source
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)",
	"musicbrainz":   "EdgeFetch/2.7 (bot@edgefetch.dev; musicbrainz-client)",
}

AllowlistedUserAgentProfiles maps vetted User-Agent profile identifiers to compliant header values.

View Source
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 BoolPtr added in v2.8.34

func BoolPtr(v bool) *bool

BoolPtr returns a pointer to v (helper for DeclarativeResolveOptions and PlatformTwinDiscoveryInput).

func BuildWikimediaRobotsSuggestion added in v2.8.17

func BuildWikimediaRobotsSuggestion(rawHost string) string

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

func BuildWikipediaDirectTitleGuessURL(rawQuery, lang string) string

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

func CandidateCompanionMarkdownURL(pageURL string) string

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 CheckUnboundedTwinEndpointGuard added in v2.8.34

func CheckUnboundedTwinEndpointGuard(rawURL string) (blocked bool, message string)

CheckUnboundedTwinEndpointGuard blocks unfiltered saferproducts.gov/RestWebServices/Recall dumps (> 25 MiB) that lack a valid bounded RecallNumber, ProductType, or ProductDescription query parameter.

func ClampMaxAgeMsByPolicy added in v2.8.29

func ClampMaxAgeMsByPolicy(maxAgeMs int, urlStr, adapterID string) int

ClampMaxAgeMsByPolicy clamps a requested maxAgeMs against URL and adapter-ID cache TTL ceilings.

func CleanFenceInfoString added in v2.8.17

func CleanFenceInfoString(rawInfo string) string

CleanFenceInfoString sanitizes fenced code block info strings in linear time.

func CleanMediaWikiMarkdown added in v2.8.17

func CleanMediaWikiMarkdown(rawMD string) string

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

func CleanPDFMarkdown(md string) string

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

func CollapseAnimatedCounterTickers(prose string) string

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 DataGovAdapterIDs added in v2.8.34

func DataGovAdapterIDs() []string

DataGovAdapterIDs returns the sorted list of adapter IDs backed by api.data.gov (`DATA_GOV_API_KEY`).

func DecodeBasicEntities added in v2.8.17

func DecodeBasicEntities(s string) string

DecodeBasicEntities decodes basic named HTML entities (`&amp;`, `&lt;`, `&gt;`, `&quot;`, `&#39;`, `&apos;`, `&nbsp;`) and valid Unicode scalar numeric character references (`1..0x10FFFF` excluding surrogates), leaving invalid/NUL numeric entities intact.

func DecodeHTMLEntities added in v2.8.17

func DecodeHTMLEntities(input string) string

DecodeHTMLEntities decodes decimal (`&#123;`), hexadecimal (`&#x1f600;`), and named (`&amp;`, `&lt;`, `&mdash;`, etc.) HTML entities in linear O(N) time.

func DecodeMarkdownEntities added in v2.8.17

func DecodeMarkdownEntities(md string) string

DecodeMarkdownEntities decodes HTML entities in Markdown prose segments while leaving fenced code blocks untouched.

func DereferenceNuxtDevaluePayload added in v2.8.17

func DereferenceNuxtDevaluePayload(flat []any, maxNodes int) any

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

func DeriveQuickMarkdownFromRawBytes(data []byte, baseURL string) string

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

func DetectRenderedChallenge(rawHTML string) string

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

func DiscoverWordPressRestTwinURL(rawHTML, pageFinalURL, selfHost string) string

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

func EscapeAllResidualLtInProse(prose string, allowPdfPageMarkers bool) string

EscapeAllResidualLtInProse escapes every `<` to `&lt;` outside verified standalone PDF page markers.

func EscapeGfmTaskListCheckboxes added in v2.8.17

func EscapeGfmTaskListCheckboxes(prose string) string

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

func ExtractInertiaPageProps(rawHTML string, maxScanChars int) map[string]any

ExtractInertiaPageProps linearly extracts Inertia.js `data-page="{&quot;component&quot;:...}"` 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

func ExtractJSONLDObjects(rawHTML string, maxEntities int) []map[string]any

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

func ExtractLargestURLFromSrcset(srcset string) string

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

func ExtractPDFTitle(md, urlStr string) string

ExtractPDFTitle derives a clean document title from extracted PDF Markdown, skipping copyright/conference boilerplate and falling back to the URL filename when needed.

func ExtractSensitiveHeaderSecrets added in v2.8.34

func ExtractSensitiveHeaderSecrets(extraHeaders map[string]string) []string

ExtractSensitiveHeaderSecrets returns non-empty values of sensitive companion headers that must be scrubbed from responses/spans.

func ExtractSlugTitleFromURL added in v2.8.29

func ExtractSlugTitleFromURL(rawURL string) string

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

func ExtractWikipediaLangFromHost(rawHost string) string

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

func ExtractYouTubeTranscriptFromHTML(rawHTML string) string

ExtractYouTubeTranscriptFromHTML extracts timed caption/transcript segments from rendered YouTube transcript DOM elements.

func FilterSafeResponseHeaders added in v2.8.17

func FilterSafeResponseHeaders(rawHeaders map[string]string) map[string]string

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 FormatWave2UpgradedJSONMode added in v2.8.34

func FormatWave2UpgradedJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave2UpgradedJSONMode formats a JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

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 FormatWave3CommunityJSONMode added in v2.8.34

func FormatWave3CommunityJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3CommunityJSONMode formats a Category E Community JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3CyclingComponentsJSONMode added in v2.8.34

func FormatWave3CyclingComponentsJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3CyclingComponentsJSONMode formats a Category O1 JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3CyclingOEMsJSONMode added in v2.8.34

func FormatWave3CyclingOEMsJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3CyclingOEMsJSONMode formats a Category O2 JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3DevInfraJSONMode added in v2.8.34

func FormatWave3DevInfraJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3DevInfraJSONMode formats a Category N JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3DevInfraTextMode added in v2.8.34

func FormatWave3DevInfraTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool)

FormatWave3DevInfraTextMode formats a Category N text/streaming payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3EduJSONMode added in v2.8.34

func FormatWave3EduJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3EduJSONMode formats a Category B Education JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3FinanceJSONMode added in v2.8.34

func FormatWave3FinanceJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3FinanceJSONMode formats a Category S JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3FinanceTextMode added in v2.8.34

func FormatWave3FinanceTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool)

FormatWave3FinanceTextMode formats a Category S text/CSV payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3GTINIdentityJSONMode added in v2.8.34

func FormatWave3GTINIdentityJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3GTINIdentityJSONMode formats a Category Q JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3GTINIdentityTextMode added in v2.8.34

func FormatWave3GTINIdentityTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool)

FormatWave3GTINIdentityTextMode formats a Category Q text payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3GovJSONMode added in v2.8.34

func FormatWave3GovJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3GovJSONMode formats a Category A JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3GovTextMode added in v2.8.34

func FormatWave3GovTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool)

FormatWave3GovTextMode formats a Category A text payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3JobsPublicJSONMode added in v2.8.34

func FormatWave3JobsPublicJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3JobsPublicJSONMode formats a Category C JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3MediaLyricsJSONMode added in v2.8.34

func FormatWave3MediaLyricsJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3MediaLyricsJSONMode formats a Category R JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3MediaLyricsTextMode added in v2.8.34

func FormatWave3MediaLyricsTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool)

FormatWave3MediaLyricsTextMode formats a Category R text payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3PropRestIRJSONMode added in v2.8.34

func FormatWave3PropRestIRJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3PropRestIRJSONMode formats a Category H JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3PropRestIRTextMode added in v2.8.34

func FormatWave3PropRestIRTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool)

FormatWave3PropRestIRTextMode formats Category H RSS/Atom XML feeds and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3RegulatorsHealthJSONMode added in v2.8.34

func FormatWave3RegulatorsHealthJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3RegulatorsHealthJSONMode formats a Category K Part 2 JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3RegulatorsHealthTextMode added in v2.8.34

func FormatWave3RegulatorsHealthTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool)

FormatWave3RegulatorsHealthTextMode formats a Category K Part 2 text payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3RegulatorsJSONMode added in v2.8.34

func FormatWave3RegulatorsJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3RegulatorsJSONMode formats a Category K Part 1 JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3ResaleJSONMode added in v2.8.34

func FormatWave3ResaleJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3ResaleJSONMode formats a Category P JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3ScholarlyJSONMode added in v2.8.34

func FormatWave3ScholarlyJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3ScholarlyJSONMode formats a Category L JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3ScholarlyTextMode added in v2.8.34

func FormatWave3ScholarlyTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool)

FormatWave3ScholarlyTextMode formats a Category L text/XML payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3SecurityIntelJSONMode added in v2.8.34

func FormatWave3SecurityIntelJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3SecurityIntelJSONMode formats a Category M JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3SecurityIntelTextMode added in v2.8.34

func FormatWave3SecurityIntelTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool)

FormatWave3SecurityIntelTextMode formats a Category M text payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3SocialCreatorJSONMode added in v2.8.34

func FormatWave3SocialCreatorJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3SocialCreatorJSONMode formats a Category T JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3StoreAddonsJSONMode added in v2.8.34

func FormatWave3StoreAddonsJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3StoreAddonsJSONMode formats a Category I JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3TradeJSONMode added in v2.8.34

func FormatWave3TradeJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool)

FormatWave3TradeJSONMode formats a Category J JSON payload and returns JSON-marshaled DeclarativeFormattedDoc.

func FormatWave3TradeTextMode added in v2.8.34

func FormatWave3TradeTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool)

FormatWave3TradeTextMode formats a Category J XML/text payload and returns JSON-marshaled DeclarativeFormattedDoc.

func GetRegistrableDomain added in v2.7.2

func GetRegistrableDomain(host string) string

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

func HasPrivateSharedHostingSuffix(host string) bool

HasPrivateSharedHostingSuffix reports whether host matches a rule from the Mozilla PSL PRIVATE DOMAINS section.

func HasRawOrEncodedUnicodeTag added in v2.8.17

func HasRawOrEncodedUnicodeTag(raw string) bool

HasRawOrEncodedUnicodeTag detects literal, JSON-escaped (`\udb40\udc69`, `\u{e0069}`), or HTML-entity-encoded (`&#xE0069;`, `&#917609;`, `&amp;#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

func InspectRawSchemaOrgJSONLD(rawHTML string) string

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

func IsBoschEbikeErrorCodeJSONMode(mode string) bool

IsBoschEbikeErrorCodeJSONMode reports whether mode is the Bosch eBike Help Center error-code formatter.

func IsDataGovAdapterID added in v2.8.34

func IsDataGovAdapterID(id string) bool

IsDataGovAdapterID reports whether id is a registered api.data.gov adapter ID.

func IsDisallowedMarkdownLinkDestination added in v2.8.17

func IsDisallowedMarkdownLinkDestination(rawHref string) bool

IsDisallowedMarkdownLinkDestination reports whether rawHref violates the strict fail-closed URI allowlist.

func IsDisallowedWikipediaTitle added in v2.8.17

func IsDisallowedWikipediaTitle(decodedTitle string) bool

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 IsDomainSpecificExtractorID added in v2.8.34

func IsDomainSpecificExtractorID(extractorID string) bool

IsDomainSpecificExtractorID reports whether extractorID is a domain-specific adapter that preempts generic custom-domain storefront overlay enrichment.

func IsJSONLDScriptAttr added in v2.8.17

func IsJSONLDScriptAttr(attrStr string) bool

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

func IsNuxtDevalueFlatArray(parsed any) bool

IsNuxtDevalueFlatArray detects whether a parsed JSON value is a Nuxt 3/4 `devalue` flat index-pointer array.

func IsObviousUnhydratedCSRShell added in v2.8.34

func IsObviousUnhydratedCSRShell(rawHTML string) bool

IsObviousUnhydratedCSRShell reports whether rawHTML is an empty client-side SPA mount shell without SSR or JSON-LD content.

func IsPDFBytes

func IsPDFBytes(data []byte) bool

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

func IsPublicOrPrivateSuffix(host string) bool

IsPublicOrPrivateSuffix reports whether host is itself a public or private suffix (or unregistrable).

func IsRound2HTMLMode added in v2.8.34

func IsRound2HTMLMode(mode string) bool

IsRound2HTMLMode reports whether mode is handled by the round-2 HTML extractors.

func IsRound2JSONMode added in v2.8.34

func IsRound2JSONMode(mode string) bool

IsRound2JSONMode reports whether mode is handled by the round-2 JSON formatters.

func IsSafeDeclarativeTwinURL added in v2.8.17

func IsSafeDeclarativeTwinURL(raw string) bool

IsSafeDeclarativeTwinURL reports whether raw is a safe public HTTPS declarative twin URL.

func IsSafePublicHostname added in v2.8.17

func IsSafePublicHostname(rawHost string) bool

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 IsSameAPIEndpointOriginAndPath added in v2.8.34

func IsSameAPIEndpointOriginAndPath(fetchURL, normalizedURL string) bool

IsSameAPIEndpointOriginAndPath reports whether fetchURL and normalizedURL share the same origin and decoded pathname.

func IsTwinRedirectErrorPage added in v2.8.34

func IsTwinRedirectErrorPage(fetchURL, finalURL string) bool

IsTwinRedirectErrorPage reports whether finalURL redirected away from fetchURL onto a generic error, 404, or registration landing path.

func IsValidISO5775ETRTO added in v2.8.34

func IsValidISO5775ETRTO(raw string) (string, bool)

IsValidISO5775ETRTO validates an ETRTO NN-NNN tire size against ISO 5775 rim bead seat diameters and realistic bicycle tire widths (18..130 mm).

func IsValidUserAgentHeaderValue added in v2.8.29

func IsValidUserAgentHeaderValue(ua string) bool

IsValidUserAgentHeaderValue verifies that a User-Agent string is 1..256 printable ASCII characters.

func IsWave2UpgradedHTMLMode added in v2.8.34

func IsWave2UpgradedHTMLMode(mode string) bool

IsWave2UpgradedHTMLMode reports whether mode is one of the 7 upgraded Wave 2 HTML extractors.

func IsWave2UpgradedJSONMode added in v2.8.34

func IsWave2UpgradedJSONMode(mode string) bool

IsWave2UpgradedJSONMode reports whether mode is handled by the upgraded Wave 2 JSON formatters (`finra_brokercheck_json`, `ncaa_espn_json`).

func IsWave2cEconHTMLMode added in v2.8.29

func IsWave2cEconHTMLMode(mode string) bool

IsWave2cEconHTMLMode reports whether mode is handled by the Category K Economy & Statistics HTML extractor.

func IsWave2cEconJSONMode added in v2.8.29

func IsWave2cEconJSONMode(mode string) bool

IsWave2cEconJSONMode reports whether mode is handled by the Category K Economy & Statistics JSON formatter.

func IsWave2cHealthTransportHTMLMode added in v2.8.29

func IsWave2cHealthTransportHTMLMode(mode string) bool

IsWave2cHealthTransportHTMLMode reports whether mode is handled by Group A Health & Transport HTML extractors.

func IsWave2cHealthTransportJSONMode added in v2.8.29

func IsWave2cHealthTransportJSONMode(mode string) bool

IsWave2cHealthTransportJSONMode reports whether mode is handled by Group A Health & Transport JSON formatters.

func IsWave2cHealthTransportTextMode added in v2.8.29

func IsWave2cHealthTransportTextMode(mode string) bool

IsWave2cHealthTransportTextMode reports whether mode is handled by Group A Health & Transport text/XML formatters.

func IsWave2cIpArchivesHTMLMode added in v2.8.29

func IsWave2cIpArchivesHTMLMode(mode string) bool

IsWave2cIpArchivesHTMLMode reports whether mode is handled by Group C IP, Archives & Culture HTML extractors.

func IsWave2cIpArchivesJSONMode added in v2.8.29

func IsWave2cIpArchivesJSONMode(mode string) bool

IsWave2cIpArchivesJSONMode reports whether mode is handled by Group C IP, Archives & Culture JSON formatters.

func IsWave2cLawHTMLMode added in v2.8.29

func IsWave2cLawHTMLMode(mode string) bool

IsWave2cLawHTMLMode reports whether mode is handled by Category I Federal Law & Courts HTML extractors.

func IsWave2cLawJSONMode added in v2.8.29

func IsWave2cLawJSONMode(mode string) bool

IsWave2cLawJSONMode reports whether mode is handled by Category I Federal Law & Courts JSON extractors.

func IsWave2cMoneyHTMLMode added in v2.8.29

func IsWave2cMoneyHTMLMode(mode string) bool

IsWave2cMoneyHTMLMode reports whether mode is handled by Category J HTML fallback dispatch.

func IsWave2cMoneyJSONMode added in v2.8.29

func IsWave2cMoneyJSONMode(mode string) bool

IsWave2cMoneyJSONMode reports whether mode is handled by Category J (Money, Elections & Contracts) JSON dispatch.

func IsWave2cMoneyTextMode added in v2.8.29

func IsWave2cMoneyTextMode(mode string) bool

IsWave2cMoneyTextMode reports whether mode is handled by Category J text/XML dispatch.

func IsWave2cScienceHTMLMode added in v2.8.29

func IsWave2cScienceHTMLMode(mode string) bool

IsWave2cScienceHTMLMode reports whether mode is handled by the Group B HTML fallback extractor.

func IsWave2cScienceJSONMode added in v2.8.29

func IsWave2cScienceJSONMode(mode string) bool

IsWave2cScienceJSONMode reports whether mode is handled by the Group B Science, Weather & Places JSON formatter.

func IsWave2cScienceTextMode added in v2.8.29

func IsWave2cScienceTextMode(mode string) bool

IsWave2cScienceTextMode reports whether mode is handled by the Group B text formatter (e.g. usgs_water_rdb).

func IsWave2dDevHTMLMode added in v2.8.29

func IsWave2dDevHTMLMode(mode string) bool

IsWave2dDevHTMLMode reports whether mode is handled by M4B Group A HTML extractors.

func IsWave2dDevJSONMode added in v2.8.29

func IsWave2dDevJSONMode(mode string) bool

IsWave2dDevJSONMode reports whether mode is handled by M4B Group A (Developer Ecosystem) JSON formatters.

func IsWave2dDevTextMode added in v2.8.29

func IsWave2dDevTextMode(mode string) bool

IsWave2dDevTextMode reports whether mode is handled by M4B Group A text/XML formatters.

func IsWave2dJobsHTMLMode added in v2.8.29

func IsWave2dJobsHTMLMode(mode string) bool

IsWave2dJobsHTMLMode reports whether mode is handled by Category S US Jobs HTML extractors (#163-#168).

func IsWave2dJobsJSONMode added in v2.8.29

func IsWave2dJobsJSONMode(mode string) bool

IsWave2dJobsJSONMode reports whether mode is handled by Category S US Jobs JSON formatters (#163-#166).

func IsWave2dLocalHTMLMode added in v2.8.29

func IsWave2dLocalHTMLMode(mode string) bool

IsWave2dLocalHTMLMode reports whether mode is handled by Wave 2D Category U HTML extractors (#186-189, #191-192).

func IsWave2dLocalJSONMode added in v2.8.29

func IsWave2dLocalJSONMode(mode string) bool

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

func IsWave2dLocalTextMode(mode string) bool

IsWave2dLocalTextMode reports whether mode is handled by Wave 2D Category U text/CSV formatters (#192).

func IsWave2dMediaVideoHTMLMode added in v2.8.29

func IsWave2dMediaVideoHTMLMode(mode string) bool

IsWave2dMediaVideoHTMLMode reports whether mode is handled by M4A Group B HTML fallback extractors.

func IsWave2dMediaVideoJSONMode added in v2.8.29

func IsWave2dMediaVideoJSONMode(mode string) bool

IsWave2dMediaVideoJSONMode reports whether mode is handled by M4A Group B (US News & Video) JSON formatters.

func IsWave2dMediaVideoTextMode added in v2.8.29

func IsWave2dMediaVideoTextMode(mode string) bool

IsWave2dMediaVideoTextMode reports whether mode is handled by M4A Group B text/XML formatters.

func IsWave2dRetailHTMLMode added in v2.8.29

func IsWave2dRetailHTMLMode(mode string) bool

IsWave2dRetailHTMLMode reports whether mode is handled by Wave 2D Category P HTML extractors (#137, #139-142).

func IsWave2dRetailJSONMode added in v2.8.29

func IsWave2dRetailJSONMode(mode string) bool

IsWave2dRetailJSONMode reports whether mode is handled by Wave 2D Category P JSON formatters (#131-135).

func IsWave2dRetailTextMode added in v2.8.29

func IsWave2dRetailTextMode(mode string) bool

IsWave2dRetailTextMode reports whether mode is handled by Wave 2D Category P XML/Atom feed formatters (#143-144).

func IsWave2dSportsMiscHTMLMode added in v2.8.29

func IsWave2dSportsMiscHTMLMode(mode string) bool

IsWave2dSportsMiscHTMLMode reports whether mode is handled by Category V Sports & Misc HTML extractors (#193-#200).

func IsWave2dSportsMiscJSONMode added in v2.8.29

func IsWave2dSportsMiscJSONMode(mode string) bool

IsWave2dSportsMiscJSONMode reports whether mode is handled by Category V Sports & Misc JSON formatters (#193-#200).

func IsWave2dSportsMiscTextMode added in v2.8.29

func IsWave2dSportsMiscTextMode(mode string) bool

IsWave2dSportsMiscTextMode reports whether mode is handled by Category V Sports & Misc text/CSV formatters (#198).

func IsWave3CommunityHTMLMode added in v2.8.34

func IsWave3CommunityHTMLMode(mode string) bool

IsWave3CommunityHTMLMode reports whether mode is handled by Category E Community HTML extractors (#243-#250).

func IsWave3CommunityJSONMode added in v2.8.34

func IsWave3CommunityJSONMode(mode string) bool

IsWave3CommunityJSONMode reports whether mode is handled by Category E Community JSON formatters (#245-#250).

func IsWave3CyclingComponentsHTMLMode added in v2.8.34

func IsWave3CyclingComponentsHTMLMode(mode string) bool

IsWave3CyclingComponentsHTMLMode reports whether mode is one of the 9 Category O1 HTML modes (#341-#349).

func IsWave3CyclingComponentsJSONMode added in v2.8.34

func IsWave3CyclingComponentsJSONMode(mode string) bool

IsWave3CyclingComponentsJSONMode reports whether mode is handled by Category O1 JSON formatters (`ifixit_json`).

func IsWave3CyclingOEMsHTMLMode added in v2.8.34

func IsWave3CyclingOEMsHTMLMode(mode string) bool

IsWave3CyclingOEMsHTMLMode reports whether mode is one of the 9 Category O2 HTML modes (#350-#358).

func IsWave3CyclingOEMsJSONMode added in v2.8.34

func IsWave3CyclingOEMsJSONMode(mode string) bool

IsWave3CyclingOEMsJSONMode reports whether mode is handled by Category O2 JSON formatters (`cpsc_ebike_incidents_json`).

func IsWave3DevInfraHTMLMode added in v2.8.34

func IsWave3DevInfraHTMLMode(mode string) bool

IsWave3DevInfraHTMLMode reports whether mode is one of the 13 Category N Developer Infrastructure HTML modes (#327-#340).

func IsWave3DevInfraJSONMode added in v2.8.34

func IsWave3DevInfraJSONMode(mode string) bool

IsWave3DevInfraJSONMode reports whether mode is handled by Category N JSON formatters.

func IsWave3DevInfraTextMode added in v2.8.34

func IsWave3DevInfraTextMode(mode string) bool

IsWave3DevInfraTextMode reports whether mode is handled by Category N text/streaming formatters (`gerrit_json`, `apis_guru_list_bounded`, `web_compat_bounded`, `web_compat_json`).

func IsWave3EduHTMLMode added in v2.8.34

func IsWave3EduHTMLMode(mode string) bool

IsWave3EduHTMLMode reports whether mode is handled by Category B Education HTML extractors (#217-#225).

func IsWave3EduJSONMode added in v2.8.34

func IsWave3EduJSONMode(mode string) bool

IsWave3EduJSONMode reports whether mode is handled by Category B Education JSON formatters (#222-#224).

func IsWave3FinanceHTMLMode added in v2.8.34

func IsWave3FinanceHTMLMode(mode string) bool

IsWave3FinanceHTMLMode reports whether mode is one of the Category S HTML modes (#387, #391, #392).

func IsWave3FinanceJSONMode added in v2.8.34

func IsWave3FinanceJSONMode(mode string) bool

IsWave3FinanceJSONMode reports whether mode is one of the Category S JSON formatters (#388, #389, #390, #392).

func IsWave3FinanceTextMode added in v2.8.34

func IsWave3FinanceTextMode(mode string) bool

IsWave3FinanceTextMode reports whether mode is one of the Category S text/CSV formatters (#387).

func IsWave3GTINIdentityHTMLMode added in v2.8.34

func IsWave3GTINIdentityHTMLMode(mode string) bool

IsWave3GTINIdentityHTMLMode reports whether mode is one of the Category Q HTML modes (#368-#374 + fcc-id).

func IsWave3GTINIdentityJSONMode added in v2.8.34

func IsWave3GTINIdentityJSONMode(mode string) bool

IsWave3GTINIdentityJSONMode reports whether mode is one of the Category Q JSON formatters.

func IsWave3GTINIdentityTextMode added in v2.8.34

func IsWave3GTINIdentityTextMode(mode string) bool

IsWave3GTINIdentityTextMode reports whether mode is one of the Category Q text formatters.

func IsWave3GovHTMLMode added in v2.8.34

func IsWave3GovHTMLMode(mode string) bool

IsWave3GovHTMLMode reports whether mode is one of the Category A Local Government HTML extractors (#202-#216).

func IsWave3GovJSONMode added in v2.8.34

func IsWave3GovJSONMode(mode string) bool

IsWave3GovJSONMode reports whether mode is one of the Category A Local Government JSON formatters.

func IsWave3GovTextMode added in v2.8.34

func IsWave3GovTextMode(mode string) bool

IsWave3GovTextMode reports whether mode is handled by Category A text/XML/mixed formatters (`boarddocs_text`).

func IsWave3JobsPublicHTMLMode added in v2.8.34

func IsWave3JobsPublicHTMLMode(mode string) bool

IsWave3JobsPublicHTMLMode reports whether mode is handled by Category C Public-Sector & Staffing Jobs HTML extractors (#226-#233).

func IsWave3JobsPublicJSONMode added in v2.8.34

func IsWave3JobsPublicJSONMode(mode string) bool

IsWave3JobsPublicJSONMode reports whether mode is handled by Category C Public-Sector & Staffing Jobs JSON formatters (#226-#233).

func IsWave3MediaLyricsHTMLMode added in v2.8.34

func IsWave3MediaLyricsHTMLMode(mode string) bool

IsWave3MediaLyricsHTMLMode reports whether mode is one of the 12 Category R HTML modes (#375-#386).

func IsWave3MediaLyricsJSONMode added in v2.8.34

func IsWave3MediaLyricsJSONMode(mode string) bool

IsWave3MediaLyricsJSONMode reports whether mode is one of the Category R JSON formatters.

func IsWave3MediaLyricsTextMode added in v2.8.34

func IsWave3MediaLyricsTextMode(mode string) bool

IsWave3MediaLyricsTextMode reports whether mode is handled by Category R text formatters (`imdb_datasets_tsv`).

func IsWave3PropRestIRHTMLMode added in v2.8.34

func IsWave3PropRestIRHTMLMode(mode string) bool

IsWave3PropRestIRHTMLMode reports whether mode is handled by Categories F/G/H HTML extractors (#251-#261).

func IsWave3PropRestIRJSONMode added in v2.8.34

func IsWave3PropRestIRJSONMode(mode string) bool

IsWave3PropRestIRJSONMode reports whether mode is handled by Categories F/G/H JSON formatters (#259).

func IsWave3PropRestIRTextMode added in v2.8.34

func IsWave3PropRestIRTextMode(mode string) bool

IsWave3PropRestIRTextMode reports whether mode is handled by Categories F/G/H text/RSS XML formatters (#260-#261).

func IsWave3RegulatorsHTMLMode added in v2.8.34

func IsWave3RegulatorsHTMLMode(mode string) bool

IsWave3RegulatorsHTMLMode reports whether mode is one of the 10 Category K Part 1 HTML extractors (#279-#288).

func IsWave3RegulatorsHealthHTMLMode added in v2.8.34

func IsWave3RegulatorsHealthHTMLMode(mode string) bool

IsWave3RegulatorsHealthHTMLMode reports whether mode is one of the Category K Part 2 HTML extractors (#289-#300).

func IsWave3RegulatorsHealthJSONMode added in v2.8.34

func IsWave3RegulatorsHealthJSONMode(mode string) bool

IsWave3RegulatorsHealthJSONMode reports whether mode is one of the Category K Part 2 JSON formatters (#291-#300).

func IsWave3RegulatorsHealthTextMode added in v2.8.34

func IsWave3RegulatorsHealthTextMode(mode string) bool

IsWave3RegulatorsHealthTextMode reports whether mode is one of the Category K Part 2 text/RSS/CSV formatters (#289-#291, #296).

func IsWave3RegulatorsJSONMode added in v2.8.34

func IsWave3RegulatorsJSONMode(mode string) bool

IsWave3RegulatorsJSONMode reports whether mode is one of the Category K Part 1 JSON formatters.

func IsWave3ResaleHTMLMode added in v2.8.34

func IsWave3ResaleHTMLMode(mode string) bool

IsWave3ResaleHTMLMode reports whether mode is one of the 8 Category P HTML modes (#360-#367).

func IsWave3ResaleJSONMode added in v2.8.34

func IsWave3ResaleJSONMode(mode string) bool

IsWave3ResaleJSONMode reports whether mode is one of the Category P JSON formatters (`reverb_listing_json`, `reverb_search_json`).

func IsWave3SchemaHTMLMode added in v2.8.34

func IsWave3SchemaHTMLMode(mode string) bool

IsWave3SchemaHTMLMode reports whether mode is handled by Category D Universal Schema.org extractors (#237-#241).

func IsWave3ScholarlyHTMLMode added in v2.8.34

func IsWave3ScholarlyHTMLMode(mode string) bool

IsWave3ScholarlyHTMLMode reports whether mode is one of the 14 Category L HTML extractors (#301-#314).

func IsWave3ScholarlyJSONMode added in v2.8.34

func IsWave3ScholarlyJSONMode(mode string) bool

IsWave3ScholarlyJSONMode reports whether mode is one of the Category L JSON formatters (#301-#313).

func IsWave3ScholarlyTextMode added in v2.8.34

func IsWave3ScholarlyTextMode(mode string) bool

IsWave3ScholarlyTextMode reports whether mode is a Category L text/XML formatter (`dblp_xml`).

func IsWave3SecurityIntelHTMLMode added in v2.8.34

func IsWave3SecurityIntelHTMLMode(mode string) bool

IsWave3SecurityIntelHTMLMode reports whether mode is one of the Category M HTML extractors.

func IsWave3SecurityIntelJSONMode added in v2.8.34

func IsWave3SecurityIntelJSONMode(mode string) bool

IsWave3SecurityIntelJSONMode reports whether mode is one of the Category M JSON formatters (#315-#326).

func IsWave3SecurityIntelTextMode added in v2.8.34

func IsWave3SecurityIntelTextMode(mode string) bool

IsWave3SecurityIntelTextMode reports whether mode is one of the Category M text/CSV/STIX/RSS formatters.

func IsWave3SocialCreatorHTMLMode added in v2.8.34

func IsWave3SocialCreatorHTMLMode(mode string) bool

IsWave3SocialCreatorHTMLMode reports whether mode is one of the 7 Category T HTML modes (#394-#400).

func IsWave3SocialCreatorJSONMode added in v2.8.34

func IsWave3SocialCreatorJSONMode(mode string) bool

IsWave3SocialCreatorJSONMode reports whether mode is one of the 7 Category T JSON modes (#393-#399).

func IsWave3StoreAddonsHTMLMode added in v2.8.34

func IsWave3StoreAddonsHTMLMode(mode string) bool

IsWave3StoreAddonsHTMLMode reports whether mode is handled by Category I Store Add-Ons HTML extractors (#263-#270).

func IsWave3StoreAddonsJSONMode added in v2.8.34

func IsWave3StoreAddonsJSONMode(mode string) bool

IsWave3StoreAddonsJSONMode reports whether mode is handled by Category I Store Add-Ons JSON formatters (#265, #266).

func IsWave3TradeHTMLMode added in v2.8.34

func IsWave3TradeHTMLMode(mode string) bool

IsWave3TradeHTMLMode reports whether mode is one of the 8 Category J Trade, Tariffs & Sanctions HTML extractors (#271-#278).

func IsWave3TradeJSONMode added in v2.8.34

func IsWave3TradeJSONMode(mode string) bool

IsWave3TradeJSONMode reports whether mode is handled by Category J JSON formatters (#271, #272, #275).

func IsWave3TradeTextMode added in v2.8.34

func IsWave3TradeTextMode(mode string) bool

IsWave3TradeTextMode reports whether mode is handled by Category J XML/text formatters (#274, #276).

func IsWikimediaHost added in v2.8.17

func IsWikimediaHost(rawHost string) bool

IsWikimediaHost reports whether rawHost belongs to Wikipedia or a sister Wikimedia project domain.

func IsWikipediaHost added in v2.8.17

func IsWikipediaHost(rawHost string) bool

IsWikipediaHost reports whether rawHost is wikipedia.org or a subdomain of wikipedia.org.

func LookupKnownRegistrableDomain added in v2.8.17

func LookupKnownRegistrableDomain(host string) (string, bool)

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 MakeAPIKeyHint added in v2.8.34

func MakeAPIKeyHint(apiKey string) string

MakeAPIKeyHint returns a non-secret display hint (`****` when < 16 UTF-16 code units; `...<last4>` otherwise).

func MakeSafeCodeFence added in v2.8.17

func MakeSafeCodeFence(code, lang string, preferTilde bool) string

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

func MatchesApprovedWildcard(rawWildcard, rawCandidate string) bool

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

func NeedsBrowserRender(rawHTML string) bool

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(prose string) string

NeutralizeAllUnsafeMarkdownLinks neutralizes disallowed inline `](...)` destinations, `[id]: ...` reference definitions, and bare `//host.tld` protocol-relative URLs in linear O(N) time.

func NormalizeAPIKeyUserID added in v2.8.34

func NormalizeAPIKeyUserID(rawUserID string) string

NormalizeAPIKeyUserID normalizes a Hub API-key vault user identifier.

func NormalizeProviderID added in v2.8.34

func NormalizeProviderID(rawProvider string) string

NormalizeProviderID normalizes a provider or adapter slug for API key lookup.

func NormalizeStrictGTIN added in v2.8.29

func NormalizeStrictGTIN(raw string) string

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

func NormalizeTrackerHostCandidate(raw string) (string, bool)

NormalizeTrackerHostCandidate normalizes a candidate domain host per RFC 1123 (rejecting IPv4 literals and numeric-only TLDs).

func NormalizeWikipediaLang added in v2.8.17

func NormalizeWikipediaLang(rawLang, fallback string) string

NormalizeWikipediaLang validates and normalizes a Wikipedia language code, returning fallback (default "en") when invalid.

func ParseDeclarativeYAML added in v2.6.2

func ParseDeclarativeYAML(raw []byte) (any, error)

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

func ParseMarkdownFrontmatter(md string) (title, description, body string)

ParseMarkdownFrontmatter parses and strips a leading YAML `---` frontmatter block (up to 4 KiB), returning sanitized `title`, `description`, and remaining `body`.

func ParseNostrNIP01Frames added in v2.8.34

func ParseNostrNIP01Frames(subID string, frames []string, maxEvents int) []any

ParseNostrNIP01Frames extracts validated NIP-01 EVENT objects matching subID from raw WebSocket frames.

func PercentEncodeUnsafeRecordURLChars added in v2.8.17

func PercentEncodeUnsafeRecordURLChars(urlStr string) string

PercentEncodeUnsafeRecordURLChars percent-encodes characters that can break Markdown link syntax or inject raw tags (`(`, `)`, `[`, `]`, `<`, `>`, `\`, and ASCII whitespace).

func PlainText

func PlainText(rawHTML string) string

PlainText strips scripts/styles/tags from HTML and collapses 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

func RedactPII(s string) string

RedactPII replaces email addresses, SSNs, phone numbers, and Luhn-valid payment card numbers with `[REDACTED_*]`.

func RedactPIIMarkdownSafe added in v2.8.17

func RedactPIIMarkdownSafe(text string) string

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 RedactSecretsInBody added in v2.8.34

func RedactSecretsInBody(body string, secrets []string) string

RedactSecretsInBody replaces every injected secret (>= 4 UTF-16 code units) in an upstream response body with `[redacted]` across raw, encodeURIComponent (`%20` & `+`), URLSearchParams (`+` & `%20`), and mixed-case `%xx`/`%XX` forms.

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 RegisterWave3CyclingComponentsHTMLModes added in v2.8.34

func RegisterWave3CyclingComponentsHTMLModes()

RegisterWave3CyclingComponentsHTMLModes registers all Category O1 Bike Components & Help HTML modes lazily.

func RegisterWave3CyclingOEMsHTMLModes added in v2.8.34

func RegisterWave3CyclingOEMsHTMLModes()

RegisterWave3CyclingOEMsHTMLModes registers all Category O2 HTML modes (#350-#358) lazily.

func RegisterWave3DevInfraHTMLModes added in v2.8.34

func RegisterWave3DevInfraHTMLModes()

RegisterWave3DevInfraHTMLModes registers all Category N Developer Infrastructure HTML modes lazily.

func RegisterWave3FinanceHTMLModes added in v2.8.34

func RegisterWave3FinanceHTMLModes()

RegisterWave3FinanceHTMLModes registers all Category S Finance & Market Data HTML modes lazily.

func RegisterWave3GTINIdentityHTMLModes added in v2.8.34

func RegisterWave3GTINIdentityHTMLModes()

RegisterWave3GTINIdentityHTMLModes registers all Category Q Product Identity & Data Pools HTML modes lazily.

func RegisterWave3MediaLyricsHTMLModes added in v2.8.34

func RegisterWave3MediaLyricsHTMLModes()

RegisterWave3MediaLyricsHTMLModes registers all Category R Media & Entertainment / Lyrics HTML modes lazily.

func RegisterWave3ResaleHTMLModes added in v2.8.34

func RegisterWave3ResaleHTMLModes()

RegisterWave3ResaleHTMLModes registers all Category P Resale & Marketplaces HTML modes lazily.

func RegisterWave3ScholarlyHTMLModes added in v2.8.34

func RegisterWave3ScholarlyHTMLModes()

RegisterWave3ScholarlyHTMLModes registers all 14 Category L Research & Scholarly HTML modes (#301-#314).

func RegisterWave3SecurityIntelHTMLModes added in v2.8.34

func RegisterWave3SecurityIntelHTMLModes()

RegisterWave3SecurityIntelHTMLModes registers all Category M HTML modes via RegisterExternalHTMLModeLazy.

func RegisterWave3SocialCreatorHTMLModes added in v2.8.34

func RegisterWave3SocialCreatorHTMLModes()

RegisterWave3SocialCreatorHTMLModes registers all Category T Open Social & Creator HTML modes lazily.

func RerankPassages

func RerankPassages(doc, query string, maxChars int) string

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

func ResolveEffectiveMinIntervalMs(reqMinIntervalMs int, host string) int

ResolveEffectiveMinIntervalMs returns the effective pacing floor for a host in milliseconds.

func ResolveEffectiveUserAgent added in v2.8.29

func ResolveEffectiveUserAgent(profile, host, fallback string) string

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

func ResolveGatsbyPageDataTwinURL(rawHTML, pageFinalURL, selfHost string) string

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 ResolveOfficialAPIExtraHeaders added in v2.8.34

func ResolveOfficialAPIExtraHeaders(in OfficialAPIExtraInput) map[string]string

ResolveOfficialAPIExtraHeaders computes provider/host-specific companion headers (Twitch Client-Id, Google Places FieldMask, UPS transId).

func ResolveOfficialAPIExtraSecrets added in v2.8.34

func ResolveOfficialAPIExtraSecrets(in OfficialAPIExtraInput) ([]string, string)

ResolveOfficialAPIExtraSecrets returns companion secrets (sensitive headers, PodcastIndex API secret, Twitch/IGDB Client-ID) for redaction.

func ResolveWikipediaCanonicalFinalURL added in v2.8.17

func ResolveWikipediaCanonicalFinalURL(requestedURL, responseFinalURL string) string

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 RunWave2UpgradedHTMLMode added in v2.8.34

func RunWave2UpgradedHTMLMode(mode, rawHTML, baseURL string) (string, bool)

RunWave2UpgradedHTMLMode executes one of the 7 upgraded Wave 2 HTML modes and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave2cEconHTMLMode added in v2.8.29

func RunWave2cEconHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)

RunWave2cEconHTMLMode executes a Category K HTML fallback extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave2cHealthTransportHTMLMode added in v2.8.29

func RunWave2cHealthTransportHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)

RunWave2cHealthTransportHTMLMode executes a Group A HTML fallback extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave2cIpArchivesHTMLMode added in v2.8.29

func RunWave2cIpArchivesHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)

RunWave2cIpArchivesHTMLMode executes a Group C HTML fallback extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave2cLawHTMLMode added in v2.8.29

func RunWave2cLawHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)

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

func RunWave2cMoneyHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)

RunWave2cMoneyHTMLMode runs a Category J HTML fallback extractor and returns rendered markdown.

func RunWave2cScienceHTMLMode added in v2.8.29

func RunWave2cScienceHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)

RunWave2cScienceHTMLMode executes a Group B HTML fallback extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave2dJobsHTMLMode added in v2.8.29

func RunWave2dJobsHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)

RunWave2dJobsHTMLMode executes a Category S HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave2dLocalHTMLMode added in v2.8.29

func RunWave2dLocalHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)

RunWave2dLocalHTMLMode executes a Category U HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave2dRetailHTMLMode added in v2.8.29

func RunWave2dRetailHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)

RunWave2dRetailHTMLMode executes a Category P HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave2dSportsMiscHTMLMode added in v2.8.29

func RunWave2dSportsMiscHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)

RunWave2dSportsMiscHTMLMode executes a Category V HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave3CyclingComponentsHTMLMode added in v2.8.34

func RunWave3CyclingComponentsHTMLMode(mode, rawHTML, baseURL string) (string, bool)

RunWave3CyclingComponentsHTMLMode executes a Category O1 HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave3CyclingOEMsHTMLMode added in v2.8.34

func RunWave3CyclingOEMsHTMLMode(mode, rawHTML, baseURL string) (string, bool)

RunWave3CyclingOEMsHTMLMode executes a Category O2 HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave3DevInfraHTMLMode added in v2.8.34

func RunWave3DevInfraHTMLMode(mode, rawHTML, baseURL string) (string, bool)

RunWave3DevInfraHTMLMode executes a Category N HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave3FinanceHTMLMode added in v2.8.34

func RunWave3FinanceHTMLMode(mode, rawHTML, baseURL string) (string, bool)

RunWave3FinanceHTMLMode executes a Category S HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave3GTINIdentityHTMLMode added in v2.8.34

func RunWave3GTINIdentityHTMLMode(mode, rawHTML, baseURL string) (string, bool)

RunWave3GTINIdentityHTMLMode executes a Category Q HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave3GovHTMLMode added in v2.8.34

func RunWave3GovHTMLMode(mode, rawHTML, baseURL string) (string, bool)

RunWave3GovHTMLMode executes a Category A HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave3JobsPublicHTMLMode added in v2.8.34

func RunWave3JobsPublicHTMLMode(mode string, rawHTML string, baseURL string) (string, bool)

RunWave3JobsPublicHTMLMode executes a Category C HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave3MediaLyricsHTMLMode added in v2.8.34

func RunWave3MediaLyricsHTMLMode(mode, rawHTML, baseURL string) (string, bool)

RunWave3MediaLyricsHTMLMode executes a Category R HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave3PropRestIRHTMLMode added in v2.8.34

func RunWave3PropRestIRHTMLMode(mode, rawHTML, baseURL string) (string, bool)

RunWave3PropRestIRHTMLMode executes a Category F/G/H HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave3RegulatorsHTMLMode added in v2.8.34

func RunWave3RegulatorsHTMLMode(mode, rawHTML, baseURL string) (string, bool)

RunWave3RegulatorsHTMLMode executes a Category K Part 1 HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave3RegulatorsHealthHTMLMode added in v2.8.34

func RunWave3RegulatorsHealthHTMLMode(mode, rawHTML, baseURL string) (string, bool)

RunWave3RegulatorsHealthHTMLMode executes a Category K Part 2 HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave3ResaleHTMLMode added in v2.8.34

func RunWave3ResaleHTMLMode(mode, rawHTML, baseURL string) (string, bool)

RunWave3ResaleHTMLMode executes a Category P HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave3ScholarlyHTMLMode added in v2.8.34

func RunWave3ScholarlyHTMLMode(mode, rawHTML, baseURL string) (string, bool)

RunWave3ScholarlyHTMLMode executes a Category L HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave3SecurityIntelHTMLMode added in v2.8.34

func RunWave3SecurityIntelHTMLMode(mode, rawHTML, baseURL string) (string, bool)

RunWave3SecurityIntelHTMLMode executes a Category M HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave3SocialCreatorHTMLMode added in v2.8.34

func RunWave3SocialCreatorHTMLMode(mode, rawHTML, baseURL string) (string, bool)

RunWave3SocialCreatorHTMLMode executes a Category T HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave3StoreAddonsHTMLMode added in v2.8.34

func RunWave3StoreAddonsHTMLMode(mode, rawHTML, baseURL string) (string, bool)

RunWave3StoreAddonsHTMLMode executes a Category I HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func RunWave3TradeHTMLMode added in v2.8.34

func RunWave3TradeHTMLMode(mode, rawHTML, baseURL string) (string, bool)

RunWave3TradeHTMLMode executes a Category J HTML extractor and returns JSON-marshaled DeclarativePostFetchResult.

func SanitizeFullMarkdownDocumentForArtifact added in v2.8.17

func SanitizeFullMarkdownDocumentForArtifact(fullMD string) string

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

func SanitizeMarkdown(md, baseURL string) string

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 `&lt;` 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

func SanitizeMarkdownWithOptions(md, baseURL string, allowPdfPageMarkers bool) string

SanitizeMarkdownWithOptions sanitizes Markdown with optional PDF page marker preservation.

func SanitizePlainMetadataText added in v2.8.17

func SanitizePlainMetadataText(raw string, maxLen int) string

SanitizePlainMetadataText strips smuggling/control characters, normalizes whitespace, caps length to maxLen, neutralizes unsafe Markdown links, and escapes `<` to `&lt;` (returning `""` when empty).

func SanitizeSchemaHTTPSURL added in v2.8.17

func SanitizeSchemaHTTPSURL(raw any, baseURL string) string

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

func SanitizeSchemaPlainField(raw any, maxLen int) string

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

func SanitizeScrapedMarkdown(md string) string

SanitizeScrapedMarkdown applies the fail-closed Markdown sanitizer with empty baseURL.

func SanitizeScrapedMeta added in v2.6.3

func SanitizeScrapedMeta(s string) string

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

func SanitizeScrapedMetadataField(raw string, maxLen int) string

SanitizeScrapedMetadataField sanitizes single-line metadata fields (`Title`, `Description`, `Author`, `SiteName`), stripping invisible smuggling characters, collapsing newlines/tabs, neutralizing unsafe Markdown links, and escaping `<` -> `&lt;`.

func SanitizeScrapedTimestampField added in v2.8.17

func SanitizeScrapedTimestampField(raw string, maxLen int) string

SanitizeScrapedTimestampField sanitizes ISO/human timestamp metadata fields, neutralizing Markdown/HTML syntax.

func ScanGeneratorMetaTags added in v2.8.17

func ScanGeneratorMetaTags(htmlStr string, maxChars int) []string

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

func ScrubTwinURLSecrets(rawURL string) string

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

func SplitMarkdownByCodeFences(rawMD string) []string

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

func SplitPDFPagesAndMarkers(rawText string, maxPages int) (pages []string, markedMarkdown string)

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

func StripInvisibleSchemaChars(s string) string

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

func StripInvisibleSmugglingChars(s string) string

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

func StripMarkdownTableDividerLinesLinear(s string) string

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

func UTF16Len(s string) int

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

func UTF16OffsetToByteOffset(s string, utf16Off int) int

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 ValidateTwinRedirectFull added in v2.8.34

func ValidateTwinRedirectFull(twinID, initialFetchURL, finalURL, selfHost string) (trusted bool, errorPage bool)

ValidateTwinRedirectFull validates whether finalURL is a trusted redirect destination for twinID starting from initialFetchURL, and also reports whether finalURL landed on an error page.

func YAMLToJSON added in v2.6.2

func YAMLToJSON(raw []byte) ([]byte, error)

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"`
	MaxFetchBytes        int    `json:"maxFetchBytes,omitempty"`
	AllowTruncatedStream bool   `json:"allowTruncatedStream,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 + manifest policy (including exact/wildcard universal manifests with explicit policy metadata) 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"`
	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

type DeclarativeExactSegments struct {
	Bool  bool
	Count *int
}

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"`
	FooterItalicTemplate  string                        `json:"footerItalicTemplate,omitempty"`
	FooterItalicWhenVar   string                        `json:"footerItalicWhenVar,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 on 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 FormatNostrNIP01Frames added in v2.8.34

func FormatNostrNIP01Frames(origURL, relayURL, subID, nip11Raw string, frames []string, maxEvents int) (*DeclarativeFormattedDoc, bool)

FormatNostrNIP01Frames parses optional NIP-11 relay metadata + raw NIP-01 WebSocket frames into a sanitized DeclarativeFormattedDoc.

func FormatRound2JSONDoc added in v2.8.34

func FormatRound2JSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatRound2JSONDoc formats a round-2 JSON twin payload into a DeclarativeFormattedDoc.

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 FormatWave2UpgradedJSONDoc added in v2.8.34

func FormatWave2UpgradedJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave2UpgradedJSONDoc formats a JSON twin payload for `finra_brokercheck_json` or `ncaa_espn_json`.

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 FormatWave3CommunityJSONDoc added in v2.8.34

func FormatWave3CommunityJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3CommunityJSONDoc formats a Category E Community JSON twin payload into DeclarativeFormattedDoc.

func FormatWave3CyclingComponentsJSONDoc added in v2.8.34

func FormatWave3CyclingComponentsJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3CyclingComponentsJSONDoc formats a Category O1 JSON twin payload (`ifixit_json`) into DeclarativeFormattedDoc.

func FormatWave3CyclingOEMsJSONDoc added in v2.8.34

func FormatWave3CyclingOEMsJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3CyclingOEMsJSONDoc formats a Category O2 JSON twin payload into DeclarativeFormattedDoc.

func FormatWave3DevInfraJSONDoc added in v2.8.34

func FormatWave3DevInfraJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3DevInfraJSONDoc formats a Category N JSON twin payload into DeclarativeFormattedDoc.

func FormatWave3DevInfraTextDoc added in v2.8.34

func FormatWave3DevInfraTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3DevInfraTextDoc formats a Category N text/streaming twin payload (`gerrit_json`, `apis_guru_list_bounded`, `web_compat_bounded`).

func FormatWave3EduJSONDoc added in v2.8.34

func FormatWave3EduJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3EduJSONDoc formats a Category B Education JSON twin payload into DeclarativeFormattedDoc.

func FormatWave3FinanceJSONDoc added in v2.8.34

func FormatWave3FinanceJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3FinanceJSONDoc formats a Category S JSON twin payload into DeclarativeFormattedDoc.

func FormatWave3FinanceTextDoc added in v2.8.34

func FormatWave3FinanceTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3FinanceTextDoc formats a Category S text/CSV twin payload (`fed_h15_csv`).

func FormatWave3GTINIdentityJSONDoc added in v2.8.34

func FormatWave3GTINIdentityJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3GTINIdentityJSONDoc formats a Category Q JSON twin payload into DeclarativeFormattedDoc.

func FormatWave3GTINIdentityTextDoc added in v2.8.34

func FormatWave3GTINIdentityTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3GTINIdentityTextDoc formats a Category Q text twin payload (`opengtindb_text`) into DeclarativeFormattedDoc.

func FormatWave3GovJSONDoc added in v2.8.34

func FormatWave3GovJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3GovJSONDoc formats a Category A JSON twin payload into DeclarativeFormattedDoc.

func FormatWave3GovTextDoc added in v2.8.34

func FormatWave3GovTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3GovTextDoc formats a Category A text/XML/JSON payload (BoardDocs Domino responses).

func FormatWave3JobsPublicJSONDoc added in v2.8.34

func FormatWave3JobsPublicJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3JobsPublicJSONDoc formats a Category C JSON payload into a DeclarativeFormattedDoc.

func FormatWave3MediaLyricsJSONDoc added in v2.8.34

func FormatWave3MediaLyricsJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3MediaLyricsJSONDoc formats a Category R JSON twin payload into DeclarativeFormattedDoc.

func FormatWave3MediaLyricsTextDoc added in v2.8.34

func FormatWave3MediaLyricsTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3MediaLyricsTextDoc formats a Category R text twin payload (`imdb_datasets_tsv`).

func FormatWave3PropRestIRJSONDoc added in v2.8.34

func FormatWave3PropRestIRJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3PropRestIRJSONDoc formats a Category H JSON twin payload (`q4_ir_json`) into DeclarativeFormattedDoc.

func FormatWave3PropRestIRTextDoc added in v2.8.34

func FormatWave3PropRestIRTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3PropRestIRTextDoc formats Category H RSS/Atom XML feeds (`ir_portal_rss_xml`, `company_newsroom_rss_xml`) into DeclarativeFormattedDoc.

func FormatWave3RegulatorsHealthJSONDoc added in v2.8.34

func FormatWave3RegulatorsHealthJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3RegulatorsHealthJSONDoc formats a Category K Part 2 JSON twin payload into DeclarativeFormattedDoc.

func FormatWave3RegulatorsHealthTextDoc added in v2.8.34

func FormatWave3RegulatorsHealthTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3RegulatorsHealthTextDoc formats a Category K Part 2 text/RSS/CSV payload into DeclarativeFormattedDoc.

func FormatWave3RegulatorsJSONDoc added in v2.8.34

func FormatWave3RegulatorsJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3RegulatorsJSONDoc formats a Category K Part 1 JSON payload into DeclarativeFormattedDoc.

func FormatWave3ResaleJSONDoc added in v2.8.34

func FormatWave3ResaleJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3ResaleJSONDoc formats a Category P JSON twin payload into DeclarativeFormattedDoc.

func FormatWave3ScholarlyJSONDoc added in v2.8.34

func FormatWave3ScholarlyJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3ScholarlyJSONDoc formats a Category L JSON twin payload into DeclarativeFormattedDoc.

func FormatWave3ScholarlyTextDoc added in v2.8.34

func FormatWave3ScholarlyTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3ScholarlyTextDoc formats a Category L text/XML twin payload (`dblp_xml`).

func FormatWave3SecurityIntelJSONDoc added in v2.8.34

func FormatWave3SecurityIntelJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3SecurityIntelJSONDoc formats a Category M JSON payload into DeclarativeFormattedDoc.

func FormatWave3SecurityIntelTextDoc added in v2.8.34

func FormatWave3SecurityIntelTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3SecurityIntelTextDoc formats a Category M text/CSV/STIX/RSS payload into DeclarativeFormattedDoc.

func FormatWave3SocialCreatorJSONDoc added in v2.8.34

func FormatWave3SocialCreatorJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3SocialCreatorJSONDoc formats a Category T JSON twin payload into DeclarativeFormattedDoc.

func FormatWave3StoreAddonsJSONDoc added in v2.8.34

func FormatWave3StoreAddonsJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3StoreAddonsJSONDoc formats a Category I Store Add-Ons JSON payload into DeclarativeFormattedDoc.

func FormatWave3TradeJSONDoc added in v2.8.34

func FormatWave3TradeJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3TradeJSONDoc formats a Category J JSON twin payload into DeclarativeFormattedDoc.

func FormatWave3TradeTextDoc added in v2.8.34

func FormatWave3TradeTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool)

FormatWave3TradeTextDoc formats a Category J XML/text twin payload (`ofac_sdn_xml`, `ustr_301_rss_xml`).

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.

func Wave3DevFormatWebCompatText added in v2.8.34

func Wave3DevFormatWebCompatText(rawBody, origURL string) (*DeclarativeFormattedDoc, bool)

Wave3DevFormatWebCompatText streams a bounded/truncated web-features/data.json prefix (or complete web-compat JSON payload) using json.NewDecoder, extracting top-level metadata and up to 25 feature entries without unmarshaling the full multi-megabyte JSON document.

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 Round2RunHTML added in v2.8.34

func Round2RunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Round2RunHTML executes a round-2 post-fetch HTML extractor. Universal modes return nil unless the platform fingerprint (or the Schema.org type) is present, so they never hijack unrelated pages.

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.

func Wave3CommunityRunHTML added in v2.8.34

func Wave3CommunityRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Wave3CommunityRunHTML executes a Category E Community HTML extractor and returns DeclarativePostFetchResult.

func Wave3CyclingComponentsRunHTML added in v2.8.34

func Wave3CyclingComponentsRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Wave3CyclingComponentsRunHTML executes a Category O1 HTML extractor and returns DeclarativePostFetchResult.

func Wave3CyclingOEMsRunHTML added in v2.8.34

func Wave3CyclingOEMsRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Wave3CyclingOEMsRunHTML executes a Category O2 HTML extractor and returns DeclarativePostFetchResult.

func Wave3DevInfraRunHTML added in v2.8.34

func Wave3DevInfraRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Wave3DevInfraRunHTML executes a Category N HTML extractor and returns DeclarativePostFetchResult.

func Wave3EduRunHTML added in v2.8.34

func Wave3EduRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Wave3EduRunHTML executes a Category B Education HTML extractor and returns DeclarativePostFetchResult.

func Wave3FinanceRunHTML added in v2.8.34

func Wave3FinanceRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Wave3FinanceRunHTML executes a Category S HTML extractor and returns DeclarativePostFetchResult.

func Wave3GTINIdentityRunHTML added in v2.8.34

func Wave3GTINIdentityRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Wave3GTINIdentityRunHTML executes a Category Q HTML extractor and returns DeclarativePostFetchResult.

func Wave3JobsPublicRunHTML added in v2.8.34

func Wave3JobsPublicRunHTML(mode string, rawHTML string, baseURL string, extractorID string) *DeclarativePostFetchResult

Wave3JobsPublicRunHTML executes a Category C HTML extractor and returns a DeclarativePostFetchResult.

func Wave3MediaLyricsRunHTML added in v2.8.34

func Wave3MediaLyricsRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Wave3MediaLyricsRunHTML executes a Category R HTML extractor and returns DeclarativePostFetchResult.

func Wave3PropRestIRRunHTML added in v2.8.34

func Wave3PropRestIRRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Wave3PropRestIRRunHTML executes a Category F/G/H HTML extractor and returns DeclarativePostFetchResult.

func Wave3RegulatorsHealthRunHTML added in v2.8.34

func Wave3RegulatorsHealthRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Wave3RegulatorsHealthRunHTML executes a Category K Part 2 HTML extractor (#289-#300).

func Wave3ResaleRunHTML added in v2.8.34

func Wave3ResaleRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Wave3ResaleRunHTML executes a Category P HTML extractor and returns DeclarativePostFetchResult.

func Wave3SchemaRunHTML added in v2.8.34

func Wave3SchemaRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Wave3SchemaRunHTML executes a Category D Universal Schema.org HTML extractor.

func Wave3ScholarlyRunHTML added in v2.8.34

func Wave3ScholarlyRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Wave3ScholarlyRunHTML executes a Category L HTML extractor and returns DeclarativePostFetchResult.

func Wave3SecurityIntelRunHTML added in v2.8.34

func Wave3SecurityIntelRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Wave3SecurityIntelRunHTML executes a Category M HTML extractor and returns DeclarativePostFetchResult.

func Wave3SocialCreatorRunHTML added in v2.8.34

func Wave3SocialCreatorRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Wave3SocialCreatorRunHTML executes a Category T HTML extractor and returns DeclarativePostFetchResult.

func Wave3StoreAddonsRunHTML added in v2.8.34

func Wave3StoreAddonsRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Wave3StoreAddonsRunHTML executes a Category I Store Add-Ons HTML extractor (#263-#270). Companion-only modes (#265, #266) always return nil so they never preempt shopify_html.

func Wave3TradeRunHTML added in v2.8.34

func Wave3TradeRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult

Wave3TradeRunHTML executes a Category J HTML extractor and returns 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

type DeclarativeReplaceSpec struct {
	From string `json:"from"`
	To   string `json:"to"`
}

DeclarativeReplaceSpec defines a literal substring replacement.

type DeclarativeResolveOptions added in v2.8.29

type DeclarativeResolveOptions struct {
	AllowPageKeyTwins *bool
}

DeclarativeResolveOptions controls twin resolution behavior (e.g. `page-key` twins default ON when nil).

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` twins enabled by default unless explicitly disabled via DeclarativeResolveOptions{AllowPageKeyTwins: BoolPtr(false)}).

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) AllowCrossOriginRedirects added in v2.8.34

func (m *DeclarativeTwinMatch) AllowCrossOriginRedirects() bool

AllowCrossOriginRedirects reports whether this twin route is vetted to follow a trusted cross-origin CDN/S3 redirect.

func (*DeclarativeTwinMatch) AllowTruncatedStream added in v2.8.34

func (m *DeclarativeTwinMatch) AllowTruncatedStream() bool

AllowTruncatedStream reports whether a bounded streaming prefix (`maxBytes < 4 MiB` for text twins, or `cms-price-transparency` / `web-compat-data`) may be formatted when truncated.

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

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"`
	UnhydratedCSRShell       bool             `json:"unhydratedCsrShell,omitempty"`
	Authoritative            bool             `json:"authoritative,omitempty"`
	SkipOverlayEnrichment    bool             `json:"skipOverlayEnrichment,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

func ParseHTMLDoc(rawHTML string, maxChars int) *HTMLDoc

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

func (n *HTMLNode) Attr(name string) (string, bool)

Attr returns the value of attribute name (case-insensitive) and whether it exists on this element.

func (*HTMLNode) AttrOf added in v2.8.17

func (n *HTMLNode) AttrOf(subSelector, name string) string

AttrOf returns First(subSelector).AttrOrEmpty(name), or "" if absent.

func (*HTMLNode) AttrOrEmpty added in v2.8.17

func (n *HTMLNode) AttrOrEmpty(name string) string

AttrOrEmpty returns the value of attribute name (case-insensitive), or "" if absent.

func (*HTMLNode) DLMap added in v2.8.17

func (n *HTMLNode) DLMap(subSelector ...string) map[string]string

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

func (n *HTMLNode) First(selector string) *HTMLNode

First returns the first matching descendant HTMLNode, or nil if none match.

func (*HTMLNode) HTML added in v2.8.17

func (n *HTMLNode) HTML(subSelector ...string) string

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

func (n *HTMLNode) IsDescendantOf(ancestor *HTMLNode) bool

IsDescendantOf reports whether n is a strict descendant of ancestor within the same parsed DOM.

func (*HTMLNode) NodeKey added in v2.8.17

func (n *HTMLNode) NodeKey() any

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) OuterHTML added in v2.8.17

func (n *HTMLNode) OuterHTML() string

OuterHTML returns serialized outer HTML of this node.

func (*HTMLNode) SameNode added in v2.8.17

func (n *HTMLNode) SameNode(other *HTMLNode) bool

SameNode reports whether n and other wrap the same underlying DOM node.

func (*HTMLNode) Select added in v2.8.17

func (n *HTMLNode) Select(selector string, limit int) []*HTMLNode

Select returns up to limit matching descendant HTMLNodes in DOM document order (capped at 5,000).

func (*HTMLNode) TableRows added in v2.8.17

func (n *HTMLNode) TableRows(subSelector ...string) [][]string

TableRows extracts a 2D slice of cleaned cell text from <tr> -> <th>/<td> rows.

func (*HTMLNode) Tag added in v2.8.17

func (n *HTMLNode) Tag() string

Tag returns the lowercase HTML tag name for element nodes, or "" for the document root.

func (*HTMLNode) Text added in v2.8.17

func (n *HTMLNode) Text(subSelector ...string) string

Text returns clean text content (inserting spaces at block boundaries, stripping script/style/noscript/template/svg/xmp/plaintext/textarea, collapsing whitespace, and trimming). When subSelector is provided, reads from First(subSelector[0]).

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

type ImageInfo struct {
	URL string `json:"url"`
	Alt string `json:"alt,omitempty"`
}

ImageInfo describes an image discovered on a page.

func ExtractMarkdownLinksAndImages added in v2.8.17

func ExtractMarkdownLinksAndImages(md, baseURL string) (links []string, images []ImageInfo)

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

func (*LlmsDocument) MatchPage

func (doc *LlmsDocument) MatchPage(pageURL string) (matched *LlmsLink, companionMdURL string, related []LlmsLink)

MatchPage finds any exact orcompanion `.md` entry in `doc` corresponding to `pageURL`, plus up to 8 same-section related links.

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 NostrNIP01Plan added in v2.8.34

type NostrNIP01Plan struct {
	Enabled    bool   `json:"enabled"`
	OK         bool   `json:"ok"`
	Reason     string `json:"reason,omitempty"`
	NIP11URL   string `json:"nip11Url,omitempty"`
	WSSURL     string `json:"wssUrl,omitempty"`
	SubID      string `json:"subId,omitempty"`
	ReqFrame   string `json:"reqFrame,omitempty"`
	CloseFrame string `json:"closeFrame,omitempty"`
	MaxEvents  int    `json:"maxEvents,omitempty"`
}

NostrNIP01Plan holds the Go-validated read-only NIP-01 REQ/CLOSE frames and relay endpoints for a Nostr URL.

func PrepareNostrNIP01 added in v2.8.34

func PrepareNostrNIP01(rawURL, selfHost, subID string, maxEvents int) NostrNIP01Plan

PrepareNostrNIP01 parses and validates a Nostr relay URL for bounded read-only NIP-01 WebSocket REQ querying.

type OfficialAPIExtraInput added in v2.8.34

type OfficialAPIExtraInput struct {
	Provider      string            `json:"provider"`
	TargetURL     string            `json:"targetUrl,omitempty"`
	CallerAPIKeys map[string]string `json:"callerApiKeys,omitempty"`
	CallerHeaders map[string]string `json:"callerHeaders,omitempty"`
	Env           map[string]string `json:"env,omitempty"`
	BaseHeaders   map[string]string `json:"baseHeaders,omitempty"`
	ExtraHeaders  map[string]string `json:"extraHeaders,omitempty"`
	RandomNonce   string            `json:"randomNonce,omitempty"`
}

OfficialAPIExtraInput carries caller/env metadata to ResolveOfficialAPIExtraHeadersAndSecrets.

type OfficialAPIExtraOutput added in v2.8.34

type OfficialAPIExtraOutput struct {
	ExtraHeaders          map[string]string `json:"extraHeaders,omitempty"`
	ExtraSecrets          []string          `json:"extraSecrets,omitempty"`
	PodcastIndexAPISecret string            `json:"podcastIndexApiSecret,omitempty"`
}

OfficialAPIExtraOutput returns computed extra headers, extra secrets to scrub, and optional companion secret for SHA-1 signing.

type OfficialAPIKeyInjection added in v2.8.34

type OfficialAPIKeyInjection struct {
	Kind   string `json:"kind"`
	Name   string `json:"name"`
	Prefix string `json:"prefix,omitempty"`
}

OfficialAPIKeyInjection describes how an official API key is injected into an origin-pinned request.

type OfficialAPIKeyProviderSpec added in v2.8.34

type OfficialAPIKeyProviderSpec struct {
	Provider         string                   `json:"provider"`
	EnvKeyName       string                   `json:"envKeyName"`
	VaultProvider    string                   `json:"vaultProvider"`
	Aliases          []string                 `json:"aliases,omitempty"`
	FallbackDemoKey  string                   `json:"fallbackDemoKey,omitempty"`
	DefaultInjection *OfficialAPIKeyInjection `json:"defaultInjection,omitempty"`
}

OfficialAPIKeyProviderSpec describes the metadata, env var, vault slug, aliases, and auth injection for an official API provider.

func ResolveOfficialAPIProviderSpec added in v2.8.34

func ResolveOfficialAPIProviderSpec(providerOrAdapter string) OfficialAPIKeyProviderSpec

ResolveOfficialAPIProviderSpec returns the canonical OfficialAPIKeyProviderSpec for a provider or adapter slug.

func ResolveOfficialAPIProviderSpecForURL added in v2.8.34

func ResolveOfficialAPIProviderSpecForURL(providerOrAdapter, targetURL string) OfficialAPIKeyProviderSpec

ResolveOfficialAPIProviderSpecForURL refines ResolveOfficialAPIProviderSpec for multi-host providers based on targetURL's host.

type OfficialAPIOutboundInput added in v2.8.34

type OfficialAPIOutboundInput struct {
	URL          string                  `json:"url"`
	PinnedOrigin string                  `json:"pinnedOrigin"`
	APIKey       string                  `json:"apiKey"`
	Injection    OfficialAPIKeyInjection `json:"injection"`
	Method       string                  `json:"method,omitempty"`
	ContentType  string                  `json:"contentType,omitempty"`
	Accept       string                  `json:"accept,omitempty"`
	UserAgent    string                  `json:"userAgent,omitempty"`
	ExtraHeaders map[string]string       `json:"extraHeaders,omitempty"`
}

OfficialAPIOutboundInput describes parameters for constructing an authenticated outbound official API URL & header map.

type OfficialAPIOutboundOutput added in v2.8.34

type OfficialAPIOutboundOutput struct {
	OK          bool              `json:"ok"`
	OutboundURL string            `json:"outboundUrl,omitempty"`
	Headers     map[string]string `json:"headers,omitempty"`
}

OfficialAPIOutboundOutput returns the origin-pinned outbound URL and sanitized request headers.

func BuildOfficialAPIOutboundRequest added in v2.8.34

func BuildOfficialAPIOutboundRequest(in OfficialAPIOutboundInput) OfficialAPIOutboundOutput

BuildOfficialAPIOutboundRequest builds the outbound URL (with query-key injection when configured) and headers while enforcing origin pinning.

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&lt;void&gt;</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, `page-key` adapters (`algolia`, `bazaarvoice`, `powerreviews`, `yext-locator`, etc.) are NEVER scanned or returned. Domain-specific adapters (and explicit `arc-xp` / `smartetailing` / `gs1-us-datahub` / `recharge-bold-subscriptions` / `suspension-cockpit-compat`) suppress companion twin discovery so generic platform twins (e.g. `aem`, `shopify-storefront-graphql`) do not preempt them.

type PlatformTwinDiscoveryInput added in v2.8.29

type PlatformTwinDiscoveryInput struct {
	PageURL             string            `json:"pageUrl"`
	AllowPageKeyTwins   *bool             `json:"allowPageKeyTwins,omitempty"`
	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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL